1. Binding of request parameters
Binding mechanism: the data submitted by the form is k=v format username = Jack & password = 123
The parameter binding process of spring MVC is to bind the request parameters submitted by the form as the parameters of the methods in the controller: the name of the submitted form and the name of the parameters are the same
Supported data types: basic data type and string type; entity type (JavaBean) collection data type (List, map collection, etc.) basic data type and string type; the name of the submitted form and the name of the parameter are the same, case sensitive
Entity type (JavaBean) requires the name of the submitted form to be consistent with the attribute name in the JavaBean. If a JavaBean class contains other reference types, the name attribute of the form needs to be written as: object. Attribute
Encapsulate the set attribute data with a list[index]. Attribute name 'map['key']. Attribute name. Note: if the request parameter is Chinese, you can configure the character set filter provided by Spring in web.xml to solve the Chinese garbled code problem
If there is Date type in the attribute of the object, the page input parameter format is 2019 / 1 / 1, which can be bound automatically. If the page input parameter format is 2019-1-1, it cannot be bound. You need to use a user-defined type converter to solve it
Any data type submitted by the form is all string type, but Integer type is defined in the background, and the data can also be encapsulated, indicating that data type conversion will be carried out by default within the Spring framework. If you want to customize data type conversion, you can implement the interface of Converter
1. Create date conversion class
//Convert string to date public class StringToDateConverter implements Converter<String,Date>{ public Date convert(String source) { // judge if(source == null){ throw new RuntimeException("Please input data"); } DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); try { // Convert string to date return df.parse(source); } catch (Exception e) { throw new RuntimeException("Error in data type conversion"); } } }
2. Modify springmvc.xml
<!--Configure custom type converter--> <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean"> <property name="converters"> <set> <bean class="com.qf.utils.StringToDateConverter"/> </set> </property> </bean> <!-- open SpringMVC Framework annotation support --> <mvc:annotation-driven conversion-service="conversionService"/>
You can see that this method is very troublesome. Another method: just add @ datetimeformat (pattern = "yyyy MM DD") to the attribute of Date type in the entity class
@DateTimeFormat(pattern = "yyyy-MM-dd") private Date birthday;
2. Common notes
RequestParam annotation function: pass the parameter with the specified name in the request to the formal parameter assignment attribute in the controller. Value: name in the request parameter. required: whether this parameter must be provided in the request parameter. The default value is true and must be provided
The PathVariable annotation is used to bind placeholders in URLs. There is / delete/{id} in the url, {id} is the placeholder attribute value: Specifies the name of the placeholder in the url
Jsp is as follows:
<%-- Created by IntelliJ IDEA. User: 86156 Date: 2021/10/19 Time: 9:50 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <center> <a href="user/test1?id=438">Point me 1</a><br><hr> <a href="user/test2/12138">Point me 2</a><br><hr> <a href="user/test3">Point me 3!</a><br><hr> <a href="user/test4">Point me 4</a><br><hr> </center> </body> </html>
The Controller is as follows:
@org.springframework.stereotype.Controller @RequestMapping("user") public class Controller { @RequestMapping("test1") //Common annotation 1 RequestParam gets the value of the url public void test1(@RequestParam("id") Integer ids) { System.out.println(ids); } //Common notes 2 // Restful style URL //The request path is the same. You can execute different methods in the background according to different request methods //restful style URL benefits //Clear structure //Meet the standard //Easy to understand //Convenient expansion @RequestMapping("test2/{id}") public void test2(@PathVariable("id") Integer id) { System.out.println(id); } }
restful style URLs are the same as the request path. They can execute different methods in the background according to different request methods. restful style URLs have the advantages of clear structure, compliance with standards, easy understanding and convenient expansion
3. Uncommon notes
RequestHeader annotation: get the value of the specified request header attribute value: the name of the request header
Cookie value annotation function: used to obtain the value of the name of the specified cookie. Property value: the name of the cookie
JSP page as above
The Controller is as follows:
//Note 3 not commonly used @RequestMapping("test3") public void test3(@RequestHeader("host") String host){ System.out.println(host); } //Note 4 not commonly used @RequestMapping("test4") public void test4(@CookieValue("JSESSIONID") String jid){ System.out.println(jid); }
Click the output of the four connection consoles respectively
4. Response data and results view
Return value classification
Return string: the string returned by the String Controller method can specify the name of the logical view and the address of the physical view according to the view parser. During application, you can set the parameter type to Model, and use the Model object to call the addAttribute method to store data.
The return value is void. If the method return value of the controller is written as void, the program will execute the exception of 404. By default, the JSP page is not found. When applying, you can set the parameter types as HttpServletRequest and HttpServletResponse, and use forwarding or redirection to jump to the page
The return value is ModelAndView object. ModelAndView object is an object provided by Spring. You can call addObject method to save data and setViewName method to jump to the page
Use the forward keyword to forward requests. return "forward: the JSP path to forward"
Redirect using redirect keyword (the project path will be added by default) return "redirect: redirected JSP path"
4.1 first create two JSP pages, then reg.jsp under webapp, and index.jsp under student folder under web
<%-- Created by IntelliJ IDEA. User: 86156 Date: 2021/10/18 Time: 16:38 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <center> <%-- I casually wrote a form and demonstrated it to everyone ok la--%> <form method="get" action="student/reg"><br> full name: <input type="text" name="name"><br> password:<input type="password" name="password"><br> <%-- Set, directly assign a value to the subscript--%> Car 1:<input type="text" name="list[0].cname"><br> Car 2:<input type="text" name="map['first'].cname"><br> birthday:<input type="date" name="birthday"><br> <input type="submit" name="Submit" value="Submit"><br> </form> </center> </body> </html>
<html> <head> <%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %> </head> <body> <h2>Hello World!</h2> ${student.name}<br> ${student.password}<br> ${student.list[0].cname}<br> ${student.map['first'].cname}<br> ${student.birthday}<br> ${student} </body> </html>
4.2 entity class
4.2.1 Car
package com.coffee.entity; import lombok.Data; @Data public class Car { private String cname; }
4.2.2 Student class (because the time format returned by the browser is different from our back-end, it needs to be defined here. If it is not defined, a 400 error will appear)
package com.coffee.entity; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Data; import org.springframework.format.annotation.DateTimeFormat; import java.io.Serializable; import java.util.Date; import java.util.List; import java.util.Map; @Data public class Student implements Serializable { private String name; private String password; private List<Car> list; private Map<String,Car> map; //If you have time, you must add this annotation @DateTimeFormat(pattern = "yyyy-MM-dd") private Date birthday; }
4.3 Controller
4.3.1 use the model parameter to the corresponding view
@org.springframework.stereotype.Controller @RequestMapping("/student") public class Controller { @RequestMapping(value = "/reg", produces = "text/html;charset=UTF-8") public String reg(Model model,Student student) { model.addAttribute("student",student); return "/index.jsp"; } }
4.3.2 return value type using ModelAndView
@org.springframework.stereotype.Controller @RequestMapping("/student") public class Controller { @RequestMapping(value = "/reg", produces = "text/html;charset=UTF-8") public ModelAndView reg(Student student) { ModelAndView modelAndView = new ModelAndView(); // Stored value modelAndView.addObject("student",student); // Set jump page modelAndView.setViewName("/index.jsp"); return modelAndView; } }
4.3.3 add HttpServletRequsert and HttpServletResponse to forward and redirect through their objects to realize the jump function
@org.springframework.stereotype.Controller @RequestMapping("/student") public class Controller { @RequestMapping(value = "/reg", produces = "text/html;charset=UTF-8") public void reg(HttpServletRequest request, HttpServletResponse response,Student student) { request.setAttribute("student",student); try { request.getRequestDispatcher("/index.jsp").forward(request,response); } catch (ServletException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
4.3.4 using String
@org.springframework.stereotype.Controller @RequestMapping("/student") public class Controller { @RequestMapping(value = "/reg", produces = "text/html;charset=UTF-8") public String reg(Student student) { return "/index.jsp"; } }
@org.springframework.stereotype.Controller @RequestMapping("/student") public class Controller { @RequestMapping(value = "/reg", produces = "text/html;charset=UTF-8") public String reg(Student student) { //forward return "forward:/index.jsp"; //Redirection because I pass values, redirection is not appropriate //return "redirect:/index.jsp" } }
5. Use of ajax in spring MVC
@RequestBody and @ ResponseBody are generally used to obtain request json type data and return response json type data in ajax
@RequestBody: used to obtain the data of the request body json (Note: GET mode requests are not allowed). Set the request parameter to json type in ajax: contentType: application/json
@ResponseBody: used to respond to json data, provided that the jar package dependency of json needs to be imported in advance
1.DispatcherServlet will intercept all resource problems
As a result, static resources (img, css, js) will also be intercepted and cannot be used. The solution is to configure static resources without interception. Add the following configuration in the springmvc.xml configuration file:
<!--Front end controller, which static resources are not intercepted(springmvc.xml in)--> <mvc:resources location="/css/" mapping="/css/**"/> <mvc:resources location="/images/" mapping="/images/**"/> <mvc:resources location="/js/" mapping="/js/**"/> <!-- set up html Static pages are not blocked(web.xml in) --> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.html</url-pattern> </servlet-mapping>
<!-- Set all static resources not to be intercepted(springmvc.xml in),Equivalent to the above two configurations--> <mvc:default-servlet-handler/>
2. Import dependency in pom.xml
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.9.0</version> </dependency>
3. Write html/jsp pages
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <center> <form> ID: <input type="text" name="id" id="id"><br> full name:<input type="text" name="name" id="name"><br> Age:<input type="text" name="age" id="age"><br> <input type="button" onclick="login()" value="Submit"><br> </form> </center> </body> <!--Import jQuery library--> <script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-3.5.1.min.js"></script> <script type="application/javascript"> function login() { var $id = $("#id").val(); var $name = $("#name").val(); var $age = $("#age").val(); //Test whether the data in the input box can be obtained alert($id+"***"+$name+"***"+$age); var student = $("form").serialize(); $.ajax({ type: "POST", url: "student/login", data: student, success: function(backData){ //When the data is successfully returned, it is output in the pop-up box alert(backData.id+"full name:"+backData.name+"Age:"+backData.age); } }); // This is the get and post methods // $.get("student/login",student, // function (backData) { // alert("I am me"); // alert(backData.id + "Name:" + backData.name + "age:" + backData.age); // }) // $.post("student/login",student, // function (backData) { // alert("I am me"); // alert(backData.id + "Name:" + backData.name + "age:" + backData.age); // }) } </script> </html>
4. Add method in Controller
package com.coffee.controller; import com.coffee.entity.Student; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; //Note notes @RestController @RequestMapping("student") public class Control { @RequestMapping("login") // If you pass in the object parameters, mvc will automatically encapsulate the data obtained by the front end public Student myTest(Student student){ System.out.println(student); Student student1 = new Student(); student1.setId(student.getId()); student1.setName(student.getName()); student1.setAge(student.getAge()); //The console prints out that the back end has received the data transmitted by the front end System.out.println(student1); return student1; } }
give the result as follows
Console can output
Finally, the front-end interface pops up for the second time
6. Introduction to Jason
Commonly used Jason framework: Jackson fastjason gson
JavaBean serialization conversion to Json format, performance: Jackson > fastjason > gson > Json Lib
Jackson common notes
@JsonIgnore: the specified property does not return
@Jsonformat (pattern = "yyyy MM DD HH: mm: SS", locale = "zh", timezone = "GMT + 8"): Specifies the date attribute
@JsonProperty("alias"): assign an alias to the property
package com.coffee.entity; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Data; import org.springframework.format.annotation.DateTimeFormat; import java.io.Serializable; import java.util.Date; import java.util.List; import java.util.Map; @Data public class Student implements Serializable { @JsonIgnore//Hide this property @JsonProperty("full name")//Alias private String name; @JsonProperty("password") private String password; @JsonProperty("Car 1") private List<Car> list; @JsonProperty("Car 2") private Map<String,Car> map; //Json date format @JsonFormat(pattern = "yyyy-MM-dd") @DateTimeFormat(pattern = "yyyy-MM-dd") private Date birthday; }