spring mvc: 密码框
以user为例,包含username, password字段.
user.java
public class User { private String username; private String password; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
UserController.java代码
import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import org.springframework.ui.ModelMap; @Controller public class UserController { @RequestMapping(value = "/user", method = RequestMethod.GET) public ModelAndView user() { return new ModelAndView("user_index", "command", new User()); } @RequestMapping(value = "/addUser", method = RequestMethod.POST) public String addUser(@ModelAttribute("SpringWeb")User user, ModelMap model) { model.addAttribute("username", user.getUsername()); model.addAttribute("password", user.getPassword()); return "user_add"; } }
这里的第一个服务方法user()
,我们已经在ModelAndView
对象中传递了一个名称为“command
”的空User
对象,因为如果在JSP文件中使用<form:form>
标签,spring框架需要一个名称为“command
”的对象。 所以当调用user()方法时,它返回user.jsp视图。
第二个服务方法addUser()
将根据URL => HelloWeb/addUser
上的POST方法请求时调用。根据提交的信息准备模型对象。 最后从服务方法返回“userlist
”视图,这将呈现userlist.jsp
视图。
user_index.jsp 的代码如下所示
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>添加user信息</title> </head> <body> <form:form method="post" action="/hello/addUser"> <table> <tr> <td><form:label path="username">姓名:</form:label></td> <td><form:input path="username" /></td> </tr> <tr> <td><form:label path="password">密码</form:label></td> <td><form:password path="password"/></td> </tr> <tr> <td colspan="2"> <input type="submit" value="提交表单"/> </td> </tr> </table> </form:form> </body> </html>
user_add.jsp
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <%@ page isELIgnored="false" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>用户信息显示</title> </head> <body> <table> <tr> <td>用户名</td> <td>${username}</td> </tr> <tr> <td>密码</td> <td>${password}</td> </tr> </table> </body> </html>
如图: