1,创建实体类对象User
注意要导入 bean-validator.jar 包
package com.yangw.springmvc.entity;import org.hibernate.validator.constraints.Length; import org.hibernate.validator.constraints.NotEmpty; import org.hibernate.validator.constraints.Range; import org.springframework.format.annotation.NumberFormat; import org.springframework.format.annotation.NumberFormat.Style; /***
* 这里的这几个注解是用来验证字段的
*/ public class User {@NotEmpty(message="用户名不能为空")private String name;@Length(min=3 ,max=10,message="密码长度应该在3-10之间")private String password;@NumberFormat(style=Style.NUMBER)@Range(min=1,max=100,message="年龄应该在1-100之间")private int age;public User() {}public User(String name, String password, int age) {this.name = name;this.password = password;this.age = age;}/**
*get set方法这里略去
*/
}/*** Springmvc作服务器端验证更加简单* 它支持 JSR303 ,JSR是sun公司专门为java来更新的每一个标准* bean-validator.jar 是hibernate的jar包*/
2,在UserController类中完成 User的添加,显示所有内容
package com.yangw.springmvc.controller;import java.util.HashMap; import java.util.Map;import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod;import com.yangw.springmvc.entity.User;@Controller @RequestMapping(value="/user") public class UserController{private Map<String,User> users = new HashMap<String,User>();public UserController(){users.put("yangw", new User("yangw","123456",24));users.put("ganw", new User("ganw","123456",25));users.put("wangw", new User("wangw","123456",27));}//只有get请求才处理@RequestMapping(value="/users",method=RequestMethod.GET )public String list(Model model){model.addAttribute("users", users);return "user/list"; }// //链接到add页面时是GET请求,会访问这段代码 // @RequestMapping(value="/add",method=RequestMethod.GET ) // public String add(Model model){ // //这里需要提供一个User对象,因为添加的页面 // 第一种方式 model.addAttribute(new User());// //直接返回到add页面 // return "user/add"; // }//链接到add页面时是GET请求,会访问这段代码@RequestMapping(value="/add",method=RequestMethod.GET )public String add(@ModelAttribute(value="user") User user){//第二种提供一个User对象的方式,因为添加的页面return "user/add"; }//链接到add页面时是POST请求,会访问这段代码@RequestMapping(value="/add",method=RequestMethod.POST)//这个User是一个要被验证的对象,使用@Validated说明;//紧跟@Validated来写验证结果类,用BindingResult表示public String add(@Validated User user,BindingResult br){if(br.hasErrors()){//如果有错误,到add界面显示return "user/add";}users.put(user.getName(), user);return "redirect:/user/users"; }}
3,list.jsp页面
注意加入标签库的jar包 jsf-api.jar jsf-impl.jar jstl-1.2.jar
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!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>Insert title here</title> </head> <body><a href="add">添加用户</a><br/><c:forEach items="${users }" var="um" ><!-- 这里的um是一个个的 键值对 -->${um.key}---${um.value.name }---${um.value.password }----${um.value.age } <br/></c:forEach> </body> </html>
4,add.jsp页面
用到了springmvc的form表单
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%><%@ taglib prefix="sf" uri="http://www.springframework.org/tags/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>添加用户</title> </head> <body><!-- 设置为post请求,并且会自动将表单中的值添加到user中 --><!-- 此时没有写action,直接提交会提交给/add --><sf:form method="post" modelAttribute="user"><!-- sf:input path属性 中设置user对象的属性名 --><!--这个是服务器端验证 sf:errors 标签来输出 验证的错误信息 -->username:<sf:input path="name"/> <sf:errors path="name"/><br/>password:<sf:password path="password"/><sf:errors path="password"/><br/>age:<sf:input path="age"/><sf:errors path="age"/><br/><input type="submit" value="提交" /></sf:form> </body> </html>
5,web.xml增加编码过滤器
<filter><filter-name>characterEncoding</filter-name><filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class><init-param><param-name>encoding</param-name><param-value>UTF-8</param-value></init-param></filter><filter-mapping><filter-name>characterEncoding</filter-name><url-pattern>/*</url-pattern></filter-mapping>
6,显示一个用户详细信息
/*** @PathVariable:路径中的变量**/@RequestMapping(value="/{name}",method=RequestMethod.GET)public String show(@PathVariable String name,Model model){model.addAttribute(users.get(name));return "/user/show"; }
show.jsp页面
<body>username:${user.name }<br/>password:${user.password}<br/>age:${user.age }</body>
为list页面的增加超级链接
<c:forEach items="${users }" var="um" ><!-- 这里的um是一个个的 键值对 -->${um.key}---<a href="${um.value.name }">${um.value.name }</a>---${um.value.password }----${um.value.age } <br/></c:forEach>
7,用户的删除,更新
/*** 修改用户,获取原始用户页面信息**/@RequestMapping(value="/{name}/update",method=RequestMethod.GET)public String update(@PathVariable String name,Model model){model.addAttribute(users.get(name));return "/user/update"; }/*** 修改用户,对提交的数据进行更新操作**/@RequestMapping(value="/{name}/update",method=RequestMethod.POST)public String update(@Validated User user,BindingResult br){if(br.hasErrors()){//如果有错误,到add界面显示return "user/update";}users.put(user.getName(), user);return "redirect:/user/users"; }/*** 删除用户**/@RequestMapping(value="/{name}/delete",method=RequestMethod.GET)public String delete(@PathVariable String name){users.remove(name);return "redirect:/user/users"; }
update.jsp 和 list.jsp
update.jsp页面 与add.jsp其实一样<body><!-- 设置为post请求,并且会自动将表单中的值添加到user中 --><!-- 此时没有写action,直接提交会提交给/update --><sf:form method="post" modelAttribute="user">username:<sf:input path="name"/> <sf:errors path="name"/><br/>password:<sf:password path="password"/><sf:errors path="password"/><br/>age:<sf:input path="age"/><sf:errors path="age"/><br/><input type="submit" value="提交" /></sf:form> </body>
<c:forEach items="${users }" var="um" ><!-- 这里的um是一个个的 键值对 -->${um.key}---<a href="${um.value.name }">${um.value.name }</a>---${um.value.password }----${um.value.age } ----<a href="${um.value.name }/update">更新</a>---<a href="${um.value.name }/delete">删除</a><br/></c:forEach>