REST風格與傳統風格比較
查詢用戶
傳統方式 /user_detail?id=120
Rest風格 /user/120
刪除用戶
傳統方式 /user_delete?id=123
Rest風格 /user/123/delete
修改用戶
傳統方式 /user_update?id=123
Rest風格 /user/123/update
獲取列表
傳統方式 /user_list
Rest風格 /users 或者 /user/users
JSR303
JSR-303 是JAVA EE 6 中的一項子規范,叫做Bean Validation,官方參考實現是Hibernate Validator。
此實現與Hibernate ORM 沒有任何關系。JSR 303 用於對Java Bean 中的字段的值進行驗證。
Bean validation 下載地址: http://download.oracle.com/otndocs/jcp/bean_validation-1_1_0_cr1-pfd-spec/index.html
實例演示
實體類
package com.springmvc.demo.entity; import javax.validation.constraints.NotNull; import javax.validation.constraints.Pattern; import javax.validation.constraints.Size;
public class User { @NotNull(message="用戶名不能為空") private String username; @NotNull(message="密碼不能為空") @Size(min=4,max=10,message="密碼長度必須在4-10的長度") private String password; @Pattern(regexp="^[a-zA-Z0-9_]+@[a-zA-Z0-9_]+.[a-zA-Z]{2,5}?((.cn)|(.jp))?$", message="郵箱格式不正確") private String email; public User(){} public User(String username, String password, String email) { super(); this.username = username; this.password = password; this.email = email; } //getter and setter }
web.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<!-- 配置字符過濾器,必須在OpenSessionInViewerFilter之前 -->
<filter>
<filter-name>CharacterFilter</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>CharacterFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>dispatcher</servlet-name> <!-- 此處用的是dispacter,所以同目錄下的想xml文件名應該為dispacter-servlet.xml -->
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
dispatcher-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd ">
<!-- 指定使用注解方式配置,配置自動掃描的包名, base-package指定自己應用中控制器所在的包目錄 <context:component-scan/> 掃描指定的包中的類上的注解,常用的注解有: @Controller 聲明Action組件 @Service 聲明Service組件 @Service("myMovieLister") @Repository 聲明Dao組件 @Component 泛指組件, 當不好歸類時. @RequestMapping("/menu") 請求映射 @Resource用於注入,( j2ee提供的 ) 默認按名稱裝配, @Resource(name="beanName") @Autowired用於注入,(srping提供的) 默認按類型裝配 @Transactional(rollbackFor={Exception.class}) 事務管理 @ResponseBody @Scope("prototype")設定bean的作用域 -->
<context:component-scan base-package="com.springmvc.demo.controller" />
<!-- 默認的注解映射的支持 -->
<!-- JSR-303 support will be detected on classpath and enabled automatically -->
<mvc:annotation-driven/>
<!-- http://static.springsource.org/spring/docs/3.0.0.RC3/reference/html/ch05s07.html --><!-- 配置視圖解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 配置視圖層 使用jstl標簽 -->
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
<!-- 定義視圖前綴格式 -->
<property name="prefix" value="/WEB-INF/jsp/" />
<!-- 定義視圖后綴格式 -->
<property name="suffix" value=".jsp" />
</bean>
</beans>
控制器
package com.springmvc.demo.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.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.springmvc.demo.entity.User;
@Controller @RequestMapping(value="/user") public class UserController { private Map<String,User> users = new HashMap<String, User>(); public UserController(){ users.put("suruonian", new User("suruonian","suruonian","suruonian@demo.com")); users.put("linyunxi", new User("linyunxi","linyunxi","linyunxi@163.com")); users.put("dennisit", new User("dennisit","dennisit","dennisit@163.com")); users.put("moshaobai", new User("moshaobai","bing_he","1325103287@qq.com")); } /** * * * Description: 構建REST風格 /user/users的GET請求時才執行該方法的操作RequestMethod.GET表示 * 只處理GET請求 * @param model 用於上下文參數傳遞 * @return 視圖頁面 user/list 結合user-servlet.xml中配置的視圖模型匹配視圖頁面 * 實例中方法返回表示/WEB-INF/jsp/user/list.jsp頁面 * */ @RequestMapping(value="/users",method=RequestMethod.GET) public String list(Model model){ model.addAttribute("users", users); return "user/list"; } /** * * * Description: 鏈接到頁面時是GET請求,執行該方法 <a href="add">添加</a> * @return 返回給用戶添加頁面 * */ @RequestMapping(value="/add",method=RequestMethod.GET) public String add(Model model){ model.addAttribute("user",new User()); //開啟ModelDriven 跳轉到增加頁面時使用該Model
return "user/add"; } /** * * Description: 添加操作 請求/user/add form表單提交時使用的post請求調用該方法 * @param user 添加的User對象 * @param br 驗證綁定 * @return 視圖頁面 * 添加成功 請求重定向redirect:/user/users 表示執行操作結束后請求定向為/user/users * 添加失敗 頁面轉到/WEB-INF/jsp/add.jsp 這里有驗證綁定,將在視圖頁面展示驗證錯誤信息 * */ @RequestMapping(value="/add",method=RequestMethod.POST) public String add(@Validated User user,BindingResult br){ //需要說明的是BindingResult形參一定要跟@Validated修飾的形參后面寫驗證
if(br.hasErrors()){ //如果有錯誤,直接跳轉到添加視圖
return "user/add"; //服務端跳轉 該跳轉會自動在前面增加 forward
} users.put(user.getUsername(), user); return "redirect:/user/users"; //客戶端跳轉 使用 redirect
} /** * * * Description: 查看操作 根據用戶名查看 REST風格: /detail/查看的用戶名 * @param username 帶查看的用戶名@PathVariable 修飾username 表示用請求路徑中的username作為 形參 * @param model 攜帶數據的Model * @return 視圖頁面 /WEB-INF/jsp/user/detail.jsp頁面 * */ @RequestMapping(value="/{username}",method=RequestMethod.GET) public String detail(@PathVariable String username, Model model){ System.out.println("獲取到傳入的參數值為:" + username); model.addAttribute("user", users.get(username)); return "user/detail"; } /** * * * Description: 預更新操作根據用戶名查詢用戶信息 然后數據交給攜帶體 展示到視圖 REST風格: /更新的用戶的用戶名/update * @param username @PathVariable修飾 表示形參同URL中的請求參數 * @param model 攜帶數據的Model * @return 視圖頁面/WEB-INF/jsp/user/update頁面 * */ @RequestMapping(value="/{username}/update",method=RequestMethod.GET) public String update(@PathVariable String username, Model model){ System.out.println("獲取到傳入的參數值為:" + username); model.addAttribute(users.get(username)); return "user/update"; } /** * * * Description: 真正更新的操作 REST風格: /更新的用戶的用戶名/update * @param username 帶更新的用戶的用戶名 * @param user 帶更新的用戶的信息對象 @Validated修飾表示信息需要被驗證 * @param br 驗證信息綁定對象 必須緊跟在待驗證的信息形參后面 * @return 視圖頁面 * 更新成功 請求重定向 /user/users * 更新失敗 轉到/WEB-INF/jsp/user/update.jsp頁面 * */ @RequestMapping(value="/{username}/update",method=RequestMethod.POST) public String update(@PathVariable String username, @Validated User user,BindingResult br){ if(br.hasErrors()){ //如果有錯誤,直接跳轉到修改視圖
return "user/update"; } users.put(username, user); return "redirect:/user/users"; } /** * * * Description: 刪除操作 REST風格:/刪除的用戶名/delete * @param username 刪除的用戶名 類似表主鍵,可以標記到整個記錄信息 * @return 視圖頁面 * 請求重定向到 /user/users * */ @RequestMapping(value="/{username}/delete",method=RequestMethod.GET) public String delete(@PathVariable String username){ System.out.println("獲取到傳入的參數值為:" + username); users.remove(username); return "redirect:/user/users"; } }
視圖層/WEB-INF/jsp/user/下的list.jsp,add.jsp,detail.jsp,update.jsp文件
list.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path; %>
<!DOCTYPE HTML>
<html>
<head>
<base href="<%=basePath%>">
<title><%=basePath%></title>
</head>
<body>
<h2>用戶信息展示</h2> <p><a href="<%=basePath %>/user/add">添加信息</a></p>
<c:forEach items="${users}" var="usermap"> 姓名: <a href="<%=basePath %>/user/${usermap.value.username }">${usermap.value.username} </a> 密碼: ${usermap.value.password } 郵箱: ${usermap.value.email } <a href="<%=basePath %>/user/${usermap.value.username }/update">修改</a>
<a href="<%=basePath %>/user/${usermap.value.username }/delete">刪除</a>
<br/>
</c:forEach>
</body>
</html>
add.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="sf" uri="http://www.springframework.org/tags/form" %>
<%
String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %>
<!DOCTYPE HTML>
<html>
<head>
<base href="<%=basePath%>">
<title><%=basePath%></title>
</head>
<body>
<h2>增加用戶信息頁面</h2> <br>
<!-- 此時沒有寫action,直接提交會提交給/add -->
<sf:form method="post" modelAttribute="user"> 姓名:<sf:input path="username"/> <sf:errors path="username" /> <br/> 密碼:<sf:password path="password"/> <sf:errors path="password" /> <br/> 郵箱:<sf:input path="email"/> <sf:errors path="email" /> <br/>
<input type="submit" value="添加" />
</sf:form>
</body>
</html>
detail.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path; %>
<!DOCTYPE HTML>
<html>
<head>
<base href="<%=basePath%>">
<title><%=basePath%></title>
</head>
<body>
<h2>用戶詳細信息頁面</h2> <br> 姓名: ${user.username} <br> 密碼: ${user.password } <br> 郵箱: ${user.email } <br/>
<a href="<%=basePath %>/user/users">返回用戶列表</a>
</body>
</html>
update.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="sf" uri="http://www.springframework.org/tags/form" %>
<%
String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path; %>
<!DOCTYPE HTML>
<html>
<head>
<base href="<%=basePath%>">
<title><%=basePath%></title>
</head>
<body>
<h2>修改用戶信息頁面</h2> <br>
<!-- 此時沒有寫action,直接提交會提交給/update -->
<sf:form method="post" modelAttribute="user"> 姓名:<sf:input path="username"/> <sf:errors path="username" /> <br/> 密碼:<sf:password path="password"/> <sf:errors path="password" /> <br/> 郵箱:<sf:input path="email"/> <sf:errors path="email" /> <br/>
<input type="submit" value="修改" />
</sf:form>
</body>
</html>
轉載請注明出處:[http://www.cnblogs.com/dennisit/archive/2013/04/13/3019391.html]