在action的登陆方法中使用动态表单(属于ajax)
在配置文件中(struts-config.xml)
<form-beans>
<form-bean
name="loginForm"
type="org.apache.struts.action.DynaActionForm">
<form-property
name="userName" type="java.lang.String" />
<form-property
name="password" type="java.lang.String" />
</form-bean>
<action-mappings>
<action path="/login" type="org.springframework.web.struts.DelegatingActionProxy"
parameter="method" name="loginForm" validate="false" scope="request" input="/login.jsp">
<forward
name="index" path="/index.jsp"></forward>
</action>
……………………
</action-mappings>
在LoginAction.java中
public class LoginAction extends DispatchAction {
private UserManager
userManager;
public UserManager getUserManager() {
return userManager;
}
public void setUserManager(UserManager userManager) {
this.userManager = userManager;
}
/**
* 登陆验证后跳转到用户概况页面 (index.jsp)
*/
public ActionForward login(ActionMapping mapping,
ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
/** 获得动态表单**/
DynaActionForm
loginForm = (DynaActionForm)form;
/** 从表单中获得用户名**/
String
userName = (String)loginForm.get("userName");
/** 从表单中获得密码**/
String
password = (String)loginForm.get("password");
/** 通过用户名得到用户实体**/
User
user = userManager.getUserByName(userName);
/** 设置错误信息**/
ActionMessages
actionMessages = super.getErrors(request);
/** 判断用户是否存在**/
if(user == null){
/** 把错误信息添加到loginError中**/
actionMessages.add("loginError",new ActionMessage("MSG002"));
/** 保存错误信息并传递到登录页面中**/
super.saveErrors(request, actionMessages);
/** 跳转到登陆页面**/
return mapping.getInputForward();
}else{
/**判断密码是否错误 **/
if(!password.equals(user.getPassword())){
actionMessages.add("loginError",new ActionMessage("MSG002"));
super.saveErrors(request, actionMessages);
return mapping.getInputForward();
}
}
/** 把用户user存到session里**/
request.getSession().setAttribute("user",user);
//不能把user这个对象放在session里,应该放userId,不然外键太多容易是tomcat死了
/** 验证成功 跳转到用户概况页面**/
return mapping.findForward("index");
}
}
JSP页面上:动态表单的属性要和页面的属性名字相同!
<input name="userName" id="userName"
type="text" />
<input name="password" id="password"
type="password" />