SpringMVC 登陆判断
struts2:extends ActionSupport
@Override
public String execute() throws Exception {
User user = userService.getUser(loginName);
if (user==null) {
addFieldError("loginName",getText("invalid.loginname")); 用户名错误
return INPUT;
}
else if (!user.getPassword().equals(password)) {
addFieldError("password", getText("invalid.password")); 密码错误
return INPUT;
}
else {
sessionMap.put("user",user);
return SUCCESS;
}
SpringMVC:啥都没继承
把对象写在方法的参数列表中,spring会自动创建这个对象
//建议不用实体类接受请求,建议单独定义一个表单类 @RequestMapping(value="login",method=RequestMethod.POST) public String doLogin2( @ModelAttribute("form")LoginForm loginForm,//这样转发回表单页面的时候会自动回填数据 BindingResult result ){ if(!loginForm.getLoginName().equals("admin")){ result.rejectValue("loginName","form", "用户名输入错误"); //reject是驳回的意思 }else if (!loginForm.getPassword().equals("123456")) { result.rejectValue("password","form", "密码输入错误"); } //如果添加了错误信息,则转发回登陆表单页面 if(result.hasErrors()){ return "login"; } System.out.println("登录名:"+loginForm.getLoginName()); System.out.println("密码:"+loginForm.getPassword()); return "hello"; }
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>SpringMVC</title> <link href="style/style.css" rel="stylesheet" type="text/css"/> </head> <body> <!-- 对象要和表单绑定,把对象传递过来 --> <form:form action="" method="post" commandName="form"> <tr> <td>登录名:</td> <td> <form:input path="loginName" /> </td> </tr> <tr> <td></td> <td> <form:errors path="loginName"/> </td> </tr> <tr> <td>密码:</td> <td> <form:password path="password" /> </td> </tr> <tr> <td></td> <td> <form:errors path="password"/> </td> </tr> <tr> <td></td> <td> <input type="submit" value="登陆"/> </td> </tr> </form:form> </body> </html>