35 spring MVC (Introduction to ssm and microservices, temporary)

Posted by shelbytll on Mon, 14 Feb 2022 02:43:06 +0100

1. Spring MVC overview

1.1 spring MVC concept

Spring MVC is also called Spring web mvc. Spring is a built-in MVC framework in spring 3 Publish after 0. Spring MVC framework solves the common problems in WEB Development (parameter receiving, file uploading, form verification, etc.), and it is simple to use and has nothing to do with spring
Seam integration. Support RESTful style URL requests. The loose coupling pluggable component structure is adopted, which is more scalable than other MVC frameworks
And flexibility.

1.2 spring MVC principle

Before using spring MVC, we used servlets for Web development. However, when using Servlet development to receive request parameters,
Data sharing, page Jump and other operations are relatively complex. servlet is the standard for web development in java. Since spring MVC is right
Servlet encapsulation, so it is obvious that the bottom layer of spring MVC is servlet, and spring MVC is the deep encapsulation of servlet
Pack.

1.3 advantages of spring MVC

1. Based on MVC architecture, the function division is clear. Solve the separation of page code and background code.
2. Simple and easy to use. Spring MVC is also lightweight, and the jar is very small. You can develop an annotated spring MVC project without relying on specific interfaces and classes.
3. As a part of the Spring framework, you can use Spring's IoC and AOP. It is convenient to integrate mybatis, hibernate, JPA and other frameworks.
4. The annotations of spring MVC are powerful and easy to use.

2. MVC mode review

Model 1: jsp+javabean model - embed a lot of java code in jsp pages
Model 2: jsp+servlet+javabean model - the jsp page sends the request to the servlet, the servlet calls the javabean, and then the servlet responds to the user with the jsp page.
Model 2 is generally the current MVC mode, which we have always used.

Model view controller: Model View Controller
Model: JavaBeans in the model layer are responsible for data access and business processing
View: View JSP technology is responsible for collecting and displaying data
Controller: controller servlet Technology Intermediate scheduling

Operation of controller:
1. Accept the request from the client (including the data carried in the request)
2. Processing request: call the business logic in the model layer of the background
3. Page navigation: response after processing: JSP page

3. Entry program

3.1 create maven project

Create the project and complete the directory structure

3.2 pom. Add dependencies and plug-ins to XML files

<!--web project-->
<packaging>war</packaging>
<dependencies>
<!--spring-webmvc rely on-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.13.RELEASE</version>
</dependency>
<!--springmvc Bottom or servlet,So you must add serlvet rely on-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope><!--When the plug-in runs without scope, the plug-in will fail to start-->
</dependency>
</dependencies>
<build>
<plugins>
<!-- Coding and compiling JDK edition -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<!--tomcat plug-in unit-->
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<path>/</path>
<port>8080</port>
</configuration>
</plugin>
</plugins>
</build>

3.3 create Spring and Spring MVC configuration files

We generally register all beans except the Controller in the spring container, and register the Controller in the spring MVC container. So we add ApplicationContext. In the resources directory XML as spring configuration, add spring MVC. XML XML as the configuration file of spring MVC.

3.3.1 create Spring configuration file ApplicationContext XML file

<?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"
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
">
<!--spring Configuration file for:Other than the controller bean Objects are scanned here-->
<context:component-scan base-package="com.kkb.dao,com.kkb.service"/>
</beans>

3.3.2 create the spring MVC configuration file xml

<?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: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/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
">
<!--springmvc Configuration file for:Controller bean Objects are scanned here-->
<context:component-scan base-package="com.kkb.controller"/>
</beans>

3.4 on the web Spring and spring MVC configuration in XML

<!--spring Configuration of-->
<context-param>
<!--contextConfigLocation: Indicates for loading Bean Configuration file for-->
<param-name>contextConfigLocation</param-name>
<!--appoint spring Location of the configuration file
 This configuration file also has some default rules. Its configuration file name is called by default applicationContext.xml ,
If you put this configuration file in WEB-INF Directory, so there is no need to specify the location of the configuration file,
Just specify the listener.
This configuration is Spring integrate Web General configuration of environment; It is generally used to load the controller layer Bean(as
dao,service Etc.) to facilitate communication with any other Web Framework integration.
-->
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
<listenerclass>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--SpringMVC Configuration of-->
<!--
Front end controller: all requests will pass through this controller and then be distributed to each sub controller through this controller.
The front-end controller is essentially a Servlet,because SpringMVC The bottom layer is to use Servlet Written
-->
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servletclass>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- Read when creating front-end controller springmvc Profile startup ioc container -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<!-- Tomcat Create this object at startup -->
<load-on-startup>1</load-on-startup>
</servlet>
<!-- Configure interception path url,All with.do The end requests will be intercepted and processed by the front-end controller -->
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<!--
SpringMVC Configuration resolution of:
1,servlet-class: Fully qualified name of the front-end controller, in spring-webmvc-5.2.5.RELEASE.jar In package
org.springframework.web.servlet lower
2,load-on-startup: Whether the mark is in Web Server (here is) Tomcat)This is created at startup Servlet real
 For example, whether or not Web Call to execute this when the server starts Servlet of init()square
 Method, not created when it is actually accessed. The value is required to be an integer.
A value greater than 0 indicates that the container loads and initializes the at startup servlet,The smaller the value, the smaller the Servlet Your priority is
 The higher it is, the earlier it is created
 Value less than 0 or omitted: indicates the Servlet Only when it is actually used will it be created.
The value is the same: the container will choose its own creation order
3,url-pattern: Can be written as / ,Can be written as*.do ,*.action,*.mvc And so on. Write here first*.do,in the future
 Introduce the differences between different writing methods.
4,init-param: Expressed springmvc Name and location of the configuration file. If there is no configuration, the default is in the project WEB-INF
 Directory with name Servlet name-servlet.xml Configuration file for.
If there is no configuration, the default rule is enabled: that is, if the configuration file is placed in webapp/WEB-INF/ Directory, and configure the file
 The name of the piece is equal to DispatcherServlet Name of+ -servlet(That is, the configuration file path here is webapp/WEBINF/dispatcherServlet-servlet.xml),If so, there is no need to add init-param Parameter, i.e. no
 Manual configuration springmvc The framework will automatically load the configuration file.
In general, the configuration file is placed under the class path, that is resources Directory. Therefore, when registering the front-end controller,
You also need to set up a lookup SpringMVC Configuration file path.
among contextConfigLocation Attributes: from DispatcherServlet Parent class of FrameworkServlet,
In this class contextConfigLocation Property is used to configure springmvc The path and name of the.
-->

3.5 create controller

package com.kkb.controller;
import com.kkb.service.TeamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
/**
* ClassName: TeamController
*
* @author wanglina
* @version 1.0
*/
@Controller
public class TeamController {
@Autowired
private TeamService teamService;
@RequestMapping("hello.do")
public ModelAndView add(){
System.out.println("TeamController----add---");
teamService.add();
ModelAndView mv=new ModelAndView();
mv.addObject("teamName","Lakers");//amount to
request.setAttrubuite("teanName","Lakers");
mv.setViewName("index");//In the future, it will be processed by the view parser of spring MVC and converted into a physical resource path,
amount to request.getRequestDispatcher("index.jsp").forward();
//After being processed by the InternalResourceViewResolver object, adding the pre suffix becomes
/jsp/index.jsp
return mv;
}
}
package com.kkb.service;
import org.springframework.stereotype.Service;
@Service
public class TeamService {
public void add(){
System.out.println("TeamService---- add-----");
}
}

3.6 configuring the view parser

In spring MVC Add the configuration of the view parser to the XML configuration file

<!--view resolver -->
<bean id="internalResourceViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<mvc:annotation-driven/>
<!--annotation-driven It is a simplified form, which can also be manually configured to replace it. The simplified form can make beginners quickly
 Apply the default configuration scheme.
The annotation is automatically registered DefaultAnnotationHandlerMapping And AnnotationMethodHandlerAdapter
 Two bean,yes springMVC by@Controller Necessary to distribute user requests, solved@Controller Preconditions for annotation use
 Set.
