SPRINGMVC Study Notes (v) a restful crud based

Source: Internet
Author: User

1.1. Overview

When a submitted form has a _method field , the POST request is converted to a hiddenhttpmethodfilter DELETE , PUT Request , Add @PathVariable annotations to make a RESTful -style CRUD


1.2. Configuration information

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" xsi:schemalocation= "Http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version = "3.0" ><!--the front controller of this Spring WEB application, responsible for handling all application requests --><servlet><servlet-name>springdispatcherservlet</servlet-name><servlet-class> Org.springframework.web.servlet.dispatcherservlet</servlet-class><init-param><param-name> contextconfiglocation</param-name><param-value>classpath:spring-mvc.xml</param-value></ init-param><load-on-startup>1</load-on-startup></servlet><!--Map all requests to the Dispatcherservlet for handling--><servlet-mapping><servlet-name>springdispatcherservlet</ servlet-name><url-pattern>/</url-pattern></servlet-mapping><!--Configuration Hiddenhttpmethodfilter is able to POST request to DELETE, PUT request--><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></web-app>

1.3. Effects

① adding employee information via POST request

② Change Employee information by PUT Request

③ Delete Employee information via delete request

④ Get full employee information via get request

watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvyty3ndc0nta2/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/ Dissolve/70/gravity/southeast ">


1.4. Code

Employee.java

Package Com.ibigsea.springmvc.model;public class Employee {private Integer id;private string name;private string email; private int sex;private Department department;public Employee (Integer ID, string name, string email, int sex,department de partment) {super (); this.id = Id;this.name = Name;this.email = Email;this.sex = sex;this.department = Department;} Public Employee () {super ();} Public Integer GetId () {return ID;} public void SetId (Integer id) {this.id = ID;} Public String GetName () {return name;} public void SetName (String name) {this.name = name;} Public String Getemail () {return email;} public void Setemail (String email) {this.email = email;} public int Getsex () {return sex;} public void setsex (int sex) {this.sex = sex;} Public Department getdepartment () {return Department;} public void Setdepartment (Department Department) {this.department = Department;} @Overridepublic String toString () {return "Employee [id=" + ID + ", name=" + name + ", email=" + email+ ", sex=" + Sex + " , department= "+ DEpartment + "]";}} 

Department.java

Package Com.ibigsea.springmvc.model;import Java.io.serializable;public class Department implements Serializable { Private static final Long Serialversionuid = 6881984318733090395l;private integer id;private String name;public integer ge TId () {return ID;} public void SetId (Integer id) {this.id = ID;} Public String GetName () {return name;} public void SetName (String name) {this.name = name;} @Overridepublic String toString () {return "Department [id=" + ID + ", name=" + name + "]";}}

Restfulcontroller.java

Package Com.ibigsea.springmvc.rest;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.ibigsea.springmvc.dao.departmentdao;import Com.ibigsea.springmvc.dao.employeedao;import com.ibigsea.springmvc.model.employee;/** * Search and delete based on restful style * @author Bigsea */@Controller @requestmapping ("/restful") public class Restfulcontroller {@Autowiredprivate EmployeeDAO EmployeeDAO, @Autowiredprivate Departmentdao departmentdao;/** * The name of the employee cannot be changed because of the change, * so by @ModelAttribute annotation, * indicates when the target method is run , first get the Employee object * Save the Employee object in Implicitmode * @param ID Employee ID * @param map actually passed in Implicitmode */@ModelAttributepublic void Getemploy EE (@RequEstparam (value= "id", required=false) Integer id,map<string,object> Map) {if (id! = NULL) {Map.put ("employee", Employeedao.getempbyid (ID));}} /** * View all employee information * @param map * @return */@RequestMapping ("/list") Public String list (map<string, object> map) {Map.put ("Emps", Employeedao.getall ()); return "List";} /** * Jump to Employee Join page * @param map * @return */@RequestMapping (value= "/add", Method=requestmethod.get) public String Add (map< String, object> map) {map.put ("depts", Departmentdao.getall ()), Map.put ("Action", "Add"); return "EMP";} /** * Join Employees * @param EMP * @return */@RequestMapping (value= "/add", method=requestmethod.post) public String Add (employee emp {if (EMP = = null) {return "EMP";} if (Emp.getdepartment (). getId () = null) {emp.setdepartment (Departmentdao.getdepartmentbyid (emp.getdepartment). GetId ()));} Employeedao.save (EMP); return "Redirect:/restful/list";} /** * Delete Employee information * @param ID * @return */@RequestMapping (value= "/delete/{id}", method=requestmethod.delete) public String Delete (@PathVarIable ("id") Integer ID) {Employeedao.delempbyid (ID); return "Redirect:/restful/list";} /** * Because the method of @ModelAttribute annotations is run first, * the employee information corresponding to the employee ID is obtained * and then the employee data obtained from the foreground is stored in the employee information obtained, * so that the name attribute is not required to obtain the value * @param emp * @r Eturn */@RequestMapping (value= "/edit", method=requestmethod.put) public String edit (Employee emp) {if (EMP = = null) { return "EMP";} if (Emp.getdepartment (). getId () = null) {emp.setdepartment (Departmentdao.getdepartmentbyid (emp.getdepartment). GetId ()));} Employeedao.save (EMP); return "Redirect:/restful/list";} /** * Jump to Employee change page * @param ID Employee ID * @param map implicitmode * @return */@RequestMapping (value= "/edit/{id}", method=requestm Ethod. GET) Public String edit (@PathVariable ("id") Integer id,map<string, object> Map) {map.put ("emp", Employeedao.getempbyid (ID)); Map.put ("Depts", Departmentdao.getall ()); Map.put ("Action", "edit"); return "EMP";}}

