SpringMVC学习(五)-RESTFUl_CRUD操作

使用SpringMVC静态模仿从数据提取数据完成CRUD操作

重点知识详解:

1.将post请求改为DELETE和PUT请求(将GET请求,通过JQUERY完成转化为DELETE请求)

2.使用配置文件将get请求转换为post请求

3.静态资源问题的处理

1.Employee.java封装类

package com.springmvc.crud.entiry;


public class Employee {


    private Integer id;
    private String lastname;
    private String email;
    //1 male 0 female
    private Integer gender;
    private Department department;

    public Employee() {
        super();
        // TODO Auto-generated constructor stub
    }



    public Integer getId() {
        return id;
    }
    public void setId(Integer 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 Integer getGender() {
        return gender;
    }
    public void setGender(Integer 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, Integer gender, Department department) {
        super();
        this.id=id;
        this.lastname = lastname;
        this.email = email;
        this.gender = gender;
        this.department = department;
    }



}

2.Department.java封装类

package com.springmvc.crud.entiry;

public class Department {


    private Integer id;
    private String departmentName;


    public Department() {
        super();
        // TODO Auto-generated constructor stub
    }

    public Department(Integer id, String departmentName) {
        super();
        this.id = id;
        this.departmentName = departmentName;
    }

    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getDepartmentName() {
        return departmentName;
    }
    public void setDepartmentName(String departmentName) {
        this.departmentName = departmentName;
    }


}

3.EmployeeDao.java Dao层实现

package com.springmvc.crud.dao;

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

import org.springframework.stereotype.Repository;

import com.springmvc.crud.entiry.Department;

@Repository
public class DepartmentDao {

    private static Map departments = null;

    static{
        departments = new HashMap<>();
        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"));
    }

    public Collection getDepartment() {

        return departments.values();
    }
    public Department getDepartment(Integer id){
        return departments.get(id);
    }

}

4.DepartmentDao.java Dao层实现

package com.springmvc.crud.dao;

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

import org.springframework.stereotype.Repository;

import com.springmvc.crud.entiry.Department;

@Repository
public class DepartmentDao {

    private static Map departments = null;

    static{
        departments = new HashMap<>();
        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"));
    }

    public Collection getDepartment() {

        return departments.values();
    }
    public Department getDepartment(Integer id){
        return departments.get(id);
    }

}

5.EmployeeHandler.java实现类

package com.springmvc.crud.handler;

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 com.springmvc.crud.dao.DepartmentDao;
import com.springmvc.crud.dao.EmployeeDao;
import com.springmvc.crud.entiry.Employee;

@Controller
public class EmployeeHandler {

    @Autowired
    private EmployeeDao employeeDao;

    @Autowired
    private DepartmentDao departmentDao;

    @RequestMapping("/emps")
    public String list(Map map) {
        map.put("employees",employeeDao.getAll());
        return "list";
    }

    @RequestMapping(value="/emp",method=RequestMethod.GET)
    public String inputAdd(Map map) {
        map.put("departments", departmentDao.getDepartment());
        map.put("employee", new Employee());
        return "input";
    }

    @RequestMapping(value="/emp",method=RequestMethod.POST)
    public String add(Employee employee) {

        employeeDao.save(employee);
        return "redirect:/emps";
    }

    @RequestMapping(value="/emp/{id}",method=RequestMethod.DELETE)  
    public String delete(@PathVariable("id")Integer id){  
        employeeDao.delete(id);   
        return "redirect:/emps";  
    }

    @RequestMapping(value="/emp/{id}",method=RequestMethod.GET)
    public String inputEdit(@PathVariable("id") Integer id,Map map) {
        map.put("employee", employeeDao.get(id));
        map.put("departments", departmentDao.getDepartment());
        return "input";
    }


    @RequestMapping(value="/emp",method=RequestMethod.PUT)
    public String update(Employee employee) {
        employeeDao.save(employee);
        return "redirect:/emps";
    }