At the same time, it also provides: data binding support,@NumberFormatannotation support,@DateTimeFormat support,@Valid branch
 Hold, read and write XML Support of( JAXB,Reading and writing JSON Support of( Jackson). We process the response ajax When you request, you use the json
 Support (after configuration, added jackson of core and mapper After the package is, it can be automatically converted into a configuration file without writing a configuration file json). 
-->

3.7 compiling index JSP page

Create a folder jsp under the webapp folder, and then add index.jsp to the jsp folder jsp page

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>index</title>
</head>
<body>
<h1>index---------------${teamName}</h1>
</body>
</html>

8.3 testing

3.9 analysis

When spring and spring MVC appear at the same time, there will be two containers in our project, one is spring container and the other is spring MVC container. Spring container is loaded through ContextLoaderListener and spring MVC container is loaded through dispatcher servlet. These two containers are different:

As shown in the figure:
The context loaded beans initialized by ContextLoaderListener are shared by the whole application, no matter what presentation layer technology is used, such as dao layer and service layer beans;
The bean s loaded in the context of dispatcher servlet initialization are only valid for Spring Web MVC, such as Controller, HandlerMapping, HandlerAdapter, etc. the initialization context should only load Web related components.
1. Can't spring container scan all beans?
may not. When the request sent by the user reaches the server, it will look for the front-end Controller DispatcherServlet to process it. It is only found in the spring MVC container, so the Controller must be scanned in the spring MVC container.
2. Can all beans be scanned in the spring MVC container?
sure. You can scan all beans in the spring MVC container. However, this is generally not done in actual development for the following reasons:
(1) To facilitate the management of configuration files
(2) In the future, in the combination of Spring + spring MVC + mybatis, there will be a lot of configuration content to be written, which will generally be written separately according to the function

4. Spring MVC workflow

4.1 workflow analysis


(1) The user sends a request to the front-end controller DispatcherServlet through the browser.
(2) The front-end controller directly forwards the request to the processor mapper HandleMapping.
(3) The processor mapper HandleMapping will find the processor responsible for processing the request according to the request, encapsulate it as the processor execution chain HandlerExecutionChina, and then return it to the front-end controller dispatcher servlet.
(4) The front-end controller DispatcherServlet finds the processor adapter HandlerAdaptor that can execute the processor according to the processor in the processor execution chain.
(5) The processor adapter HandlerAdaptor calls the execution processor Controller.
(6) The processor Controller encapsulates the processing result and the view to jump into an object ModelAndView, and returns it to the processor adapter HandlerAdaptor.
(7) The processor adapter directly returns the result to the front-end controller DispatcherServlet.
(8) The front-end controller calls the view parser to encapsulate the view name in ModelAndView as a view object.
(9) The View parser ViewResolver returns the encapsulated View object to the front-end controller DispatcherServlet
(10) The front-end controller DispatcherServlet calls the view object and lets it render by itself, that is, data filling to form a response object.
(11) The front controller responds to the browser.
4.2 spring MVC components
1.DispatcherServlet:
Front end controller, also known as central controller or core controller. The entry controller requested by the user is equivalent to c in mvc mode. Dispatcher servlet is the center of the whole process control, which is equivalent to the brain of spring mvc. It calls other components to process the user's request. The existence of dispatcher servlet reduces the complexity of components
Coupling between. The core controller provided by the spring MVC framework requires us to XML file.
2.HandlerMapping:
The processor mapper HandlerMapping is also a Controller that sends requests. We don't need to control this class ourselves, but it is an important Controller in the running process of spring MVC. HandlerMapping is responsible for finding the Handler, that is, the processor (that is, the Controller) according to the user's request. Spring MVC provides different mappers to implement different mapping methods, such as configuration file method, implementation interface method, annotation method, etc. in actual development, the commonly used method is annotation method.
3.Handler: processor
Handler is the back-end Controller following the front-end Controller of dispatcher servlet. Under the control of dispatcher servlet, handler processes specific user requests. Since the handler involves specific user business requests, it is generally necessary for programmers to develop the handler according to business requirements. (the handler here refers to our Controller)
4.HandlAdapter:
The processor adapter executes the processor through the HandlerAdapter, which is an application of the adapter mode. By expanding the processor adapter, it supports more types of processors and calls the processor to pass parameters.
5.ViewResolver:
The View resolver is responsible for generating the processing results into the View view. The ViewResolver first resolves the logical View name into the physical View name, that is, the specific page address, and then generates the View object. Finally, it renders the View and displays the processing results to the user through the page. Spring MVC framework provides many View types, including jstlView, freemarkerView, pdfView, etc. Generally, the model data needs to be displayed to the user through the page through the page label or page template technology, and the programmer needs to develop the specific page according to the business needs.

5 @RequestMapping annotation

five 1@RequestMapping Location of occurrence

The @ RequestMapping annotation defines the mapping rules of the processor for requests. The annotation can be defined on a class or a method, but the meaning is different.

Multiple processor methods can be defined in a class annotated by @ Controller. Of course, different processor methods match different URIs. These different URIs are specified in the value attribute of @ RequestMapping annotated on the method. However, if these requests have the same URI part, these same URIs can be extracted into the value attribute of RequestMapping annotated on the class. The URI at this time represents the name of the module. The request for the URI is relative to the root directory of the Web. Annotations at the class level map a specific request or request pattern to a Controller. Then you can add additional method level annotations to further specify the mapping relationship to the processing method.
Example: modifying teamcontroller Java is as follows

package com.kkb.controller;
import com.kkb.service.TeamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
/**
* ClassName: TeamController
*
* @author wanglina
* @version 1.0
*/
@Controller
@RequestMapping("team")
public class TeamController {
@Autowired
private TeamService teamService;
@RequestMapping(value = "add.do")
public ModelAndView addTeam(){
System.out.println("TeamController----addTeam---");
ModelAndView mv=new ModelAndView();
mv.setViewName("team/add");// Map to physical resource path: / JSP / team / add jsp
return mv;
}
@RequestMapping(value = "update.do")
public ModelAndView updateTeam(){
System.out.println("TeamController----updateTeam---");
ModelAndView mv=new ModelAndView();
mv.setViewName("team/update");//Map to physical resource path: / JSP / team / update jsp
return mv;
}
@RequestMapping("hello.do")
public ModelAndView hello(){
System.out.println("TeamController----add---");
teamService.add();
ModelAndView mv=new ModelAndView();
mv.addObject("teamName","Lakers");//amount to
request.setAttrubuite("teanName","Lakers");
mv.setViewName("index");//In the future, it will be processed by the view parser of spring MVC and converted into a physical resource path,
amount to request.getRequestDispatcher("index.jsp").forward();
//After being processed by the InternalResourceViewResolver object, adding the pre suffix becomes
/jsp/index.jsp
return mv;
}
}


Access in browser:

5.2 specify the submission method of the request

@The method attribute of RequestMapping is used to restrict the submission method of the request processed by the annotated method, that is, only the request meeting the submission method specified in the method attribute will execute the annotated method.
The value of the Method property is the RequestMethod enumeration constant. Commonly used is RequestMethod Get and
RequestMethod.POST indicates that the matching rules of the submission method are GET and POST submission.


The following table lists the common submission methods:

5.3 supplementary URL pattern parsing

5.3.1 URL pattern parsing

On the web This node is available when configuring the front-end controller of spring MVC with XML. The values in this node can be written in two ways:

Case: in index Add a picture to the JSP page if the value in the node is * do, the picture can be accessed normally, but if it is / it cannot be accessed
visit.
1. Add pictures to the project and modify the index JSP page

2. Modify web xml

3. The access picture cannot be displayed at this time

5.3.2 static resource access

If the value of is configured as /, static resources can be solved in the following two ways.

5.3.2.1 use < MVC: default servlet handler / >

Add the following content to the configuration file of spring MVC:

<mvc:default-servlet-handler/>
<!--Declared <mvc:default-servlet-handler /> After, springmvc The frame is created in the container
DefaultServletHttpRequestHandler Processor object. This object will be used for all incoming DispatcherServlet of URL
 Check. If a request is found to be a static resource, the request is forwarded to Web Application server default Servlet handle.
General servers have default Servlet. For example, we use Tomcat In the server, there is one dedicated to processing static resources
 Visited Servlet be named as DefaultServlet. his<servlet-name/>by default. It can handle various static resource access requests. Should Servlet Registered in Tomcat Server web.xml Yes. stay Tomcat Installation directory/conf/web.xml. -->

5.3.2.2 use < MVC: Resources / >

Add the following content to the configuration file of spring MVC:

<mvc:resources location="/images/" mapping="/images/**" />
<!--
location: Indicates the directory where the static resource is located. Of course, do not use directories/WEB-INF/And its subdirectories.
mapping: Represents a request for the resource. Notice that it's followed by two asterisks**. -->

In Spring 3 After version 0, Spring has defined a processor dedicated to processing static resource access requests
ResourceHttpRequestHandler. The < MVC: Resources / > tag is added to solve the problem that static resources cannot be accessed.

6. Parameters of the processor method

These parameters can be automatically assigned by the system when the processor calls the following four classes So we can go straight in the method
Connect to use. The following are the four types of parameters:
   HttpServletRequest
   HttpServletResponse
   HttpSession
Request parameters carried in the request
Preparation: create a new controller paramcontroller Java and front-end page hello JSP page

package com.kkb.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
@RequestMapping("param")
public class ParamController {
@RequestMapping("hello")
public ModelAndView hello(){
return new ModelAndView("hello);
}
}

6.1 parameters of direct use method are received one by one

6.2 use object to receive multiple parameters

6.3 the parameters of request parameter and method name are inconsistent

6.4 obtaining parameters using HttpServletRequest object

6.5 transfer parameters directly using URL address

6.6 get parameters of date type

6.7 get parameters of array type

6.8 get parameters of collection type

Spring MVC does not support getting object collection types directly from parameters. It is necessary to encapsulate object collections into entity classes.
Case source code:
Modify entity class team java

package com.kkb.pojo;
import org.springframework.format.annotation.DateTimeFormat;
import java.util.Date;
public class Team {
private Integer teamId;
private String teamName;
private String location;
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date createTime;
@Override
public String toString() {
return "Team{" +
"teamId=" + teamId +
", teamName='" + teamName + '\'' +
", location='" + location + '\'' +
", createTime=" + createTime +
'}';
}
//Omit set get method
}

Create entity class queryvo java

package com.kkb.vo;
import com.kkb.pojo.Team;
import java.util.List;
public class QueryVO {
private List<Team> teamList;
public List<Team> getTeamList() {
return teamList;
}
public void setTeamList(List<Team> teamList) {
this.teamList = teamList;
}
}

Front end page hello jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>hello</title>
</head>
<body>
<h3>8,Get parameters of collection type</h3>
<form action="/param/test08" method="post">
Team name 1:<input type="text" name="teamName"/><br/>
Team name 2:<input type="text" name="teamName"/><br/>
Team name 3:<input type="text" name="teamName"/><br/>
<button type="submit">Submit</button>
</form>
<form action="/param/test09" method="post">
team id1: <input type="text" name="teamList[0].teamId"/><br/>
team id2: <input type="text" name="teamList[1].teamId"/><br/>
team id3: <input type="text" name="teamList[2].teamId"/><br/>
Team name 1:<input type="text" name="teamList[0].teamName"/><br/>
Team name 2:<input type="text" name="teamList[1].teamName"/><br/>
Team name 3:<input type="text" name="teamList[2].teamName"/><br/>
<button type="submit">Submit</button>
</form>
<h3>7,Get parameters of array type</h3>
<form action="/param/test07" method="post">
Team name 1:<input type="text" name="teamName"/><br/>
Team name 2:<input type="text" name="teamName"/><br/>
Team name 3:<input type="text" name="teamName"/><br/>
<button type="submit">Submit</button>
</form>
<h3>6,Get parameters of date type</h3>
<form action="/param/test06" method="post">
team id: <input type="text" name="teamId"/><br/>
Team name:<input type="text" name="teamName"/><br/>
Team position:<input type="text" name="location"/><br/>
Creation date:<input type="text" name="createTime"/><br/>
<button type="submit">Submit</button>
</form>
<h3>5,Direct use URL Address transmission parameter</h3>
<h3>4,use HttpServletRequest Object get parameters</h3>
<form action="/param/test04" method="post">
team id: <input type="text" name="teamId"/><br/>
Team name:<input type="text" name="teamName"/><br/>
Team position:<input type="text" name="location"/><br/>
<button type="submit">Submit</button>
</form>
<h3>3,The parameters of the request parameter and method name are inconsistent</h3>
<form action="/param/test03" method="post">
team id: <input type="text" name="teamId"/><br/>
Team name:<input type="text" name="teamName"/><br/>
Team position:<input type="text" name="location"/><br/>
<button type="submit">Submit</button>
</form>
<h3>2,Use object to receive multiple parameters</h3>
<form action="/param/test02" method="post">
team id: <input type="text" name="teamId"/><br/>
Team name:<input type="text" name="teamName"/><br/>
Team position:<input type="text" name="location"/><br/>
<button type="submit">Submit</button>
</form>
<h3>1,The parameters of the direct use method are received one by one</h3>
<form action="/param/test01" method="post">
team id: <input type="text" name="teamId"/><br/>
Team name:<input type="text" name="teamName"/><br/>
Team position:<input type="text" name="teamLocation"/><br/>
<button type="submit">Submit</button>
</form>
</body>
</html>

Controller paramcontroller java

package com.kkb.controller;
import com.kkb.pojo.Team;
import com.kkb.vo.QueryVO;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
@Controller
@RequestMapping("param")
public class ParamController {
//8. Get parameters of collection type: simple types can be realized through @ RequestParam annotation; Object collection does not support direct retrieval
 Take, must be encapsulated in the class, as a property operation
@RequestMapping("test08")
public ModelAndView test08(@RequestParam("teamName") List<String> nameList){
System.out.println("test08-----------------");
for (String s : nameList) {
System.out.println(s);
}
return new ModelAndView("ok");
}
@RequestMapping("test09")
public ModelAndView test09(QueryVO vo){
System.out.println("test09-----------------");
for (Team team : vo.getTeamList()) {
System.out.println(team);
}
return new ModelAndView("ok");
}
//7. Get parameters of array type
@RequestMapping("test07")
public ModelAndView test07(String[] teamName,HttpServletRequest request){
System.out.println("test07-----------------");
//Mode 1:
for (String s : teamName) {
System.out.println(s);
}
System.out.println("---------------");
//Mode 2:
String[] teamNames = request.getParameterValues("teamName");
for (String name : teamNames) {
System.out.println(name);
}
return new ModelAndView("ok");
}
//6. Get parameters of date type
@RequestMapping("test06")
public ModelAndView test06(Team team){
System.out.println("test06-----------------");
System.out.println(team);
return new ModelAndView("ok");
}
//5. Directly use URL address to pass parameters: with the help of @ PathVariable annotation
// for example http://localhost:8080/param/test05/1001/lacker/las
@RequestMapping("test05/{id}/{name}/{loc}")
public ModelAndView test05(@PathVariable("id") Integer teamId,
@PathVariable("name") String teamName,
@PathVariable("loc") String teamLocation){
System.out.println("test05-----------------");
System.out.println(teamId);
System.out.println(teamName);
System.out.println(teamLocation);
return new ModelAndView("ok");
}
//4. Use the HttpServletRequest object to obtain parameters: the same way as used in the original Java Web project
@RequestMapping("test04")
public ModelAndView test04(HttpServletRequest request){
System.out.println("test04-----------------");
String teamId = request.getParameter("teamId");
String teamName = request.getParameter("teamName");
String location = request.getParameter("location");
if(teamId!=null)
System.out.println(Integer.valueOf(teamId));
System.out.println(teamName);
System.out.println(location);
return new ModelAndView("ok");
}
//3. The parameters of the request parameter and the method name are inconsistent: use @ RequestParam for correction,
// The value attribute represents the name of the parameter in the request
// The required attribute indicates whether the parameter is required: true: it must be assigned, otherwise an error of 400 will be reported; false: no assignment is allowed,
The result is null
@RequestMapping("test03")
public ModelAndView test03(@RequestParam(value = "teamId",required = false)
Integer id,
@RequestParam(value = "teamName",required = true)
String name,
@RequestParam("location") String loc){
System.out.println("test03-----------------");
System.out.println(id);
System.out.println(name);
System.out.println(loc);
return new ModelAndView("ok");
}
//2. Use an object to receive multiple parameters: the parameter name carried in the user request must be consistent with the attribute in the entity class, otherwise it will be invalid
 Cannot get
@RequestMapping("test02")
public ModelAndView test02(Team team){
System.out.println("test02-----------------");
System.out.println(team);
return new ModelAndView("ok");
}
/**
* 1,Directly use the parameters of the method to receive one by one: the parameter name of the method must be consistent with the parameter name carried in the user request, otherwise
 You can't get it
* Benefit: no type conversion required
*/
@RequestMapping("test01")
public ModelAndView test01(Integer teamId,String teamName,String
teamLocation){
System.out.println("test01-----------------");
System.out.println(teamId);
System.out.println(teamName);
System.out.println(teamLocation);
return new ModelAndView("ok");
}
@RequestMapping("hello")
public ModelAndView hello(){
return new ModelAndView("hello");
}
}

7. Chinese garbled code of request parameters

For the request parameters received earlier, if they contain Chinese, the Chinese garbled code will appear. Spring provides a special character set filter CharacterEncodingFilter class for the problem of Chinese garbled code in request parameters. As shown in the figure.

7.1 garbled code solution

On the web Register a character set filter in XML. It is recommended to register this filter before other filters. Because the filter is executed according to its registration order.
On the web XML configuration file directly registers the character set

<!--Register character set filter: post Solution to the problem of request Chinese garbled code-->
<filter>
<filter-name>characterEncodingFilter</filter-name>
<filterclass>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<!--Specify character set-->
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<!--force request Use character set encoding-->
<init-param>
<param-name>forceRequestEncoding</param-name>
<param-value>true</param-value>
</init-param>
<!--force response Use character set encoding-->
<init-param>
<param-name>forceResponseEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

7.2 solution principle

7. Return value of processor method

There are four common types of return values of processor methods annotated with @ Controller:
   1. ModelAndView
   2. String
   3. Returns a custom type object
   4. No return value void
We choose different return values according to the actual business.
Case preparation:
Create controller resultcontroller java

package com.kkb.controller;
import com.kkb.pojo.Team;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("result")
public class ResultController {
}

Add the page result. In the JSP folder jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>result</title>
</head>
<body>
<h1>result----------------</h1>
</body>
</html>

7.1 return to ModelAndView

In most cases, we return ModelAndView, that is, data model + view: controller resultcontroller Add method to Java:

//1. The return value is ModelAndView: this method includes both data carrying and resource jump. You can choose this method
@RequestMapping("test01")
public ModelAndView test01(){
ModelAndView mv=new ModelAndView();//Models and views
//Carry data
mv.addObject("teamName","Lakers");//Equivalent to request.
setAttribute("teamName","Lakers“);
mv.setViewName("result");// Passing through the view parser InternalResourceViewResolver
 Change the logical view name plus the prefix to the physical resource path /jsp/result.jsp
return mv;
}

Model, put our data, and then specify the view name in ModelAndView.
After the processor method is processed, it needs to jump to other resources and transfer data at the same time. It is better to choose to return to ModelAndView, but if only one of the data needs to be transferred or jumped, ModelAndView is not the best choice at this time. result. Add the following content to the JSP page:

7.2 return String

The ModelAndView in the previous method can be divided into two parts: Model and View. In spring MVC, we can specify the Model directly in the parameters, and then the return value is the logical View name. The View parser can convert the logical View name into the physical View address.

The view parser combines the string with the prefix and suffix in the parser through the internal resource view parser InternalResourceViewResolver to form the URI to jump.
Controller resultcontroller Add method to Java:

//2. Return string
@RequestMapping("test02")
public String test02(HttpServletRequest request){
Team team=new Team();
team.setLocation("Miami");
team.setTeamId(1002);
team.setTeamName("Miami Heat");
//Carry data
request.setAttribute("team",team);
request.getSession().setAttribute("team",team);
//Jump of resources
return "result";// After being processed by the view parser InternalResourceViewResolver, the logic is treated as
 The figure name plus the prefix becomes the physical resource path /jsp/result.jsp
}

result. Add the following content to the JSP page:

7.3 return object type

When the processor method returns the Object object type, it can be Integer, String, Map, List, or user-defined Object type. However, no matter what type it is, it does not appear as a logical view, but is directly returned as data and displayed. Generally, when the front end initiates an Ajax request, it will use the form of direct return Object.
When returning the object, you need to use the @ ResponseBody annotation to put the converted JSON data into the response body.
pom. Add two dependencies to the XML file

<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.0</version>
</dependency>

7.3.1 return base type

//3. Return object type: Integer Double String custom type List Map does not return the name of the logical view
 Directly refers to data return, which is generally ajax Request to use together, will json Format data is returned directly to the response body
// Be sure to contact @ ResponseBody
@ResponseBody
@RequestMapping("test03-1")
public Integer test031(){
return 666;
}
@ResponseBody
@RequestMapping("test03-2")
public String test032(){
return "test";
}

7.3.2 return custom object type

@ResponseBody
@RequestMapping("test03-3")
public Team test033(){
Team team=new Team();
team.setLocation("Miami");
team.setTeamId(1002);
team.setTeamName("Miami Heat");
return team;
}
<div>
<button type="button" id="btn1">ajax Request custom object</button>
<h3>ajax Result display of request custom object</h3>
<p id="res"></p>
</div>
<script>
$(function(){
$("#btn1").click(function () {
$.ajax({
type: "POST",
url: "/result/test03-3",
data: "",
success: function(msg){
alert( "Data Saved: " + msg );
var name=msg.teamName;
var id=msg.teamId;
var loc=msg.location;
$("#res").html("name:"+name+",id:"+id+",location:"+loc);
}
});
});
</script>

7.3.3 return set List

@ResponseBody
@RequestMapping("test03-4")
public List<Team> test034(){
List<Team> list=new ArrayList<>(5);
for(int i=1;i<=5;i++) {
Team team = new Team();
team.setLocation("Miami"+i);
team.setTeamId(1002+i);
team.setTeamName("Miami Heat"+i);
list.add(team);
}
return list;
}
<div>
<button type="button" id="btn1">ajax Request custom object</button>
<h3>ajax Result display of request custom object</h3>
<p id="res"></p>
</div>
<script>
$(function(){
$("#btn2").click(function () {
$.ajax({
type: "POST",
url: "/result/test03-4",
data: "",
success: function(list){
alert( "Data Saved: " + list );
var str="";
for(var i=0;i<list.length;i++){
var obj=list[i];
str+="name:"+obj.teamName+",id:"+obj.teamId+",location:"+obj.location+"<br/>";
}
$("#res2").html(str);
}
});
});
});
</script>

7.3.4 return set Map

@ResponseBody
@RequestMapping("test03-5")
public Map<String,Team> test035(){
Map<String,Team> map=new HashMap();
for(int i=1;i<=5;i++) {
Team team = new Team();
team.setLocation("Jinzhou"+i);
team.setTeamId(1000+i);
team.setTeamName("warrior"+i);
//The date type is a number when returned. If you want to display it in date format, you need to add a note in the corresponding attribute of the entity class
 solution@JsonFormat(pattern = "yyyy-MM-dd")
team.setCreateTime(new Date());
map.put(team.getTeamId()+"",team);
}
return map;
}
<div>
<button type="button" id="btn3">ajax request Map</button>
<h3>ajax request Map Display of results</h3>
<p id="res3"></p>
</div>
<script>
$(function(){
$("#btn3").click(function () {
$.ajax({
type: "POST",
url: "/result/test03-5",
data: "",
success: function(map){
alert( "Data Saved: " + map );
var str="";
$.each(map,function (i,obj) {
str+="name:"+obj.teamName+",id:"+obj.teamId+",location:"+obj.location+"<br/>";
});
$("#res3").html(str);
}
});
});
</script>

7.4 no return value void - understand

The return value of the method is void, which does not necessarily have no return value. We can return it to the front end in other ways. In fact, this method can also be understood as the processing scheme in Servlet.

//Jump to the server through HttpServletRequest
@RequestMapping("test04-1")
public void test041(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
System.out.println("Direct use HttpServletRequest Carry out server-side forwarding");
request.getRequestDispatcher("/jsp/ok.jsp").forward(request,response);
}
//Redirect through HttpServletResponse
@RequestMapping("test04-2")
public void test042(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
System.out.println("Direct use HttpServletResponse Redirect jump");
response.sendRedirect("/jsp/ok.jsp");
}
//The response is given through HttpServletResponse
@RequestMapping("test04-3")
public void test043(HttpServletResponse response) throws ServletException,
IOException {
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
PrintWriter writer = response.getWriter();
writer.write("return void Type test---Return string directly");
writer.flush();
writer.close();
}
//You can also manually specify the response header to realize redirection:
@RequestMapping("test04-4")
public void test044(HttpServletResponse response) throws ServletException,
IOException {
response.setStatus(302);//Set the response code, 302 indicates redirection
response.setHeader("Location","/jsp/ok.jsp");
}

8. How to navigate the page

Page navigation is divided into two types: 1. Forwarding 2. Redirection
Spring MVC can forward or redirect pages in the following two ways:
1. Return string
2. Use ModelAndView
In spring MVC, different prefixes are used to specify forwarding or redirection when two kinds of navigation are used for page navigation
Prefix: forward:url default
Redirect: redirect:url
Preparation: create a new controller, navigationcontroller java:

package com.kkb.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
/**
* ClassName: NavigationController
* SpringMVC Navigation mode
* @author wanglina
* @version 1.0
*/
@Controller
@RequestMapping("navigation")
public class NavigationController {
}

8.1 forward to a jsp page

8.1.1 string forwarding

@RequestMapping("test01-1")
public String test011(HttpServletRequest request){
request.setAttribute("teamName","Lakers");
//return "ok";// Default method: convert the logical view to the physical resource path after being processed by the view parser
return "forward:/jsp/ok.jsp";//When the forward prefix is added, the prefixes in the view parser are lost
 If it works, you must write your own absolute path
}

8.1.2 ModelAndView forwarding

@RequestMapping("test01-2")
public ModelAndView test012(){
ModelAndView mv=new ModelAndView();
mv.addObject("teamName","Miami Heat");
//mv.setViewName("ok");// Default method: convert the logical view to the physical resource path after being processed by the view parser
mv.setViewName( "forward:/jsp/ok.jsp");//When the forward prefix is added, the view parser
 The prefix and suffix of is invalid. You must write your own absolute path
return mv;
}

8.2 redirect to a jsp page

8.2.1 redirection in string mode

@RequestMapping("test02-1")
public String test021(HttpServletRequest request){
request.setAttribute("teamName","warrior");//Unable to get the stored in the request scope on the page
 The request was interrupted because of the value in
return "redirect:/jsp/ok.jsp";//When the redirect prefix is added, the pre suffix in the view parser
 It fails. You must write your own absolute path
}

8.2.2 ModelAndView redirection method

@RequestMapping("test02-2")
public ModelAndView test022(){
ModelAndView mv=new ModelAndView();
mv.addObject("teamName","huangfeng");
//The value stored in the request scope is appended to the URL as a parameter
http://localhost:8080/jsp/ok.jsp?teamName=huangfeng&teamId=1002
mv.addObject("teamId","1002");
mv.setViewName( "redirect:/jsp/ok.jsp");//When the redirect prefix is added, the view is resolved
 The prefix and suffix in the device will fail, and you must write your own absolute path
return mv;
}

8.3 redirect or forward to controller

@RequestMapping("test03-1")
public ModelAndView test031(HttpServletRequest request){
System.out.println("test03-1---Forward to controller");
ModelAndView mv=new ModelAndView();
mv.addObject("teamName","dallas mavericks ");
mv.setViewName("forward:/navigation/test01-1");
return mv;
}
@RequestMapping("test03-2")
public ModelAndView test032(HttpServletRequest request){
System.out.println("test03-1---Redirect to controller");
ModelAndView mv=new ModelAndView();
mv.addObject("teamName","kaierteren");
mv.addObject("teamId","1003");
mv.setViewName("redirect:/navigation/test01-1");//The parameter value is appended directly to the URL
return mv;
}
@RequestMapping("test")
public String test(){
System.out.println("test-----------------");
return "index";
}

9. Exception handling

The spring MVC framework often uses the @ ExceptionHandler annotation to handle exceptions.

nine 1@ExceptionHandler Annotation

@ExceptionHandler can specify a method as an exception handling method.
The return value of the annotated method can be ModelAndView, String, or void. The method name is optional. The method parameters can be Exception and its subclass objects, HttpServletRequest, HttpServletResponse, etc. The system will automatically assign values to these method parameters.
For the usage of exception handling annotation, you can also directly annotate the exception handling method in the Controller

9.2 implementation steps

9.2.1 custom exception class

package com.kkb.exceptions;
/**
* ClassName: TeamException
* Custom exception class
* @author wanglina
 Write controller
* @version 1.0
*/
public class TeamException extends Exception{
public TeamException() {
}
public TeamException(String message) {
super(message);
}
}
package com.kkb.exceptions;
/**
* ClassName: TeamIdException
*Custom exception class
* @author wanglina
* @version 1.0
*/
public class TeamIdException extends TeamException{
public TeamIdException() {
}
public TeamIdException(String message) {
super(message);
}
}
package com.kkb.exceptions;
/**
* ClassName: TeamException
* Custom exception class
* @author wanglina
* @version 1.0
*/
public class TeamNameException extends TeamException{
public TeamNameException() {
}
public TeamNameException(String message) {
super(message);
}
}

Write controller

package com.kkb.controller;
import com.kkb.exceptions.TeamException;
import com.kkb.exceptions.TeamIdException;
import com.kkb.exceptions.TeamNameException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
/**
* ClassName: ExController
* Controller for testing exception handling
* @author wanglina
* @version 1.0
*/
@Controller
@RequestMapping("ex")
public class ExController {
@RequestMapping("test01/{id}/{name}")
public ModelAndView test01(@PathVariable("id") Integer
teamId,@PathVariable("name") String teamName) throws TeamIdException,
TeamNameException{
ModelAndView mv=new ModelAndView();
if(teamId<=1000){
throw new TeamIdException("teamId wrongful! Must be above 1000!");
}
if("test".equals(teamName)){
throw new TeamNameException("teamName wrongful! out of commission test!");
}
System.out.println(10/0);
mv.setViewName("ok");
return mv;
}
@ExceptionHandler(value =
{TeamIdException.class,TeamNameException.class,Exception.class})
public ModelAndView exHandler(Exception ex){
ModelAndView mv=new ModelAndView();
mv.addObject("msg",ex.getMessage());
if(ex instanceof TeamIdException)
mv.setViewName("idError");
else if(ex instanceof TeamNameException)
mv.setViewName("nameError");
else
mv.setViewName("error");
return mv;
}
}

Write error jsp,idError.jsp,nameError.jsp page

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>error</title>
</head>
<body>
<h1>Default error page--${msg}</h1>
</body>
</html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>id error</title>
</head>
<body>
<h1>teamId Error----${msg}</h1>
</body>
</html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>name error</title>
</head>
<body>
<h1>teamName error---${msg}</h1>
</body>
</html>

9.3 optimization

Generally, exception handling methods are specifically defined in a class as a global exception handling class.
Using the annotation @ ControllerAdvice, which is called "controller enhancement", is to enhance the function of the controller object. use
@@ ExceptionHandler can be used in the class decorated by ControllerAdvice.
When the method modified with @ RequestMapping annotation throws an exception, the exception handling method in the class modified with @ ControllerAdvice will be executed.
@The class of ControllerAdvice annotation needs package scanning, otherwise the object cannot be created.
<context:component-scan base-package="com.kkb.exceptions"/>
Define the global exception handling class:

package com.kkb.exceptions;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;
/**
* ClassName: GlobalExceptionHandler
* Custom global exception handling class
* @author wanglina
* @version 1.0
*/
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(value = TeamIdException.class)
public ModelAndView exHandler1(Exception ex){
ModelAndView mv=new ModelAndView();
mv.addObject("msg",ex.getMessage());
mv.setViewName("idError");
return mv;
}
@ExceptionHandler(value = TeamNameException.class)
public ModelAndView exHandler2(Exception ex){
ModelAndView mv=new ModelAndView();
mv.addObject("msg",ex.getMessage());
mv.setViewName("nameError");
return mv;
}
@ExceptionHandler(value = TeamException.class)
public ModelAndView exHandler4(Exception ex){
ModelAndView mv=new ModelAndView();
mv.addObject("msg",ex.getMessage());
mv.setViewName("nameError");
return mv;
}
@ExceptionHandler(value = Exception.class)
public ModelAndView exHandler3(Exception ex){
ModelAndView mv=new ModelAndView();
mv.addObject("msg",ex.getMessage());
mv.setViewName("error");
return mv;
}
}

10. Interceptor

Interceptor in spring MVC is very important. Its main function is to intercept the specified user request and carry out corresponding preprocessing and post-processing. The time point of interception is "the processor mapper HandlerMapping maps the processor class to be executed according to the request submitted by the user, and also finds the processor adapter to execute the processor class, before the processor adapter HandlerAdaptor executes the processor".
When the processor mapper maps the processor class to be executed, the interceptor and the processor have been combined into a processor execution chain HandlerExecutionChain and returned to the front-end controller.
To customize the interceptor, you need to implement the HandlerInterceptor interface. The interface contains three methods:

preHandle(request,response, Object handler):
This method is executed before the processor method executes. The return value is boolean. If it is true, the processor method will be executed immediately, and the afterCompletion() method will be put into a special method stack for execution.

postHandle(request,response, Object handler,modelAndView):
The method is executed after the processor method is executed. If the processor method is not finally executed, the method will not be executed. Because this method is executed after the processor method is executed, and the method parameters include ModelAndView, this method can modify the processing result data of the processor method and the jump direction.

afterCompletion(request,response, Object handler, Exception ex):
When the preHandle() method returns true, it will put the method into a special method stack and execute the method after the work required to respond to the request is completed. That is, this method is executed after the front-end controller renders (data fills) the response page. At this time, no further operation on ModelAndView will help the response.

After completion is the last method executed to clear resources, such as adding data to the Controller method

10.1 custom interceptors

package com.kkb.interceptor;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* ClassName: MyInterceptor
* custom interceptor 
* @author wanglina
* @version 1.0
*/
public class MyInterceptor implements HandlerInterceptor {
//Execution time: before the controller method executes and before ModelAndView returns
//Usage scenario: login authentication
// Return value: true: continuing to execute the controller method means release; false: not continuing to execute the controller method means interception
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse
response, Object handler) throws Exception {
System.out.println("preHandle-------------------");
return true;
}
//Execution time: hou after the controller method is executed, there is an opportunity to modify the return value before ModelAndView returns
//Usage scenario: log in, record the login ip and time
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse
response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("postHandle-------------------");
}
//Execution time: after the controller method is executed and ModelAndView returns, there is no chance to modify the return value
//Usage scenario: some operations of global resources
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse
response, Object handler, Exception ex) throws Exception {
System.out.println("afterCompletion-------------------");
}
}
package com.kkb.interceptor;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* ClassName: MyInterceptor
* custom interceptor 
* @author wanglina
* @version 1.0
*/
public class MyInterceptor2 implements HandlerInterceptor {
//Execution time: before the controller method executes and before ModelAndView returns
//Usage scenario: login authentication
// Return value: true: continuing to execute the controller method means release; false: not continuing to execute the controller method means interception
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse
response, Object handler) throws Exception {
System.out.println("preHandle2-------------------");
return true;
}
//Execution time: hou after the controller method is executed, there is an opportunity to modify the return value before ModelAndView returns
//Usage scenario: log in, record the login ip and time
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse
response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("postHandle-2------------------");
}
//Execution time: after the controller method is executed and ModelAndView returns, there is no chance to modify the return value
//Usage scenario: some operations of global resources
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse
response, Object handler, Exception ex) throws Exception {
System.out.println("afterCompletion2-------------------");
}
}

