SpringMVC学习之REST

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" 
    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_3_0.xsd">
  <display-name></display-name>    
  
  
  <!-- 
          配置org.springframework.web.filter.HiddenHttpMethodFilter:可以把POST请求转为DELETE或POST请求
   -->
   <filter>
             <filter-name>HiddenHttpMethodFilter</filter-name>
               <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
   
   </filter>
   <filter-mapping>
               <filter-name>HiddenHttpMethodFilter</filter-name>
               <!-- 过滤所有请求 -->
               <url-pattern>/*</url-pattern>
   </filter-mapping>
   
   <!-- 配置DispatcherServlet -->
  
          <servlet>
              <servlet-name>springDispatcherServlet</servlet-name>
              <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
              <!-- 配置 DispatcherServlet的一个初始化参数:配置SpringMvc 配置文件的位置和名称-->
                   <init-param>
                      <param-name>contextConfigLocation</param-name>
                      <param-value>classpath:springmvc.xml</param-value>
              </init-param>
               <init-param>
                      <param-name>encoding</param-name>
                      <param-value>UTF-8</param-value>
              </init-param>
              <!-- 也可以不通过contextConfigLocation 来配置SpringMvc的配置文件,而使用默认的
                      默认的配置文件为:/WEB-INF/<servlet-name>-servlet.xml
                          /WEB-INF/springDispatcherServlet-servlet.xml
              -->
                  
          <!-- 设置启动 -->
          <load-on-startup>1</load-on-startup>
          </servlet>
          
          <servlet-mapping>
          <!-- 请求处理 -->
              <servlet-name>springDispatcherServlet</servlet-name>
              <!-- /:应答所有请求 -->
              <url-pattern>/</url-pattern>
          </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

springmvc.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:mvc="http://www.springframework.org/schema/mvc"
 
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 
       xmlns:context="http://www.springframework.org/schema/context" 
 
       xmlns:p="http://www.springframework.org/schema/p"
       
       xmlns:tx="http://www.springframework.org/schema/tx"
 
  xsi:schemaLocation="
 
              http://www.springframework.org/schema/beans    
 
                 http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
     
              http://www.springframework.org/schema/tx      
 
              http://www.springframework.org/schema/tx/spring-mvc-4.0.xsd
 
               http://www.springframework.org/schema/context
 
               http://www.springframework.org/schema/context/spring-context-4.0.xsd
               
               http://www.springframework.org/schema/mvc
               
               http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
 
               http://www.springframework.org/schema/aop
 
             http://www.springframework.org/schema/aop/spring-aop-4.0.xsd">
             
             <!-- 配置自定义扫描包 -->
             <context:component-scan base-package="como.springmvc.handlers"></context:component-scan>
             
           <!-- 配置视图解析器:如何把handler方法返回值解析为实际的物理视图 -->
           <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
           
           <!-- spring中加入jstl标签库 -->
           <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property>
                       <!-- 前缀 -->
                       <property name="prefix" value="/WEB-INF/views/"></property>
                       <!-- 后缀 -->
                       <property name="suffix" value=".jsp"></property>
           </bean>
           
           <!-- 配置视图BeanNameViewResolver解析器 ,使用视图名字解析视图-->
           <!-- 通过order属性定义视图解析器的优先级,值越少优先级越高 -->
         <bean class="org.springframework.web.servlet.view.BeanNameViewResolver">
                   <property name="order" value="100"></property>
           
           </bean> 
           
           <!-- 配置国际化资源文件 -->
           <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
                   <property name="basename" value="i18n"></property>
           
           </bean>
           <!-- 配置直接转发的页面 -->
           <!--  <mvc:view-controller path="/success" view-name="success" /> -->
           <!-- 在实际开发中通常都需要配置mvc:annotation-driven标签 
               因为加上mvc:view-controller后以前的@RequestMapping不起作用 -->
        <!--    <mvc:annotation-driven></mvc:annotation-driven> -->
           
         <mvc:default-servlet-handler/>
                <mvc:annotation-driven /> 
           </beans>
 

Employee.java

package como.springmvc.handlers.entity;

public class Employee {
        private Integer id;
        private String lastName;
        private String email;
        private int gender;
        private Department department;
        public Integer getId() {
            return id;
        }
        public void setId(int id) {
            this.id = id;
        }
        public String getLastName() {
            return lastName;
        }
        public void setLastName(String lastName) {
            this.lastName = lastName;
        }
        public String getEmail() {
            return email;
        }
        public void setEmail(String email) {
            this.email = email;
        }
        public int getGender() {
            return gender;
        }
        public void setGender(int gender) {
            this.gender = gender;
        }
        public Department getDepartment() {
            return department;
        }
        public void setDepartment(Department department) {
            this.department = department;
        }
        public Employee(Integer id, String lastName, String email, int gender,
                Department department) {
            super();
            this.id = id;
            this.lastName = lastName;
            this.email = email;
            this.gender = gender;
            this.department = department;
        }
        public Employee() {
            super();
        }
        
        
         
        
}

Department.java

package como.springmvc.handlers.entity;

public class Department {
        private Integer id;
        private String departementName;
        public Integer getId() {
            return id;
        }
        public void setId(Integer id) {
            this.id = id;
        }
        public String getDepartementName() {
            return departementName;
        }
        public void setDepartementName(String departementName) {
            this.departementName = departementName;
        }
        public Department(int id, String departementName) {
            super();
            this.id = id;
            this.departementName = departementName;
        }
        public Department() {
            super();
        }
        
        
}

DepartementDao.java

package como.springmvc.handlers.dao;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import org.springframework.stereotype.Repository;

import como.springmvc.handlers.entity.Department;

@Repository//@Repository用于标注数据访问组件,即DAO组件
public class DepartmentDao {
        private static Map<Integer,Department> departments = null;
        
        static{//静态数据,服务器重启恢复原始状态
            departments = new HashMap<Integer,Department>();
            departments.put(101, new Department(101,"D-AA"));
            departments.put(102, new Department(102,"D-BB"));
            departments.put(103, new Department(103,"D-CC"));
            departments.put(104, new Department(104,"D-DD"));
            departments.put(105, new Department(105,"D-EE"));
        }
        //获取全部的departments
        public Collection<Department> getDepartments(){
            return departments.values();
        }
        
        //获取指定id的department
        public Department getDepartment(Integer id){
            return departments.get(id);
        }
}

EmployeeDao.java

package como.springmvc.handlers.dao;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import como.springmvc.handlers.entity.Department;
import como.springmvc.handlers.entity.Employee;

@Repository
public class EmployeeDao {
        private static Map<Integer,Employee> employees = null;
        
        @Autowired
        private  DepartmentDao departmentDao;
        
        static{
            employees = new HashMap<Integer,Employee>();
            
            employees.put(1001, new Employee(1001,"E-AA","aa@123",1, new Department(101, "D-AA")));
            employees.put(1002, new Employee(1002,"E-BB","bb@123",0, new Department(102, "D-BB")));
            employees.put(1003, new Employee(1003,"E-CC","cc@123",1, new Department(103, "D-CC")));
            employees.put(1004, new Employee(1004,"E-DD","dd@123",1, new Department(104, "D-DD")));
            employees.put(1005, new Employee(1005,"E-EE","ee@123",0, new Department(105, "D-EE")));
        }
        
        
         private static Integer initId = 1006;  
          
            public void save(Employee employee){  
                if(employee.getId() == null){  
                    employee.setId(initId++);  
                }  
                  
                employee.setDepartment(departmentDao.getDepartment(employee.getDepartment().getId()));  
                employees.put(employee.getId(), employee);  
            }  
        
        public Collection<Employee> getAll(){
            return employees.values();
        }
        
        public Employee get(Integer id){
            return employees.get(id);
        }
        
        public void delete(Integer id){
            employees.remove(id);
        }
        
}

EmployeeHandler.java

package como.springmvc.handlers;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
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.RequestParam;

import como.springmvc.handlers.dao.DepartmentDao;
import como.springmvc.handlers.dao.EmployeeDao;
import como.springmvc.handlers.entity.Employee;

@Controller
public class EmployeeHandler {
    
    @Autowired
    private EmployeeDao employeeDao;
    
    @Autowired
    private DepartmentDao departmentDao;
    
    @ModelAttribute
    public void getEmployee(@RequestParam(value="id",required=false) Integer id,Map<String,Object> map){
        if(id !=null){
            map.put("employee", employeeDao.get(id));
        }
    }
    
    @RequestMapping(value="/emp",method=RequestMethod.PUT)
    public String update(Employee employee){
        employeeDao.save(employee);
        
        return "redirect:/emps";
    }
    
    @RequestMapping(value="/emp/{id}",method=RequestMethod.GET)
    public String input(@PathVariable("id") Integer id,Map<String,Object> map){
        map.put("employee",employeeDao.get(id));
        map.put("departments", departmentDao.getDepartments());
        return "/input";
    }
    
    @RequestMapping(value="/emp",method=RequestMethod.POST)
    public String save(Employee employee){
        employeeDao.save(employee);
        return "redirect:/emps";
    }
    
    @RequestMapping(value="emp",method=RequestMethod.GET )
    public String input(Map<String,Object> map){
        map.put("departments", departmentDao.getDepartments());
        map.put("employee", new Employee());
        return "input";
    }
    
    
    @RequestMapping("/emps")
    public String list(Map<String,Object> map){
        map.put("employees", employeeDao.getAll());
        return "list";
    }
    
    @RequestMapping(value="emp/{id}",method=RequestMethod.DELETE)
    public String delete(@PathVariable("id") Integer id){
        employeeDao.delete(id);
        return "redirect:/emps";
    }
    

}

 index.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 PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'inde.jsp' starting page</title>
    
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->

  </head>
  
  <body>
    <a href="emps">list all Employees</a>
  </body>
</html>

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 PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'list.jsp' starting page</title>
    <!--SpringMVC处理静态资源 
    REST风格的资源URL不希望带.html或.do等后缀
         若将DispatcherServlet请求映射配置为/,则SpringMVC将捕获WEB容器的所有请求,
         包括静态资源的请求,SpringMVC会将他们当作一个普通请求处理,因找不到对应处理器将导致错误。
         解决:配置<mvc:default-servlet-handler/>
     -->
    <script type="text/javascript" src="js/jquery-3.2.1.js"></script>

  </head>
  
  <body>
      <form action="" method="post">
          <input type="hidden" name="_method" value="DELETE" />
      </form>
    <c:if test="${empty requestScope.employees }">
    no information
    </c:if>
    
    <c:if test="${!empty requestScope.employees }">
    <table border="1" cellpadding="10" cellspacing="0">
            <tr>
            <th>ID</th>
            <th>LastName</th>
            <th>Email</th>
            <th>Gender</th>
            <th>Department</th> 
            <th>Edit</th>
            <th>Delete</th>
            </tr>
            <c:forEach items="${requestScope.employees }" var="emp">
                    <tr>
                        <td>${emp.id}</td>
                        <td>${emp.lastName}</td>
                        <td>${emp.email}</td>
                        <td>${emp.gender==0?'female':'male'}</td>
                        <td>${emp.department.departementName}</td>
                        <td><a href="emp/${emp.id}">Edit</a></td>
                        <td><a class="delete" href="emp/${emp.id }">Delete</a></td>
                        
                    
                    </tr>
            
            </c:forEach>
    </table>
    </c:if>
    <a href="emp">Add</a>
  </body>
  <script type="text/javascript">
          $(function(){
          $(".delete").click(function(){
          var href=$(this).attr("href");
                  $("form").attr("action",href).submit();
                      return false;
          
          });
          });
  </script>
</html>

input.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ 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 PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'input.jsp' starting page</title>
    
  </head>
  
  <body>
    <!-- 使用form标签:更快速的开发出表单页面,而且可以更方便的进行表单值的回显 
        modelAttribute属性指定绑定的模型属性,若没有指定该属性,则默认从request域
        对象中读取command的表单bean,如果该属性值也不存在,则会发生错误
    -->
    <form:form action="${pageContext.request.contextPath}/emp" method="post" modelAttribute="employee">
    
    <!-- path属性对应html表单标签的name属性值。支持级联属性 -->
    <c:if test="$employee.id ==null">
    LastName:<form:input path="lastName"/><br>
    </c:if>
    
     <c:if test="$employee.id !=null">
    <form:hidden path="id" />
    
    <!-- 对于_method不能使用form:hidden标签,因为ModelAttribute对应的bean中没有_method 这个属性
        
    -->
    <input type="hidden" name="_method" value="put" />
    </c:if>
    
    Email:<form:input path="email"/><br>
    <%
        Map<String,String> genders = new HashMap();
        genders.put("1","male");
        genders.put("0", "female");
        request.setAttribute("genders",genders);
     %>
     
     <!-- form:radiobuttons单选框组件标签,用于构造多个单选框,当表单bean对应的属性值和value值相等时,单选框被选中 -->
    Gender:<form:radiobuttons path="gender" items="${genders }"/>
    <br>
    <!-- items:可以使List,String[]或Map
         itemValue:指定value值,可以是集合中bean的一个属性
         itemLabel:指定label值 -->
    Department:<form:select path="department.id"
    items="${departments }" itemLabel="departementName" itemValue="id"></form:select>
    <input type="submit" value="Submit"/>
    </form:form>
  </body>
</html>
原文地址:https://www.cnblogs.com/liurg/p/8108560.html