    @ModelAttribute
    public void getEmployee(@RequestParam(value="id",required=false) Integer id,Map map) {
        if(id!=null) {
            map.put("employee", employeeDao.get(id));
        }
    }


}

6.web.xml配置


<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">

    
    <filter>
         <filter-name>HiddenHttpMethodFilterfilter-name>
         <filter-class>org.springframework.web.filter.HiddenHttpMethodFilterfilter-class>
    filter>

    <filter-mapping>
          <filter-name>HiddenHttpMethodFilterfilter-name>
          <url-pattern>/*url-pattern>
    filter-mapping>

    
    
    <servlet>
        <servlet-name>SpringDispatcherServletservlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
        
        <init-param>
            <param-name>contextConfigLocationparam-name>
            <param-value>classpath:springmvc.xmlparam-value>
        init-param>
    
        <load-on-startup>1load-on-startup>
    servlet>
    <servlet-mapping>
        <servlet-name>SpringDispatcherServletservlet-name>
        <url-pattern>/url-pattern>  
    servlet-mapping>

web-app>

7.springmvc.xml


<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
                           http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
                           http://www.springframework.org/schema/context 
                           http://www.springframework.org/schema/context/spring-context-3.2.xsd
                           http://www.springframework.org/schema/mvc 
                           http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
    
    <context:component-scan base-package="com.springmvc">context:component-scan>

    
    <bean class="org.springframework.web.servlet.view.BeanNameViewResolver">  
        <property name="order" value="10" />  
    bean>

    
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/"/>
        <property name="suffix" value=".jsp"/>
    bean>

    
    <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
    <property name="basename" value="i18n">property>
bean>


<mvc:default-servlet-handler/>
<mvc:annotation-driven>mvc:annotation-driven>
beans>

8.index.jsp页面

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title heretitle>
head>
<body>
    <a href="emps">listAllEmployeesa>

body>
html>

9.list.jsp页面

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>


<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title heretitle>

<script type="text/javascript" src="scripts/jquery-1.9.1.min.js">script>  
    <script type="text/javascript">  
        $(function(){  
            $(".delete").click(function(){  
                var href=$(this).attr("href");  
                $("form").attr("action",href).submit();  
                return false;  
            });  
        })    

    script>  
head>
<body>
 <form action="" method="post">  
  <input type="hidden" name="_method" value="DELETE">  
  form>
    <h1>hello worldh1>

    <c:if test="${empty requestScope.employees }">
        <h1>no employeeh1>
    c:if>

    <c:if test="${!empty requestScope.employees }">
        <table border="1" cellpadding="10" cellspacing="0">
            <tr>
                <th>IDth>
                <th>LastNameth>
                <th>Emailth>
                <th>Genderth>
                <th>Departmentth>
                <th>Editth>
                <th>Deleteth>
            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.departmentName }td>
                    <td><a href="emp/${emp.id}">Edita>td>
                    <td><a href="emp/${emp.id  }">Deletea>td>
                tr>                
            c:forEach>
        table>
    c:if>

    <br><br>
    <a href="emp">Add New Employeea>

body>
html>

10.input.jsp页面

<%@page import="java.util.HashMap"%>
<%@page import="java.util.Map"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title heretitle>
head>
<body>
<form:form action="${pageContext.request.contextPath }/emp" method="POST" 
    modelAttribute="employee"/>
    
    <form:form action="springmvc/add" method="POST" modelAttribute="employee">  
    <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">form:input><br>
    <%
        Map<String, String> genders = new HashMap<String, String>();
        genders.put("1", "male");
        genders.put("0", "female");
        request.setAttribute("genders", genders);
    %>
    Gender:<form:radiobuttons path="gender" items="${genders }"/><br>
    Department:<form:select path="department" 
        items="${departments }" itemLabel="departmentName" itemValue="id">form:select><br>
    <input type="submit" value="Submit"/>
 form:form>

body>
html>

你可能感兴趣的:(spring,mvc)