在Spring中添加Bean
2007-12-23 12:33:56 来源:WEB开发网在上次的MVC基础上,我们准备给Controller增加Model,为此创建一个Account Bean Class:
public class Account implements java.io.Serializable {
PRivate String username;
private String passWord;
public String getUsername() { return this.username; }
public void setUsername(String username) { this.username = username; }
public String getPassword() { return this.password; }
public void setPassword(String password) { this.password = password; }
}
然后修改SpringappController:
public class SpringappController implements Controller {
private Account account;
public Account getUserAccount() { return this.account; }
public void setUserAccount(Account account) { this.account = account; }
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
return new ModelAndView("view.jsp", "model", account.getUsername());
}
}
为了向SpringappController注入Bean,我们修改配置文件springapp-servlet.xml:
<!-- 申明一个Account Bean -->
<bean id="adminAccount" class="Account">
<property name="username">
<value>administrator</value>
</property>
<property name="password">
<value>1234567</value>
</property>
</bean>
<bean id="springappController" class="SpringappController">
<!-- 注入到Controller -->
<property name="userAccount">
<ref bean="adminAccount" />
</property>
</bean>
OK,运行Ant,然后启动Tomcat,结果输出:
Result: administrator
注入成功!但是在Controller中放一个Account肯定是不合逻辑的,我们准备做一个用户登录功能,为此创建一个AccountManager Bean:
public class AccountManager implements java.io.Serializable {
Account getAccount(String username, String password) {
// TODO...
Account account = new Account();
account.setUsername(username);
account.setPassword(password);
return account;
}
}
然后把SpringappController改为:
public class SpringappController implements Controller {
private AccountManager manager;
public AccountManager getManager() { return this.manager; }
public void setManager(AccountManager manager) { this.manager = manager; }
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String username = request.getParameter("username");
String password = request.getParameter("password");
return new ModelAndView("view.jsp", "model",
manager.getAccount(username, password).getUsername());
}
}
修改springapp-servlet.xml:
<bean id="accountManager" class="AccountManager" />
<bean id="springappController" class="SpringappController">
<property name="manager">
<ref bean="accountManager" />
</property>
</bean>
编译,运行,输入:http://localhost:8080/springmvc/hello.c?username=xuefeng&password=1234
结果显示:
Result: xuefeng
OK,现在只要创建一个Html form,Post到Controller然后在AccountManager中验证Username和Password就可以了。
(出处:http://www.cncms.com)