Employeedao.java

Package Com.ibigsea.springmvc.dao;import Java.util.collection;import Java.util.hashmap;import java.util.Map;import Org.springframework.stereotype.component;import Com.ibigsea.springmvc.model.department;import Com.ibigsea.springmvc.model.Employee; @Componentpublic class EmployeeDAO {private static map<integer,employee> Emps = new Hashmap<integer, employee> ();/** * Initialize employee information */static {emps.put (1001, New Employee (1001, "AA", "[email  protected] ", 0,new Department (101," JAVA ")); Emps.put (1002, New Employee (1002," BB "," [email protected] ", 0 , New Department (102, ". NET")), Emps.put (1003, New Employee (1003, "CC", "[email protected]", 1,new Department (103, "PHP")); Emps.put (1004, New Employee (1004, "DD", "[email protected]", 0,new Department (104, "C")));} private static int employeeId = 1005;/** * Save Employee Information * @param emp */public void Save (employee emp) {if (Emp.getid () = = null) { Emp.setid (employeeid++);} Emps.put (Emp.getid (), EMP);} /** * Get all employee information * @return */public Collection<emplOyee> GetAll () {return emps.values ();} /** * Get employee information based on ID * @param ID * @return */public employee Getempbyid (Integer ID) {return emps.get (ID);} /** * Delete employee information by ID * @param id */public void Delempbyid (Integer id) {emps.remove (id);}}

Departmentdao.java

Package Com.ibigsea.springmvc.dao;import Java.util.collection;import Java.util.hashmap;import java.util.Map;import Org.springframework.stereotype.component;import com.ibigsea.springmvc.model.Department; @Componentpublic class Departmentdao {public static Map<integer, department> depts = new Hashmap<integer, department> ();/** * Initialize Department letter */static {depts.put (101, New Department (101, "JAVA"));d Epts.put (102, New Department (102, ". NET"));d Epts.put (103, new Department (103, "PHP"));d Epts.put (104, New Department (104, "C"));} /** * Get all Department info * @return */public collection<department> getAll () {return depts.values ();} /** * Get department information by ID * @param ID * @return */public Department Getdepartmentbyid (Integer ID) {return depts.get (ID);}}

list.jsp

<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "pageencoding=" UTF-8 "%><%@ taglib uri=" Http://java.sun.com/jsp/jstl/core "prefix=" C "%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >

' Male ': ' Female '}</td> <td><a href= ' ${pagecontext.request.contextpath}/restful/edit/${emp.id} ' >Edit< /a></td> <td><form action= "${pagecontext.request.contextpath}/restful/delete/${emp.id}" method= "POST" > <input type= "hidden" name= "_method" value= "DELETE" > <input type= "Submit" value= "DELETE" > & lt;/form> </td> </tr> </c:forEach> </table> </c:if> <br><br> ; <a href= "${pagecontext.request.contextpath}/restful/add" > Join Employees </a></body>


emp.jsp

<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "pageencoding=" UTF-8 "%><%@ taglib uri=" Http://java.sun.com/jsp/jstl/core "prefix=" C "%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >
1.5. Static resource issues

Because Dispatcherservlet is configured and all requests are intercepted , static resources are not included in the Springmvc.xml Configuration

Mvc:default-servlet-handler

a defaultservlethttprequesthandleris defined in the springmvc context. It will screen for requests to enter the dispatcherservlet . Assuming that a request is not mapped, the request is handled by the WEB Application server's default Servlet , assuming it is not a request for a static resource. Until the Dispatcherservlet continues to deal with it.

Mvc:annotation-driven

Will voluntarily register

Requestmappinghandlermapping

Requestmappinghandleradapter

Exceptionhandlerexceptionresolver of three beans.

You'll be able to access static resources.

1.6. Mvc:annotation-drivenand theMvc:default-servlet-handler

Add mvc:annotation-driven when configuring the SPRINGMVC configuration file

<mvc:annotation-driven/> will voluntarily register three beans

2 requestmappinghandlermapping

2 Requestmappinghandleradapter

2 Exceptionhandlerexceptionresolver

The following support will also be provided:

– Support for type conversion of form parameters using Conversionservice instances

– Supports formatting of data types with @NumberFormat ,@DateTimeFormat annotations Complete

– Support for JSR 303 Validation of JavaBean instances using @Valid annotations

– Support for using @RequestBody and @ResponseBody annotations


watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvyty3ndc0nta2/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/ Dissolve/70/gravity/southeast ">









SPRINGMVC Study Notes (v) a restful crud based

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.