1. 程式人生 > >SpringMVC學習之REST

SpringMVC學習之REST

rest風格 單選 解析 mls ash package mail input stp

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>

SpringMVC學習之REST