Spring MVC supports RESTful style programming

Source: Internet
Author: User

1. Configure Web. xml

<!--configuration Springmvc dispatcherservlet-<servlet> <servlet-name>dispatcher</servlet-name&gt        ; <servlet-class>org.springframework.web.servlet.dispatcherservlet</servlet-class> <!--Configure an initialization parameter for the Dispatcherservlet: Configure the location and name of the SPRINGMVC configuration file--<!--you can actually configure the SPRINGMVC configuration file without contextconfiglocation and use the default. The default configuration file is:/web-inf/<servlet-name>-servlet.xml-<!--<init-param> <param-name>contextconfiglocatio         N</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param>-- <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet -name>dispatcher</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping><!-          -Configure character encoding filter-<filter> <filter-name>SpringCharacterEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.characterencodingfilter</filter-class> <init-param> <param-name>encoding</param-name> &LT;PARAM-VALUE&G T utf-8</param-value> </init-param> </filter> <filter-mapping> <filte R-name>springcharacterencodingfilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!--Configure Hiddenhttpmethodfilter filters that support restful style requests, turn the POST request For DELETE, PUT request-<filter> <filter-name>HiddenHttpMethodFilter</filter-name> <fi Lter-class>org.springframework.web.filter.hiddenhttpmethodfilter</filter-class> </filter> < Filter-mapping> <filter-name>HiddenHttpMethodFilter</filter-name> <url-pattern>/*</u Rl-pattern> </filter-mapping>

2. Configure the Spring MVC configuration file

<!--Configure automatic scanning of packages--    <context:component-scanbase-package = "COM.CG" ></context: Component-scan>
<!--configuration View resolver: How to resolve the handler method return value to the actual physical view--
<bean class= "Org.springframework.web.servlet.view.InternalResourceViewResolver" >
<property name= "prefix" value= "/web-inf/views/" ></property>
<property name= "suffix" value= ". JSP" ></property>
</bean>
<!--request to release access to a static resource file, where the JS file is released--
<mvc:default-servlet-handler/>
<mvc:annotation-driven></mvc:annotation-driven>

3, display so the employee's list page

<%@ 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" >$ (function () {//convert GET request to POST request $ (". Delete"). Click (function () {var href= $( This). attr ("href"); $("Form"). attr ("action"), href). Submit (); return false;    }); })</script><!--the Name property value is configured in Web. xmlHiddenhttpmethodfilterUse
HiddenhttpmethodfilterConvert the POST request to the corresponding DELETE or POST request with value's property values--<input type= "hidden" name= "_method" value= "DELETE"/> & Lt;/form> <c:ifTest= "${empty requestscope.employees}" >no employee information. &LT;/C:if> <c:if Test= "${!empty requestscope.employees}" > <table border= "1" cellpadding= "ten" cellspacing= "0" > <tr> <th>ID</th> <th>LastName</th> <th>em ail</th> <th>Gender</th> <th>Department</th> &L t;th>edit</th> <th>Delete</th> </tr> <c:for Each items= "${requestscope.employees}" var= "emp" > <tr> <td>${emp.id}&lt ;/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}" >Edit</a></td> &LT;TD&GT;&LT;a class= "Delete" href= "emp/${emp.id}" >Delete</a></td> </tr> </c:forEach> </table> </c:if> <br><br> <a href= "emp" >add New employee</a> </body>

4. Adding and modifying employee information pages

<% @pageImport= "Java.util.HashMap"%><% @pageImport= "Java.util.Map"%><%@ page language= "java" contenttype= "text/html; Charset=utf-8 "pageencoding= "UTF-8"%><%@ taglib prefix= "form" uri= "Http://www.springframework.org/tags/form"%><%@ 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" >The form page can be developed more quickly, and the echo of the form value can be made more convenient.2Note: You can specify the model property of the binding through the Modelattribute property, and if the property is not specified, the default form bean that reads command from the request domain object if the property value does not exist, then    An error will occur. -<br><br> <form:form action= "${pagecontext.request.contextpath}/emp" method= "POST" Modelattrib Ute= "Employee" > <c:ifTest= "${!empty employee.id}" > <form:hidden path= "id"/> <input type= "hidden" name= "_metho D "value=" PUT "/> </c:if> <c:ifTest= "${empty employee.id}" >LastName:<form:input path= "LastName"/> </c:if> <br>Email:<form:input path= "email"/> <br>
<!--a better way to do this, and this is a handy demo, directly with Java scripting--<%Map<string, string> genders =NewHashmap<string, string>(); Genders.put ("1", "Male"); Genders.put ("0", "Female"); Request.setattribute ("Genders", genders); %>Gender:<br> <form:radiobuttons path= "gender" items= "${genders}" delimiter= "<br>"/> <br>Department:<form:select path= "Department.id"Items= "${departments}" itemlabel= "Departmentname" itemvalue= "id" ></form:select> <br> <input ty Pe= "Submit" value= "Submit"/> </form:form> </body>

5, the core of the processing class

 Packagecom.cg.crud.handlers;ImportJava.util.Map;Importorg.springframework.beans.factory.annotation.Autowired;ImportOrg.springframework.stereotype.Controller;ImportOrg.springframework.validation.BindingResult;ImportOrg.springframework.validation.FieldError;ImportOrg.springframework.web.bind.annotation.ModelAttribute;Importorg.springframework.web.bind.annotation.PathVariable;Importorg.springframework.web.bind.annotation.RequestMapping;ImportOrg.springframework.web.bind.annotation.RequestMethod;ImportOrg.springframework.web.bind.annotation.RequestParam;ImportCom.cg.crud.dao.DepartmentDao;ImportCom.cg.crud.dao.EmployeeDao;ImportCom.cg.crud.entities.Employee; @Controller Public classEmployesshanlder {@AutowiredPrivateEmployeeDAO EmployeeDAO; @AutowiredPrivateDepartmentdao Departmentdao; /*** Access to all employees *@paramMap *@return     */@RequestMapping (Value= "/emps")     PublicString list (map<string, object>map) {Map.put ("Employees", Employeedao.getall ()); return"List"; }            /*** After modifying the employee information, click Save, automatically use this method before receiving the page to pass parameters from the database before the update of the object information, * and then re-assigned to the form of the new modification information to the object in the Map key, so that after processing the update operation of the target method of the parameter will be * Get the Bean object that has both new and unmodified information *@paramID *@paramMap*/@ModelAttribute Public voidGetEmployee (@RequestParam (value= "id", required=false) Integer ID, map<string,object>map) {        if(id! =NULL) {Map.put ("Employee", Employeedao.get (ID)); }    }        /*** Respond to user modification actions, when employees are modified, get details of individual employees and jump view to modified page *@paramID *@paramMap*/@RequestMapping (Value= "/emp/{id}", method=requestmethod.get) PublicString input (@PathVariable ("id") Integer ID, map<string, object>map) {Map.put ("Employee", Employeedao.get (ID)); Map.put ("Departments", Departmentdao.getdepartments ()); return"Input"; }        /*** The target method of saving actions in response to updating employee information *@paramEmployee *@return     */@RequestMapping (Value= "/emp", method=requestmethod.put) PublicString Update (employee employee) {Employeedao.save (employee); return"Redirect:/emps"; }        /*** Respond to requests to add target methods for employee actions (jump to add page) *@paramMap *@return     */@RequestMapping (Value= "/emp", method=requestmethod.get) PublicString input (map<string, object>map) {Map.put ("Departments", Departmentdao.getdepartments ()); Map.put ("Employee",NewEmployee ()); return"Input"; }        /*** Respond to the target method of saving actions when adding an employee *@paramEmployee *@paramresult *@return     */@RequestMapping (Value= "/emp", method=requestmethod.post) PublicString Save (Employee employee,bindingresult result) {if(Result.geterrorcount () > 0){             for(Fielderror error:result.getFieldErrors ()) {System.out.println (Error.getfield () )+ " $$ " +error.getdefaultmessage ());        }} employeedao.save (employee); return"Redirect:/emps"; }        /*** Respond to the target method of deleting employee actions *@paramID *@return     */@RequestMapping (Value= "/emp/{id}", method=requestmethod.delete) PublicString Delete (@PathVariable (value= "id"Integer ID) {employeedao.delete (ID); return"Redirect:/emps"; }}

Spring MVC supports RESTful style programming

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.