10.2 configure interceptors

In spring MVC Add the following configuration to XML

<!-- Configuring Interceptors  -->
<mvc:interceptors>
<!-- Multiple interceptors can be configured at the same time, and the configuration order is the interception order of interceptors -->
<mvc:interceptor>
<!-- The interceptor is useful for intercepting the request path/** -->
<mvc:mapping path="/**"/>
<!-- Designated interceptor -->
<bean class="com.kkb.interceptor.MyInterceptor2"
id="myInterceptor"></bean>
</mvc:interceptor>
<mvc:interceptor>
<!-- The interceptor is useful for intercepting the request path/** -->
<mvc:mapping path="/**"/>
<!-- Designated interceptor -->
<bean class="com.kkb.interceptor.MyInterceptor2"
id="myInterceptor2"></bean>
</mvc:interceptor>
</mvc:interceptors>
If there are multiple interceptors:
preHandle: Follow the sequence before and after configuration
postHandle: Execute in reverse order before and after configuration
afterCompletion: Execute in reverse order before and after configuration

11. File upload and download

Spring MVC provides direct support for file upload, which is realized through plug and play MultipartResolver Spring has an implementation class of MultipartResolver: CommonsMultipartResolver.
In the context of Spring MVC, MultipartResolver is not installed by default, so file upload cannot be processed by default. If you want to use Spring's file upload function, you need to configure MultipartResolver in the context first.

11.1 file upload

(1) Add dependency

<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>

(2)springmvc. Configure MultipartResolver in XML file:

<!--File upload-->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
</bean>

(3)fileHandle.jsp page form

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>File operation</title>
</head>
<body>
<form action="/file/upload" method="post" enctype="multipart/form-data">
Please select a file:<input type="file" name="myFile" /><br/>
<button type="submit">Upload file</button>
</form>
</body>
</html>

(4) Configure java code (note to create a folder to save the uploaded file)

package com.kkb.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;
/**
* ClassName: FileController
* Controller for file operations
* @author wanglina
* @version 1.0
*/
@Controller
@RequestMapping("file")
public class FileController {
/**
* File upload
* @param myFile
* @param request
* @return
*/
@RequestMapping("upload")
public String upload(@RequestParam("myFile") MultipartFile myFile,
HttpServletRequest request){
//Get the original name of the file D: \ te aa\txcat. jpg
String originalFilename = myFile.getOriginalFilename();
// In actual development, it is generally necessary to rename the file for storage
// File name stored in the server = random string + suffix of the source file obtained according to the actual name
String fileName= UUID.randomUUID().toString().replace("-","")
+originalFilename.substring(originalFilename.lastIndexOf("."));
System.out.println(fileName);
//File storage path
String realPath =
request.getServletContext().getRealPath("/uploadFile")+"/";
try {
myFile.transferTo(new File(realPath+fileName));//The real file upload to the server refers to
 Fixed position
System.out.println("Upload succeeded!"+realPath+fileName);
} catch (IOException e) {
e.printStackTrace();
}
return "ok";
}
@RequestMapping("hello")
public String hello(){
return "fileHandle";
}
}

