1.REST特点
(1).URI
传统:http://localhost:8080/user/user_show.do?id=1
REST:http://localhost:8080/user/user/1
(2).Http请求
get select
post insert
put update
delete delete
(3).无状态
没有session
2.REST例子
下面的例子中有验证、异常处理、中文编码过滤器、静态资源文件处理
(1).导入jar包
spring官方下载的dist目录中的所有文件
commons-logging-1.1.1.jar
slf4j-api-1.7.3.jar
hibernate-validator-4.0.2.GA.jar
validation-api-1.0.0.GA.jar
(2).web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<filter>
<filter-name>CharacterEncodingFilter</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>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>user</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>user</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
(3).user-servlet.xml,和web.xml在同级目录中
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-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/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<mvc:annotation-driven />
<context:component-scan base-package="com.artistninth.controller"/>
<mvc:resources location="/resource/" mapping="/resource/**"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
(4).User.java
package com.artistninth.vo;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;
public class User {
private String username;
private String nickname;
private String password;
private String email;
public User() {
super();
// TODO Auto-generated constructor stub
}
public User(String username, String nickname, String password, String email) {
super();
this.username = username;
this.nickname = nickname;
this.password = password;
this.email = email;
}
@NotEmpty(message="用户名不能为空")
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
@NotEmpty(message="密码不能为空")
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Email(message="邮箱格式错误")
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
(5).UserException.java
package com.artistninth.vo;
public class UserException extends RuntimeException {
public UserException() {
super();
// TODO Auto-generated constructor stub
}
public UserException(String arg0, Throwable arg1, boolean arg2, boolean arg3) {
super(arg0, arg1, arg2, arg3);
// TODO Auto-generated constructor stub
}
public UserException(String arg0, Throwable arg1) {
super(arg0, arg1);
// TODO Auto-generated constructor stub
}
public UserException(String arg0) {
super(arg0);
// TODO Auto-generated constructor stub
}
public UserException(Throwable arg0) {
super(arg0);
// TODO Auto-generated constructor stub
}
}
(6).UserController.java
package com.artistninth.controller;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import com.artistninth.vo.User;
import com.artistninth.vo.UserException;
@Controller
@RequestMapping("/user")
@SessionAttributes(value = "loginUser")
public class UserController {
private static Map<String, User> users = new HashMap<String, User>();
public UserController() {
users.put("ldh", new User("ldh", "刘德华", "123", "123@abc.com"));
users.put("zxy", new User("zxy", "张学友", "123", "123@abc.com"));
users.put("gfc", new User("gfc", "郭富成", "123", "123@abc.com"));
users.put("lm", new User("lm", "黎明", "123", "123@abc.com"));
}
@RequestMapping("/users")
public String list(Model model) {
model.addAttribute("users", users);
return "user/list";
}
@RequestMapping(value = "/add", method = RequestMethod.GET)
public String get(Model model) {
model.addAttribute(new User());
return "user/add";
}
@RequestMapping(value = "/add", method = RequestMethod.POST)
public String get(@Valid User user, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return "user/add";
}
users.put(user.getUsername(), user);
return InternalResourceViewResolver.REDIRECT_URL_PREFIX + "/user/users";
}
@RequestMapping(value = "/{username}", method = RequestMethod.GET)
public String show(@PathVariable String username, Model model) {
model.addAttribute(users.get(username));
return "user/show";
}
@RequestMapping(value = "/{username}/update", method = RequestMethod.GET)
public String update(@PathVariable String username, Model model) {
model.addAttribute(users.get(username));
return "user/update";
}
@RequestMapping(value = "/{username}/update", method = RequestMethod.POST)
public String update(@PathVariable String username, @Valid User user,
Model model, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return "user/update";
}
users.put(username, user);
return InternalResourceViewResolver.REDIRECT_URL_PREFIX + "/user/users";
}
@RequestMapping(value = "/{username}/delete", method = RequestMethod.GET)
public String delete(@PathVariable String username) {
users.remove(username);
return InternalResourceViewResolver.REDIRECT_URL_PREFIX + "/user/users";
}
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String login() {
return "user/login";
}
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String login(String username, String password,Model model) {
if (!users.containsKey(username)) {
throw new UserException("用户名不存在");
}
if (!password.equals(users.get(username).getPassword())) {
throw new UserException("密码错误");
}
model.addAttribute("loginUser", users.get(username));
return InternalResourceViewResolver.REDIRECT_URL_PREFIX + "/user/users";
}
@ExceptionHandler(value={UserException.class})
public String handlerException(Exception ex,HttpServletRequest request){
request.setAttribute("exception", ex);
return "error";
}
}
(7).main.css,在WebContent/resource/css中
*{
font-weight:bold;
}
(8).error.jsp,在WebContent/WEB-INF/jsp中
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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>
${exception.message }
</body>
</html>
(9).add.jsp,在WebContent/WEB-INFO/jsp/user中
<%@ 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>Insert title here</title>
</head>
<body>
<sf:form method="post" modelAttribute="user">
username:<sf:input path="username"/><sf:errors path="username"/><br/>
nickname:<sf:input path="nickname"/><br/>
password:<sf:password path="password"/><sf:errors path="password"/><br/>
email:<sf:input path="email"/><sf:errors path="email"/><br/>
<input type="submit"/>
</sf:form>
</body>
</html>
(10).list.jsp,在WebContent/WEB-INFO/jsp/user中
<%@ 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>
<link rel="stylesheet" type="text/css" href="<%=request.getContextPath() %>/resource/css/main.css">
</head>
<body>
<h1>当前登录用户:${loginUser.username }</h1>
<a href="add">添加</a><br/>
<c:forEach items="${users }" var="user">
<a href="${user.value.username }">${user.value.username }</a>--${user.value.nickname }--${user.value.email }
<a href="${user.value.username }/update">修改</a>
<a href="${user.value.username }/delete">删除</a>
<br/>
</c:forEach>
</body>
</html>
(11).login.jsp,在WebContent/WEB-INFO/jsp/user中
<%@ 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>Insert title here</title>
</head>
<body>
<form method="post" action="login">
username:<input type="text" name="username"/><br/>
password:<input type="password" name="password"/><br/>
<input type="submit"/>
</form>
</body>
</html>
(12).show.jsp,在WebContent/WEB-INFO/jsp/user中
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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>
${user.username }<br/>
${user.email }<br/>
</body>
</html>
(13).update.jsp,在WebContent/WEB-INFO/jsp/user中
<%@ 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>Insert title here</title>
</head>
<body>
<sf:form method="post" modelAttribute="user">
username:<sf:input path="username" readonly="true"/><sf:errors path="username"/><br/>
nickname:<sf:input path="nickname"/><br/>
password:<sf:password path="password"/><sf:errors path="password"/><br/>
email:<sf:input path="email"/><sf:errors path="email"/><br/>
<input type="submit"/>
</sf:form>
</body>
</html>