Spring MVC overview
Spring MVC is a web framework based on MVC design concept officially provided by spring. (equivalent to Servlet)
Spring MVC is a framework for MVC control based on Servlet encapsulation. Realize the data interaction between the front end and the server.
Comparative advantages of Spring MVC and Servlet
- Strictly abide by the idea of MVC layering
- It adopts loose coupling and plug-in structure, which is more flexible and extensible than our encapsulated BaseServlet and other MVC frameworks.
- Spring MVC is based on spring extensions and provides a complete set of MVC annotations
- Spring MVC provides a variety of processing methods for data binding and view parsing, which can be configured flexibly
- Spring MVC provides good support for RESTful and URL design methods
Spring MVC essential work
- Receive and parse requests
- Processing requests
- Data rendering, responding to requests
Spring MVC framework deployment
1. Create Maven web project
2. Add dependency
- junit
- spring-context
- spring-aspect
- spring-jdbc
- spring-web
- spring-webmvc
<dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.2.12.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>5.2.12.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.2.12.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>5.2.12.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.2.12.RELEASE</version> </dependency> </dependencies>
3. Create Spring MVC configuration file
-
Create a file named spring-servlet.xml in the resources directory
-
Add MVC namespace
-
<?xml version="1.0" encoding="UTF-8"?> <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:aop="http://www.springframework.org/schema/aop" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <context:annotation-config/> <context:component-scan base-package="com.ccl"/> <!-- statement MVC Using annotation driven--> <mvc:annotation-driven/> </beans>
4. Configure the front controller of spring MVC in web.xml
Spring MVC provides a class called DispatcherServlet (spring MVC central processor, that is, front-end controller) to intercept user requests and submit them to spring MVC for processing
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0"> <servlet> <servlet-name>SpringMVC</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-servlet.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>SpringMVC</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
Static resource allocation
/*Difference between and / or
/*Intercept all HTTP requests, including. jsp requests, and map all requests to the request path of the controller class for processing
/Intercept all HTTP requests, excluding. jsp requests, but don't rest assured about static resource requests, html,css,js and pictures
Static resource release configuration
html,css,js, pictures, fonts, etc
<!-- Configure static resource release--> <mvc:resources mapping="/css/**" location="/css/"/> <mvc:resources mapping="/static/**" location="/static/"/> <mvc:resources mapping="/imges/**" location="/imges/" />
Spring MVC framework uses
In spring MVC, the class that receives and processes user requests is called a COntroller
Create controller
1. Create controller class
-
Create a package named com.ccl.controllers (the package needs to be within the scope of Spring annotation scanning)
-
Create BookCOntroller (no inheritance and implementation required)
-
Add the @ Controller annotation on the class to declare that this class is the Controller of spring MVC
-
Declare request path: @ RequestMaapping ("/ url") declares the request url of this controller class
-
@Controller @RequestMapping("/book") public class BookController { }
2. Define the method to process the request in the controller class
-
Multiple methods can be defined in a controller class to handle different requests
-
Add @ RequestMapping ("url") on each method to declare the url of the current method request
-
Annotations in front of class names can be omitted
-
@RequestMapping("/add") public void add(){ System.out.println("----BookAdd----"); } @RequestMapping("/list") public void list(){ System.out.println("----BookList----"); }
visit
- http://localhost:8080/Spring/book/add
- http://localhost:8080/Spring/book/list
The front end submits data to the controller class
Create front-end page jsp
-
The action attribute of the book-add.jsp form sets the combined path of the url of the controller class and the url of the corresponding method
-
<%-- Created by IntelliJ IDEA. User: 13749 Date: 2021/10/31 Time: 17:22 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>AddBook</title> </head> <body> <h3>Add books</h3> <form action="/book/add" method="post"> <p>Book Name:<input type="text"/></p> <p>Author:<input type="text"/></p> <p>Book price:<input type="text"/></p> <p><input type="submit" value="Submit"/></p> </form> </body> </html>
Front end page submission data
Form submission
-
Form submission: the input box needs to provide the name attribute, and the spring MVC controller takes the value through the name attribute
-
<form action="book/add" method="post"> <p>Book Name:<input type="text"/></p> <p>Author:<input type="text"/></p> <p>Book price:<input type="text"/></p> <p><input type="submit" value="Submit"/></p> </form>
url submission
Ajax submission
-
Ajax submission: request line, request header and request body can be used to pass values
-
<input type="button" value="Submit" id="btn1"/><script type="text/javascript" src="js/jquery-3.2.1.min.js"></script><script type="text/javascript"> $("#BTN1 "). Click (function() {var obj = {}; obj.bookname =" Java "; obj.bookauthor =" Zhang San "; obj.bookprice = 3.33; $. Ajax ({URL:" book / add ", type:" post ", headers: {}, contenttype:" application / JSON ", data: Obj, success: function (RES) { console.log(res) } }) });</script>
The controller receives the data submitted by the front end
Request line transfer value
- Form submission
- URL submission
- $. ajax() request url value
- . p o s t ( ) / .post()/ Value transfer of {} in. post()/.get()
@The RequestParam annotation is used to receive the data passed by the request line
- Front end submission data
<form action="book/add" method="post"> <p>Book Name:<input type="text" name="bookName"/></p> <p>Author:<input type="text" name="bookAuthor"/></p> <p>Book price:<input type="text" name="bookPrice"/></p> <p><input type="submit" value="Submit"/></p></form>
- The controller receives data
@RequestMapping("/add")public void add(@RequestParam("bookName") String a , @RequestParam("bookAuthor") String b , @RequestParam("bookPrice") double c){ System.out.println("---BookAdding...."); System.out.println(a); System.out.println(b); System.out.println(c);}
If the parameter name of the controller method is the same as the front-end name, you do not need to write the @ RequestParam annotation
Request header value
-
ajax encapsulates request header data
-
$.ajax({ ... headers:{ }, .....})
@The RequestHeader annotation is used to receive the data received by the request header:
front end:
<h3>Ajax Submit</h3> <input type="button" value="Submit" id="btn1"/> <script type="text/javascript" src="js/jquery-3.2.1.min.js"></script> <script type="text/javascript"> $("#BTN1 "). Click (function() {var obj = {}; obj.bookname =" Java "; obj.bookauthor =" Zhang San "; obj.bookprice = 3.33; $. Ajax ({URL:" book / list ", type:" post ", headers: {token:" qwer "}, / / contenttype: "application/json", // data:obj, success:function (res){ console.log(res) } }) }); </script>
Back end:
@RequestMapping("list")public void list(@RequestHeader("token") String token){ System.out.println("--BookListing...."); System.out.println(token);}
The request header and the value transmitted by the request line can be received at the same time
Request body value
-
ajax encapsulates request body data
-
$.ajax({ url:"book/update", type:"post", contentType:"application/json", data: s , success:function (res){ console.log(res) }
@The RequestBody annotation is used to receive the data passed by the request body
@The RequestBody converts the JSON format data submitted by the front-end request into Java objects, relying on the jackson package
-
front end
-
<script type="text/javascript"> $("#BTN1 "). Click (function() {var obj = {}; obj.bookname =" Java "; obj.bookauthor =" Zhang San "; obj.bookprice = 3.33; VAR s = json.stringify (obj); / / convert the object to JSON format console.log (s); $. Ajax ({URL:" book / update ", type:" post ", contentType:" application/JSON“ , data: s, / / if the value of data is JSON format string, contentType must be set to "application/JSON" success: function (RES) {console. Log (RES)}})}); < / script >
-
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.12.1</version></dependency>
-
controller:
-
public void update (@RequestBody Book book){ System.out.println("----book update "); System.out.println(book); }
The controller responds to the front end request
The controller responds to the synchronization request
Synchronization request: form, hyperlink
-
The return type of the method processing the synchronization request is defined as String or ModelAndVIew
-
The return type is String:
-
Request forwarding
@RequestMapping("/add")public String add(@RequestParam("bookName") String a , @RequestParam("bookAuthor") String b , @RequestParam("bookPrice") double c){ System.out.println("---BookAdding...."); System.out.println(a); System.out.println(b); System.out.println(c); return "/tips.jsp";}
redirect
@RequestMapping("/add")public String add(@RequestParam("bookName") String a , @RequestParam("bookAuthor") String b , @RequestParam("bookPrice") double c){ System.out.println("---BookAdding...."); System.out.println(a); System.out.println(b); System.out.println(c); return "redirect:/tips.jsp";}
-
Return type is ModelAndView:
-
Request forwarding
-
@RequestMapping("/add")public ModelAndView add(@RequestParam("bookName") String a , @RequestParam("bookAuthor") String b , @RequestParam("bookPrice") double c){ System.out.println("---BookAdding...."); System.out.println(a); System.out.println(b); System.out.println(c); ModelAndView modelAndView = new ModelAndView("/tips.jsp"); return modelAndView;}
redirect
@RequestMapping("/add")public ModelAndView add(@RequestParam("bookName") String a , @RequestParam("bookAuthor") String b , @RequestParam("bookPrice") double c){ System.out.println("---BookAdding...."); System.out.println(a); System.out.println(b); System.out.println(c); ModelAndView modelAndView = new ModelAndView("redirect:/tips.jsp"); return modelAndView;}
-
The controller responds to asynchronous requests
Asynchronous requests: ajax requests
-
The first method: use the output stream in response to respond (the return type is void)
-
Add the HttpServletResponse parameter to the method
-
In the method, the output stream is obtained through response, and the stream is used for response
@RequestMapping("/update") public void update (@RequestBody Book book , HttpServletResponse response) throws IOException { System.out.println("----book update "); System.out.println(book); //Use ObjectMapper to convert objects to JSON format strings string s = new ObjectMapper(). Writevalueasstring (Book); response. SetCharacterEncoding ("UTF-8"); printwriter out = response. Getwriter(); out. Flush(); out. Close();}
-
-
The second way: directly return the response object in the controller method
-
The return type of the controller return method is set to the object type that responds to the ajax request
-
Add the @ ResponseBody annotation in front of the controller method to convert the returned object into a JSON response to the ajax request
-
@RequestMapping("/update")@ResponseBodypublic List<Book> update () { System.out.println("----book update "); List<Book> books = new ArrayList<Book>(); books.add(new Book(1,"java","Zhang San",2.33)); books.add(new Book(2,"C++","Li Si",56.0)); for (Book book1 : books) { System.out.println(book1 ); } return books;}
-
Data transfer by controller in response to synchronization request
For the forwarding response of synchronization request, we can pass parameters to the forwarded page
-
The return type is String:
-
1. Define a parameter of type Model in the controller method
-
2. Before the return page, if you want to add a key value pair to the model, the added key value pair will be passed to the forwarding page
@RequestMapping("/add2")public String add(String bookName,String bookAuthor,String bookPrice , Model model){ System.out.println("---BookAdding2...."); //It is equivalent to the request object model. AddAttribute ("key1", "value1"); Model. AddAttribute ("key2", new book (1, "Java", "Zhang San", 9.93)); return "/tips.jsp";}
-
In addition to passing values using the Model, you can also use the HttpServletRequest object
-
@RequestMapping("/add3")public String add3(String bookName,String bookAuthor,String bookPrice ,HttpServletRequest request){ System.out.println("---BookAdding2...."); //It is equivalent to the request object request.setattribute ("key1", "value1"); Request. SetAttribute ("key2", new book (1, "Java", "Zhang San", 9.93)); return "/tips.jsp";}
-
Return type ModelAndView
-
@RequestMapping("/add4")public ModelAndView add3(String bookName,String bookAuthor,String bookPrice ){ System.out.println("---BookAdding2...."); ModelAndView modelAndView = new ModelAndView("/tips.jsp"); modelAndView.addObject("key","modelling1"); modelAndView.addObject("book",new Book(1,"C++","Mr.Cao",99.0)); return modelAndView;}
Solve the problem of Chinese garbled code
Front page
-
jsp page
<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
-
html page
<meta charset="UTF-8">
Set server code
-
tomcat/conf/server.xml
-
<Connector port="8080" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" URIEncoding="UTF-8" />
Set the encoding method of SpingMVC
Coding filter
-
Configure spring MVC encoding filter in web.xml
-
<!-- Coding filter--> <filter> <filter-name>EncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <!--Set the encoding format to utf-8--> <init-param> <param-name>encoding</param-name> <param-value>utf-8</param-value> </init-param> <!-- Mandatory encoding is utf-8--> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>EncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>