Optimization: if you need to limit the size and type of files:

<!--Configuring Interceptors -->
<mvc:interceptors>
......
<mvc:interceptor>
<mvc:mapping path="/**"/>
<bean class="com.kkb.interceptor.FileInterceptor"
id="fileInterceptor"></bean>
</mvc:interceptor>
</mvc:interceptors>
<!--File upload-->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!--File upload size limit in bytes B Unit 5 m :1024*1024*5 1M=1024KB 1KB=1024B-->
<property name="maxUploadSize" value="5242880"/>
<property name="defaultEncoding" value="utf-8"/>
</bean>
package com.kkb.interceptor;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Iterator;
import java.util.Map;
/**
* ClassName: FileInterceptor
* Interceptor for file suffix processing
* @author wanglina
* @version 1.0
*/
public class FileInterceptor implements HandlerInterceptor {
/**
* Judge whether the file suffix is legal before uploading the file
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse
response, Object handler) throws Exception {
//Determine whether it is a file upload request
boolean flag=true;
if(request instanceof MultipartHttpServletRequest){
MultipartHttpServletRequest multipartRequest=
(MultipartHttpServletRequest) request;
Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
//Traversal file
Iterator<String> iterator = fileMap.keySet().iterator();
while(iterator.hasNext()){
String key = iterator.next();
MultipartFile file = multipartRequest.getFile(key);
String originalFilename = file.getOriginalFilename();
String hz =
originalFilename.substring(originalFilename.lastIndexOf("."));
//Judge whether the suffix is legal
if(!hz.toLowerCase().equals(".png") &&
!hz.toLowerCase().equals(".jpg")){
request.getRequestDispatcher("/jsp/fileTypError.jsp").forward(request,response)
;
flag=false;
}
}
}
return flag;
}
}

Upload file type error, jump to the page fileerror jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>fileError</title>
</head>
<body>
<h1>Wrong file upload type! Suffix must be.png Or.jpg</h1>
</body>
</html>

11.2 file download

(1) Front page

 <form action="/file/download" method="post" enctype="multipart/form-data">
<button type="submit">Download pictures-
-4e27abf2c3724985a0877599773143c6.jpg</button>
</form>

(2) Configure processing class methods

 @RequestMapping("download")
public ResponseEntity<byte[]> download(HttpServletRequest request) throws
IOException {
//Specify the path of the file -- ensure that the file exists under the specified path
String
path=request.getServletContext().getRealPath("/uploadFile")+"/4e27abf2c3724985a0
877599773143c6.jpg";
//The object that creates the header information of the response
HttpHeaders headers=new HttpHeaders();
//Tags respond in a stream
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
//Respond to users in the form of attachments
headers.setContentDispositionFormData("attachment",URLEncoder.encode("4e27abf2c
3724985a0877599773143c6.jpg","utf-8"));
File file=new File(path);
ResponseEntity<byte[]> resp=new ResponseEntity<>
(FileUtils.readFileToByteArray(file),headers,HttpStatus.CREATED);
return resp;
}

12. RESTful style

12.1 REST concept

REST (English: Representational State Transfer, referred to as REST, meaning: representational state transition, which describes an architecture style network system, such as web application).
It is a software architecture style and design style, not a standard. It only provides a set of design principles and constraints. It is mainly used for the interactive software of client and server. It is easier to implement the caching mechanism based on this style.
Its core value lies in how to design a REST style network interface.

12.restful concept

REST refers to a set of architectural constraints and principles. Applications or designs that meet these constraints and principles are RESTful.
RESTful features:
Resources: all things on the Internet can be abstracted as resources. It can be a text, a picture, a song, a service, in short, it is a concrete existence. A URI (uniform resource locator) can be used to point to it, and each resource corresponds to the URI of a feature. To obtain this resource, you can access its URI, so the URI is the unique identifier of each resource.
Representation: the form in which resources are concretely presented, which is called its representation. For example, text can be expressed in txt format, HTML format, XML format, JSON format, or even binary format.
State transfer: every time a request is issued, it represents an interactive process between the client and the server. All protocols are saved in one state on the HTTP server. Therefore, if the client wants to operate the server, it must use some means to make the server "state transfer". This transformation is based on the presentation layer, so it is "presentation layer state transformation".
Specifically, in the HTTP protocol, there are four verbs representing the operation mode: GET, POST, PUT and DELETE. They correspond to each other
There are four basic operations: GET is used to obtain resources, POST is used to create new resources, PUT is used to update resources, and DELETE is used to DELETE resources.
The original method of operating resources:
   http://localhost:8080/getExpress.do?id=1
   http://localhost:8080/saveExpress.do
   http://localhost:8080/updateExpress.do
   http://localhost:8080/deleteExpress.do?id=1
Of course, there is no problem with the original way, but it would be better if there was a more concise way. At this time, it is RESTful style.
Using RESTful operation resources:
Get / expressions # query all express information lists
GET /express/1006 # query an express message
POST /express # create a new express message
PUT /express/1006 # update one express message (all updated)
PATCH /express/1006 # update an express message (partial update)
DELETE /express/1006 # delete an express message

12.3 API design / URL design

12.3.1 verb + object

The core idea of RESTful is that the data operation instructions sent by the user of the client are in the structure of "Verb + object". For example, for the command GET / expressions, GET is a verb and / expressions is an object.

Verbs are usually five HTTP methods, corresponding to CRUD operations.
GET: Read
POST: Create
PUT: Update
PATCH: Update, usually a partial Update
Delete: delete
PS:
1. According to the HTTP specification, all verbs are capitalized.
2. Some agents only support POST and GET methods. In order to use these limited methods to support RESTful API, a method is needed to override the original HTTP method. Use the custom HTTP header X-HTTP-Method-Override to override the POST method

12.3.2 the object must be a noun

The object is the URL of the API and the object of the HTTP verb. It should be a noun, not a verb.
For example, / expressions is the correct URL.
The following URL s are not recommended because they are written with verbs, not recommended.
   /getAllExpresses
   /getExpress
   /createExpress
   /deleteAllExpress
ps: don't confuse the singular and plural nouns. To keep it simple, use only the plural for all resources.

12.3.3 avoid multi-level URL s

If there are multi-level classifications in resources, it is not recommended to write multi-level URL s. For example, to get a member of a team, someone might write:
   GET /team/1001/player/1005
The semantics of this writing method is not clear enough, so it is recommended to use the query string as the suffix and rewrite it as
   GET /team/1001?player=1005.
Another example is to query all the express that have not been taken out. How should you write it?
Get / expressions / statusnot recommended
   GET /expresses? Stu = false recommended

12.5 server response

The information returned by the server generally does not recommend plain text, but recommends that you choose JSON objects, because this can return standard structured data.
Therefore, the content type attribute of the HTTP header of the server response should be set to application/json. When the client requests, it should also clearly tell the server that JSON format can be accepted, that is, the ACCEPT attribute of the HTTP header of the request should also be set to application/json.
When an error occurs, in addition to returning the status code, you should also return the error information. So we can encapsulate the information to be returned by ourselves.

12.6 cases

12.6.1 restful query

Front end page restful jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>restful</title>
<script src="/js/jquery-1.11.1.js"></script>
</head>
<body>
<form id="myForm" action="" method="post">
team ID:<input type="text" name="teamId" id="teamId" /><br/>
Team name:<input type="text" name="teamName" /><br/>
Team position:<input type="text" name="location" /><br/>
<button type="button" id="btnGetAll">Query all GET</button>
<button type="button" id="btnGetOne">Query single GET</button>
<button type="button" id="btnPost">add to POST</button>
<button type="button" id="btnPut">to update PUT</button>
<button type="button" id="btnDel">delete DELETE</button>
</form>
<p id="showResult"></p>
</body>
</html>
<script>
//Bind events to the button after the page is loaded
$(function () {
//Bind click events to query all GET buttons
$("#btnGetAll").click(function () {
//Initiate asynchronous request
$.ajax({
type: "GET",
url: "/teams", //RESTful style API definition
data: "",
dataType:"json",
success: function(list){
alert( "Data Saved: " + list );
var str="";
for(var i=0;i<list.length;i++){
var obj=list[i];
str+=obj.teamId+"----"+obj.teamName+"----
"+obj.location+"<br/>";
}
$("#showResult").html(str);
}
});
});
//Bind a single GET button to a query click event
$("#btnGetOne").click(function () {
//Initiate asynchronous request
$.ajax({
type: "GET",
url: "/team/"+$("#teamId").val(), //RESTful style API definition
data: "",
dataType:"json",
success: function(obj){
alert( "Data Saved: " + obj );
if(obj==""){
$("#showResult").html(" data without composite conditions! ");
}else
$("#showResult").html(obj.teamId+"----"+obj.teamName+"----
"+obj.location+"<br/>");
}
});
});
});
</script>

Controller restfulcontroller java

package com.kkb.controller;
import com.kkb.pojo.Team;
import org.springframework.stereotype.Controller;
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.ResponseBody;
import java.util.ArrayList;
import java.util.List;
/**
* ClassName: RestfulController
* restful Style controller
* @author wanglina
* @version 1.0
*/
@Controller
public class RestfulController {
private static List<Team> teamList;
static {
teamList=new ArrayList<>(3);
for(int i=1;i<=3;i++){
Team team=new Team();
team.setTeamId(1000+i);
team.setTeamName("Lakers"+i);
team.setLocation("Los Angeles"+i);
teamList.add(team);
}
}
/**
* Query all teams
* @return
*/
@RequestMapping(value = "/teams",method = RequestMethod.GET)
@ResponseBody
public List<Team> getAll(){
System.out.println("Query all GET--Request initiated---------");
return teamList;
}
/**
* Query individual teams by id
* @return
*/
@RequestMapping(value = "/team/{id}",method = RequestMethod.GET)
@ResponseBody
public Team getOne(@PathVariable("id")int id){
System.out.println("Query single GET--Request initiated---------");
for (Team team : teamList) {
if(team.getTeamId()==id){
return team;
}
}
return null;
}
@RequestMapping("hello")
public String hello(){
return "restful";
}
}

12.6.2 addition of restful style

Add the following content to the script on the front page:
//Add POST button binding click event to

$("#btnPost").click(function () {
alert($("#myForm").serialize());
//Initiate asynchronous request
$.ajax({
type: "POST",
url: "/team", //RESTful style API definition
data: $("#myForm").serialize(), / / all data of the form is appended to the URL in the form of" & "
/team?teamId=1006&teamName=kuaichuan&location=las
dataType:"json",
success: function(msg){
//alert( "Data Saved: " + msg );
$("#showResult").html(msg);
}
});
});

Add method to controller

/**
* Add a team
*/
@RequestMapping(value = "team",method = RequestMethod.POST)
@ResponseBody
public String add(Team team){
System.out.println("add to POST--Request initiated---------");
teamList.add(team);
return "201";
}

12.6.3 RESTful style update

Add the following content to the script on the front page:
$("#btnPut").click(function(){
alert($("#myForm").serialize());
$.ajax({
type: "POST",
url: "/team/"+$("#teamId").val(),
data: $("#myForm").serialize()+"&_method=PUT",
dataType:"json",
//headers:{"X-HTTP-Method-Override":"GET"},
success: function(msg){
$("#showResult").html(msg);
}
});
});

Add method to controller

@RequestMapping(value = "/team/{id}",method = RequestMethod.PUT)
@ResponseBody
public String update(@PathVariable("id") int id,Team newTeam){
System.out.println(id);
for (Team team : teamList) {
if(team.getTeamId()==id){
team.setTeamName(newTeam.getTeamName());
team.setLocation(newTeam.getLocation());
return "204";
}
}
return "404";
}

12.6.4 deletion of restful style

Add the following content to the script on the front page:

//Bind the DELETE button to a click event
$("#btnDel").click(function () {
alert($("#myForm").serialize());
//Initiate asynchronous request
$.ajax({
type: "POST",
url: "/team/"+$("#teamId").val(), //RESTful style API definition
data: "_method=DELETE",
success: function(msg){
//alert( "Data Saved: " + msg );
$("#showResult").html(msg);
}
});
});

Add method to controller

/**
* Delete a team by ID
*/
@RequestMapping(value = "team/{id}",method = RequestMethod.DELETE)
@ResponseBody
public String del(@PathVariable("id")int id){
System.out.println("delete DELETE--Request initiated---------");
for (Team team1 : teamList) {
if(team1.getTeamId()==id){
teamList.remove(team1);
return "204";
}
}
return "500";
}

12.6.5 problems encountered in updating and deleting restful style

12.6.5.1 problems encountered:

In Ajax, the parameters passed in Restful PUT and DELETE requests are invalid, and the parameter value passed to the background is null

12.6.5.2 causes:

Tomcat encapsulates the request parameters:
   1. Encapsulate the data in the request body into a map
   2.request.getParameter(key) will take value from this map
   3. When spring MVC encapsulates POJO objects, it will request the value of each attribute in the POJO getParamter();
When AJAX sends a PU or DELETE request, the data in the request body passes through request Getparamter() can't get it.
Once Tomcat detects that it is PUT or DELETE, it will not encapsulate the data in the request body as map. Only the request in the form of POST encapsulates the request as map
map.

12.6.5.3 solution:

1. The ajax in the front-end page will add in the url when sending the request&_ Method = "PUT" or&_ Method = "DELETE"

2,web. Configuration in XML
When configuring multiple filters, pay attention to the order

<!-- use Rest Stylized URI Change the page to normal post Transfer request to specified delete perhaps put request
 Principle: in Aajx Send in post After request, take_method Parameter, change it to PUT,perhaps DELETE request-->
<filter>
<filter-name>httpMethodFilter</filter-name>
<filter-class>
org.springframework.web.filter.HiddenHttpMethodFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>httpMethodFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

12.7 self packaging response results

12.7.1 encapsulated entity class

package com.kkb.vo;
import java.util.List;
/**
* ClassName: AjaxResultVO
* Self encapsulated returned result class
* @author wanglina
* @version 1.0
*/
public class AjaxResultVO<T> {
private Integer code;//Returned status code
private String msg;//Returned information (general error information or abnormal information)
private List<T> list; //The returned data may be a collection
private T obj;//The returned data may be an object
public AjaxResultVO() {
code = 200;
msg = "OK";
list = null;
obj = null;
}
public AjaxResultVO(Integer code, String msg) {
this.code = code;
this.msg = msg;
}
public AjaxResultVO(Integer code, String msg, List<T> list) {
this.code = code;
this.msg = msg;
this.list = list;
}
public AjaxResultVO(Integer code, String msg, T obj) {
this.code = code;
this.msg = msg;
this.obj = obj;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public List<T> getList() {
return list;
}
public void setList(List<T> list) {
this.list = list;
}
public T getObj() {
return obj;
}
public void setObj(T obj) {
this.obj = obj;
}
}

12.7.2 modify the return value of the controller

package com.kkb.controller;
import com.kkb.pojo.Team;
import com.kkb.vo.AjaxResultVO;
import org.springframework.stereotype.Controller;
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.ResponseBody;
import java.util.ArrayList;
import java.util.List;
/**
* ClassName: RestfulController
* restful Style controller
* @author wanglina
* @version 1.0
*/
@Controller
public class RestfulController {
private static List<Team> teamList;
static {
teamList=new ArrayList<>(3);
for(int i=1;i<=3;i++){
Team team=new Team();
team.setTeamId(1000+i);
team.setTeamName("Lakers"+i);
team.setLocation("Los Angeles"+i);
teamList.add(team);
}
}
/**
* Delete a team by ID
*/
@RequestMapping(value = "team/{id}",method = RequestMethod.DELETE)
@ResponseBody
public AjaxResultVO<Team> del(@PathVariable("id")int id){
System.out.println("delete DELETE--Request initiated---------");
for (Team team1 : teamList) {
if(team1.getTeamId()==id){
teamList.remove(team1);
return new AjaxResultVO<Team>();
}
}
return new AjaxResultVO<Team>(500,"To delete ID non-existent~~~");
}
/**
* Update a team by ID
*/
@RequestMapping(value = "team/{id}",method = RequestMethod.PUT)
@ResponseBody
public AjaxResultVO<Team> add(@PathVariable("id")int id, Team team){
System.out.println("to update PUT--Request initiated---------");
for (Team team1 : teamList) {
if(team1.getTeamId()==id){
team1.setLocation(team.getLocation());
team1.setTeamName(team.getTeamName());
return new AjaxResultVO<Team>();
}
}
return new AjaxResultVO<Team>(500,"To update ID non-existent~~~");
}
/**
* Add a team
*/
@RequestMapping(value = "team",method = RequestMethod.POST)
@ResponseBody
public AjaxResultVO<Team> add(Team team){
System.out.println("add to POST--Request initiated---------");
teamList.add(team);
return new AjaxResultVO<>(200,"OK");
}
/**
* Query all teams
* @return
*/
@RequestMapping(value = "teams",method = RequestMethod.GET)
@ResponseBody
public AjaxResultVO<Team> getAll(){
System.out.println("Query all GET--Request initiated---------");
return new AjaxResultVO<>(200,"OK",teamList);
}
/**
* Query individual teams by id
* @return
*/
@RequestMapping(value = "team/{id}",method = RequestMethod.GET)
@ResponseBody
public AjaxResultVO<Team> getOne(@PathVariable("id")int id){
System.out.println("Query single GET--Request initiated---------");
for (Team team : teamList) {
if(team.getTeamId()==id){
return new AjaxResultVO<>(200,"OK",team);
}
}
return null;
}
@RequestMapping("hello")
public String hello(){
return "restful";
}
}

Front page modification 12.3

<script>
//Bind events to the button after the page is loaded
$(function () {
//Bind the DELETE button to a click event
$("#btnDel").click(function () {
alert($("#myForm").serialize());
//Initiate asynchronous request
$.ajax({
type: "POST",
url: "/team/"+$("#teamId").val(), //RESTful style API definition
data: "_method=DELETE",
success: function(vo){
if(vo.code==200){
$("#showResult").html(" deletion succeeded! ");
}else {
$("#showResult").html(vo.msg);
}
}
});
});
//Bind click event to update PUT button
$("#btnPut").click(function () {
alert($("#myForm").serialize());
//Initiate asynchronous request
$.ajax({
type: "POST",
url: "/team/"+$("#teamId").val(), //RESTful style API definition
data: $("#myForm").serialize()+"&_ Method = put "&
Form append in URL behind /team?teamId=1006&teamName=kuaichuan&location=las
dataType:"json",
success: function(vo){
if(vo.code==200){
$("#Showresult ". HTML (" update succeeded! ");
}else {
$("#showResult").html(vo.msg);
}
}
});
});
//Add POST button binding click event to
$("#btnPost").click(function () {
alert($("#myForm").serialize());
//Initiate asynchronous request
$.ajax({
type: "POST",
url: "/team", //RESTful style API definition
data: $("#myForm").serialize(), / / all data of the form is appended to the URL in the form of" & "
/team?teamId=1006&teamName=kuaichuan&location=las
dataType:"json",
success: function(vo){
if(vo.code==200){
$("#showResult").html(" added successfully! ");
}else {
$("#showResult").html(vo.msg);
}
}
});
});
//Bind click events to query all GET buttons
$("#btnGetAll").click(function () {
//Initiate asynchronous request
$.ajax({
type: "GET",
url: "/teams", //RESTful style API definition
data: "",
dataType:"json",
success: function(vo) {
if (vo.code == 200) {
var list=vo.list;
var str = "";
for (var i = 0; i < list.length; i++) {
var obj = list[i];
str += obj.teamId + "----" + obj.teamName + "----" +
obj.location + "<br/>";
}
$("#showResult").html(str);
}else{
$("#showResult").html(vo.msg);
}
}
});
});
//Bind a single GET button to a query click event
$("#btnGetOne").click(function () {
//Initiate asynchronous request
$.ajax({
type: "GET",
url: "/team/"+$("#teamId").val(), //RESTful style API definition
data: "",
dataType:"json",
success: function(vo){
if(vo.code==200){
var obj=vo.obj;
if(obj==""){
$("#showResult").html(" data without composite conditions! ");
}else {
$("#showResult").html(obj.teamId + "----" +
obj.teamName + "----" + obj.location + "<br/>");
}
}else{
$("#showResult").html(vo.msg);
}
}
});
});
});
</script>

Reference: This is also my reprint. This note will be changed. There is no link in the original text. It is directly sent. Link and fill in the official website. See the online disk for details
Data download link (note + code + others): Baidu online disk
Link: https://pan.baidu.com/s/1c-XEebooSrVn9ItRN-JuYQ
Extraction code: 1111
Thank you for reading. I wish you all the best from now on.

Topics: Java Microservices mvc