Introduction to the Spring MVC Framework (Recommended Collection)
❤️Hope your blogger gives you a triple company + attention!!!
Learn video from: Station B says, if you are interested, you can watch it
SSM: mybatis + Spring + Spring MVC MVC three-tier architecture
SpringMVC + Vue + SpringBoot + SpringCloud + Linux
SSM = JavaWeb for project;
Spring: IOC and APO
SpringMVC: The execution process of SpringMVC!
SpringMVC: SSM Framework Integration!
Spring
MVC: Model (dao, service) View (jsp) Controller (Servlet)
dao
service
Serlet: Forward, redirect
jsp/html
Front End Data Transfer Entity Class
Entity class: username, password, birthday, hobbies,...20
Front End: User Name Password
pojo: User
vo: UserVo
dto:
JSP: Essentially a Servlet
Assume: Is the architecture of your project designed or evolved?speech
- Alibaba PHP
- As users grow, Java
- Wang Jian goes to IOE MySQL
- MySQL : MySQL–> AliSQL. AliRedis
- All in one -->Microservices
MVC :
MWM: M V VM ViewModel: Bidirectional Binding
1. What is MVC
- MVC is short for Model, View, Controller and is a software design specification.
- Is the way to organize code by separating business logic, data, and display.
- The main role of MVC is to reduce the two-way coincidence between views and business logic.
- MVC is not a design mode, MVC is an architecture mode. Of course, there are differences between different MVCs.
**Model: **Data model, which provides data to be displayed and therefore contains data and behavior, can be considered a domain model or a JavaBean component (which contains data and behavior), but is now generally separated: Value Object (Data Dao) and Service (Behavior Service)That is, the model provides functions such as model data query and model data status update, including data and business.
**View: (View): ** Responsible for model display, which is typically what the user interface we see and what the customer wants to see.
**Controller: (Controller): ** Receives user requests, delegates processing to the model (state change), and returns the returned model data to the view after processing, which is displayed by the view. That is, the controller does the work of a dispatcher.
The most typical MVC is JSP + servlet + javabean mode.
1.1, Model1 Age
- In the early development of the web, Model1 was commonly used.
- Model1 is mainly divided into two layers, the view layer and the model layer.
Model1 advantages: simple architecture, more suitable for small-scale project development;
Model1 disadvantage: JSP is not single, overloaded, and not easy to maintain
1.2, Model2 Age
Model2 divides a project into three parts, including views, controls, and models.
User sends request
- Servlet receives request data and calls corresponding business logic methods
- When the business is finished, the updated data is returned to the servlet
- The servlet goes to JSP, which renders the page
- Response to Front End Updated Pages
Responsibility analysis:
Controller: Controller
- Get Form Data
- Call business logic
- Go to the specified page
Model: Model
- Business logic
- Save the state of the data
View: View
- Show Page
Model2 not only improves code reuse and project scalability, but also greatly reduces project maintenance costs.The implementation of mode 1 is simple and suitable for rapid development of small-scale projects. The JSP page in Model 1 plays both View and Controller roles, mixing control logic and presentation logic, which results in very low code reuse and increases the difficulty of scalability and maintenance of applications. Model2 eliminates the drawbacks of Model 1.
1.3. Review Servlet
- Create a new Maven project as the parent! pom depends!
<dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.1.9.RELEASE</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.2</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> </dependencies>
2. Create a Moudle:springmvc-01-servlet and add support for Web app s!
3. jar dependency for importing servlet s and JSPS
<dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.2</version> </dependency>
4. Write a Servlet class to handle user requests
package com.kk.servlet; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class HelloServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //1. Get front-end parameters String method = req.getParameter("method"); if (method.equals("add")){ req.getSession().setAttribute("msg","Executed add Method"); } if (method.equals("delete")){ req.getSession().setAttribute("msg","Executed delete Method"); } //2. Call the business tier //3. View forwarding or redirection req.getRequestDispatcher("/WEB-INF/jsp/text.jsp").forward(req,resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req,resp); } }
5. Write Hello.jsp, create a new JSP folder in the WEB-INF directory, and create a new hello.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Kuangshen</title> </head> <body> ${msg} </body> </html>
6. Register Servlet in web.xml
<?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>hello</servlet-name> <servlet-class>com.kk.servlet.HelloServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/hello</url-pattern> </servlet-mapping> <!-- <session-config>--> <!-- <session-timeout>15</session-timeout>--> <!-- </session-config>--> <!-- <welcome-file-list>--> <!-- <welcome-file>index.jsp</welcome-file>--> <!-- </welcome-file-list>--> </web-app>
- Configure Tomcat and start testing
- localhost:8080/user?method=add
- localhost:8080/user?method=delete
8. Access results
What does the MVC framework do
- Method for mapping URLs to java classes or java classes.
- Encapsulate user-submitted data.
- Processing Requests - Invoking Related Business Processing - Encapsulating Response Data.
- Render the data of the response.Representation layer data such as jsp / html.
Explain:
Common server-side MVC frameworks are: Struts, Spring MVC, ASP.NET MVC, Zend Framework, JSF; Common front-end MVC frameworks: vue, angularjs, react, backbone; MVC has evolved into other modes such as MVP, MVVM, and so on.
2. What is Spring MVC
Summary
Spring MVC is part of the Spring Framework and is a lightweight Web framework for MVC implementation based on Java.
View official documents:https://docs.spring.io/spring/docs/5.2.0.RELEASE/spring-framework-reference/web.html#spring-web
Why should we learn Spring MVC?
Features of Spring MVC:
- Lightweight, easy to learn
- Efficient, request-response based MVC framework
- Good Spring compatibility and seamless combination
- Contract over Configuration
- Powerful: RESTful, data validation, formatting, localization, themes, etc.
- Simple and flexible
Spring's web framework is designed around Dispatcher Servlet [Schedule Servlet].
Dispatcher Servlets are used to distribute requests to different processors. Starting with Spring 2.5, users using Java 5 or above can develop in annotation-based form, which is very concise;
Because SpringMVC is good, simple, convenient, easy to learn, naturally integrated with Spring seamlessly (using SpringIoC and Aop), conventions are better than configurations.Ability to perform simple junit tests.Supports Restful style. Exception handling, localization, internationalization, data validation, type conversion, interceptors, and so on... so we have to learn.
The most important thing is that you use more people and more companies.
Central Controller
Spring's web framework is designed around Dispatcher Servlets. Dispatcher Servlets are designed to distribute requests to different processors. Starting with Spring 2.5, users using Java 5 or above can use annotation-based controller declarations.
Like many other MVC frameworks, the Spring MVC framework is request-driven, dispatches requests and provides additional functionality around a central Servlet, and Dispatcher Servlet is an actual Servlet (it inherits from the HttpServlet base class).
Source: The spirit says, if there is infringement, please contact to delete!
SpringMVC works as follows:
When a request is made, the front-end controller intercepts the request, generates a proxy request based on the request parameters, finds the actual controller corresponding to the request, the controller processes the request, creates a data model, accesses the database, and responds to the central controller. The controller uses the model and view to render the view results, returns the results to the central controller, and then returns the results to the request.Of.
Source: The spirit says, if there is infringement, please contact to delete!
SpringMVC Execution Principle
Source: The spirit says, if there is infringement, please contact to delete!
The diagram is a more complete flowchart of SpringMVC. Solid lines represent the technology provided by the SpringMVC framework and do not require a developer implementation. Dashed lines indicate that a developer implementation is required.
Brief analysis of execution process
- Dispatcher Servlet represents the front controller and is the control center for the entire Spring MVC. Users make requests, Dispatcher Servlet receives requests and intercepts them.
- Let's assume the url requested is: http://localhost:8080/SpringMVC/hello
- As above, the url is split into three parts:
- http://localhost : 8080 server domain name
- SpringMVC web site deployed on server
- hello representation controller
- Through analysis, as the url above indicates, request a hello controller for the SpringMVC site located on server localhost:8080.
- Handler Mapping is a processor mapping. Dispatcher Servlet calls Handler Mapping, and Handler Mapping finds Handler based on the request url.
- HandlerExecution represents a specific Handler whose primary purpose is to find a controller based on a url, such as hello.
- HandlerExecution passes parsed information to Dispatcher Servlet, such as resolving controller mappings.
- A Handler Adapter represents a processor adapter that executes a Handler according to specific rules.
- Handler lets the specific Controller execute.
- Controller returns specific execution information to the Handler Adapter, such as ModelAndView.
- HandlerAdapter passes the view logical name or model to Dispatcher Servlet.
- Dispatcher Servlet calls the ViewResolver to resolve the logical view name passed by the Handler Adapter.
- The view parser passes the parsed logical view name to Dispatcher Servlet.
- Dispatcher Servlet calls a specific view based on the result of the view parsed by the view parser.
- The final view is presented to the user.
3. HelloSpring MVC (Configuration Edition)
3.1. Create a new Moudle and add web support!
3.2, Determine the dependency of imported SpringMVC!
3.3, Configure web.xml, register Dispatcher Servlet
<?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"> <!-- To configure DispatchServlet:This is MVC Core; also known as a request distributor, or front-end controller--> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- DispatchServlet To bind SpringMVC Profile--> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc-serlvet.xml</param-value> </init-param> <!-- Startup Level--> <load-on-startup>1</load-on-startup> </servlet> <!-- stay SpringMVC in / /* / : Only match all requests, not matches jsp page /* : Match all requests, including jsp page --> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
3.4, Write the configuration file for SpringMVC! Name: springmvc-servlet.xml: [servletname]-servlet.xml Description, where the name requirements are official
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> </beans>
3.5, Add Processing Mapper
3.6, Add Processor Adapter
3.7, Add View Parser
The following:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- Processor Mapper--> <!-- From here on, BeanNameUrlHandlerMapping: bean find/hello..Find the corresponding class--> <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/> <!-- Processor Adapter--> <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/> <!-- View parser; template engine Thymeleaf Fremarker--> <!--view resolver:DispatcherServlet For him ModelAndView--> <!-- Returned ModelAndView Give it to the view parser to do--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver"> <!-- prefix--> <property name="prefix" value="/WEB-INF/jsp/"/> <!-- Suffix--> <property name="suffix" value=".jsp"/> </bean> <!-- BeanNameUrlHandlerMapping:bean--> <bean id="/hello" class="com.kk.controller.HelloController"></bean> </beans>
3.8. Write the business Controller that we want to operate on, either implement the Controller interface or add comments; we need to return a ModelAndView, load data, cover view;
package com.kk.controller; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.Controller; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; //Note: Here we import the Controller interface first public class HelloController implements Controller { public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { //ModelAndView Model and View ModelAndView mv = new ModelAndView(); //Encapsulate the object and place it in Model AndView. mv.addObject("msg", "HelloSpringMVC!"); //Encapsulate the view you want to jump to and place it in ModelAndView mv.setViewName("hello"); //: /WEB-INF/jsp/hello.jsp return mv; } }
3.9. Give your class to the SpringIOC container (written to springmvc-servlet.xml) and register the bean s
<!--Handler--> <bean id="/hello" class="com.kuang.controller.HelloController"/>
3.10. Write a jsp page to jump to show the data stored in ModelandView and our normal page;
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> ${msg} </body> </html>
3.1.1, Configure Tomcat to start the test!
Possible problems: 404 visits, troubleshooting steps:
- Check the console output to see if any jar packages are missing.
- If the jar package exists and shows no output, add lib dependencies to IDEA's project publishing! (same level directory as classes)
**Summary**: Look at this estimate that most of the students can understand the principle, but we will not actually develop it like this, otherwise they will be crazy, and learn what this is! Let's see the annotation version of the implementation, this is SpringMVC The essence, how simple it is, you can see from this picture.
Source: The spirit says, if there is infringement, please contact to delete!
4. Develop SpringMVC using annotations (annotation version)
4.1, Step 1: Create a new Moudle, add web support! Build package structure com.kk.controller
4.2, Step 2: Due to possible resource filtering problems in Maven, we will configure it well
<build> <resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> </resources> </build>
4.3, Step 3: Introduce related dependencies in the pom.xml file:
There are mainly Spring Framework Core Library, Spring MVC, servlet, JSTL, etc. We have introduced in Parent Dependency!
4.4, Step 4: Configure web.xml
Note:
- Note the web.xml version, want the latest version!
- Register Dispatcher Servlet
- Configuration files associated with SpringMVC
- Start Level 1
- The mapping path is /[Do not use /*, 404]
Step 5: Add Spring MVC Profile
- Make IOC's annotations work
- Static resource filtering: HTML.JS.CSS.Pictures, Videos...
- Annotation Driver for MVC
- Configure View Parser
Add the springmvc-servlet.xml configuration file in the resource directory in a form similar to the Spring container configuration. In order to support annotation-based IOC, the function of automatically scanning packages is set up with the following configuration information:
<?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 https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!-- Automatically scan packages for comments under specified packages to take effect,from IOC Unified container management --> <context:component-scan base-package="com.kk.controller"/> <!-- Give Way Spring MVC Do not process static resources Filter out some static resources, such as.css .js .html .mp3--> <mvc:default-servlet-handler /> <!-- Support mvc Annotation Driver stay spring Usually used in@RequestMapping Annotations to complete mapping relationships To make@RequestMapping Comments take effect Must be registered in context DefaultAnnotationHandlerMapping And a AnnotationMethodHandlerAdapter Example These two instances are handled at the class level and the method level, respectively. and annotation-driven Configuration helps us automate the injection of these two instances. --> <mvc:annotation-driven /> <!-- view resolver --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver"> <!-- prefix --> <property name="prefix" value="/WEB-INF/jsp/" /> <!-- Suffix --> <property name="suffix" value=".jsp" /> </bean> </beans>
In the view parser, we store all views in the / WEB-INF / directory, which ensures view security because the files in this directory are not directly accessible by clients.
Step 6: Create Controller
Write a Java control class: com.kuang.controller.HelloController, note the coding specifications
package com.kk.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class HelloController { @RequestMapping("/hello") public String hello(Model model){ //Encapsulate data model.addAttribute("msg","Hello SpringMVCAnnotation"); return "hello"; //This is handled by the view parser; } }
- @Controller is for the Spring IOC container to be scanned automatically when it is initialized;
- @RequestMapping is for mapping request paths, where access should be/HelloController/hello because both classes and methods have mappings;
- Parameters of type Model are declared in the method to bring data from the Action into the view;
- The result returned by the method is the view name hello, with the prefix and suffix in the configuration file becoming WEB-INF/jsp/hello.jsp.
Step 7: Create View Layer
Create hello.jsp in the WEB-INF/ jsp directory, and the view can take out and display the information brought back from the Controller directly.
You can remove values or objects stored in the Model by EL representation.
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>SpringMVC</title> </head> <body> ${msg} </body> </html>
4.8, Step 8: Configure Tomcat to run
Configure Tomcat, open the server, and access the corresponding request path!
Run Successfully!
Summary
The steps are very simple:
- Create a new web project
- Import related jar packages
- Write web.xml, register Dispatcher Servlet
- Write a springmvc configuration file
- The next step is to create the corresponding control class, controller
- Finally, improve the correspondence between the front-end view and the controller
- Test run debugging.
There are three main pieces that must be configured to use springMVC:
Processor Mapper, Processor Adapter, View Parser
Typically, we only need to manually configure the view parser, whereas the processor mapper and the processor adapter only need to turn on the annotation driver, eliminating much xml configuration
5. Controller and RestFul Styles
Controller
-
Controllers provide complex behavior for accessing applications, usually through interface definitions or annotation definitions.
-
The controller is responsible for parsing the user's request and converting it into a model.
-
A controller class in Spring MVC can contain multiple methods
-
There are many ways to configure Controller in Spring MVC
Let's see what we can do:
Implement Controller interface
//Classes implementing this interface get controller functionality public interface Controller { //Processing the request and returning a model and view object ModelAndView handleRequest(HttpServletRequest var1, HttpServletResponse var2) throws Exception; }
test
- Create a new Moudle, springmvc-04-controller. Make a copy of 03 just now, and we'll do it!
- Delete HelloController
- The configuration file for mvc leaves only the view parser!
- Write a Controller class, Controller Test1
package com.kk.controller; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.Controller; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; //A class that implements the Controller interface is a controller. public class ControllerTest01 implements Controller { @Override public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception { ModelAndView mv = new ModelAndView(); mv.addObject("msg","ControllerTest01!"); //Add data mv.setViewName("test"); //Set the jump view to which to jump from this control, such as jumping to test (.jps page) return mv; } }
After writing, go to the Spring configuration file to register the requested bean; name corresponds to the request path, class corresponds to the class that handles the request
<bean name="/test" class="com.kk.controller.ControllerTest01"/>
Write the front-end test.jsp, note that it is written in the WEB-INF/jsp directory, corresponding to our view parser
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> ${msg} </body> </html>
Configure Tomcat to run tests, and all I do not have here is a /, so I do not request to add a project name.
Explain:
- Implementing interface Controller definition controllers is an older approach
- The disadvantage is that there is only one method in a controller, and if more than one method is needed, more than one Controller needs to be defined; the way of definition is more cumbersome;
Use the comment @Controller
- The @Controller annotation type is used to declare that an instance of the Spring class is a controller (three additional annotations were mentioned when talking about IOC);
- Spring can use a scanning mechanism to find all annotation-based controller classes in the application. To ensure that Spring can find your controller, you need to declare component scanning in the configuration file.
<context:component-scan base-package="com.kk.controller"/>
Add a ControllerTest2 class, implemented with annotations;
package com.kk.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; @Controller //Represents that this class will be taken over by Spring, and all the methods in this annotated class, // If the return value is a String and there are specific pages to jump, it will be parsed by the view parser; public class ControllerTest02{ @RequestMapping("/test2") public String test1(Model model){ model.addAttribute("msg","ControllerTest02!"); return "test"; } }
Run tomcat tests
You can see that both of our requests can point to a view, but the results of the page are different, from which you can see that the view is reused and that there is a weak coupling between the controller and the view.
RequestMapping
@RequestMapping
- The @RequestMapping annotation is used to map a url to a controller class or a specific handler method. It can be used on classes or methods. On classes, all methods in a class that respond to requests are represented by the address as the parent path.
package com.kk.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; @Controller @RequestMapping("c3") public class ControllerTest03 { @RequestMapping("t1") public String test1(Model model){ model.addAttribute("msg","ControllerTest03"); return "test"; } }
Access Path: http://localhost 8080/c3/t1, need to specify the path of the class before specifying the path of the method;
6. RestFul Style (Simple, Efficient, Safe)
concept
Restful is a style for locating and manipulating resources. It's not a standard or protocol, it's just a style. Software designed with this style can be simpler, more hierarchical, and more easily cached.
function
- Resource: Everything on the Internet can be abstracted as a resource
- Resource operations: use POST, DELETE, PUT, GET to operate on resources in different ways.
- Add, delete, modify, query.
Traditional way of operating resources: different parameters to achieve different results! Single method, post and get
Test 1:
1. Create a new class RestFulController
package com.kk.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class RestFulController { //Original wayhttp://localhost:8080/add?a=1&b=10 @RequestMapping("/add") public String test1(int a, int b, Model model){ int res=a+b; model.addAttribute("msg","The result is:"+res); return "test"; } }
Test 2:
2. The @PathVariable annotation can be used in Spring MVC to bind the value of a method parameter to a URI template variable.
package com.kk.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class RestFulController { // RestFul http://localhost:8080/add/a/b @RequestMapping("/add/{a}/{b}") public String test1(@PathVariable int a,@PathVariable int b, Model model){ int res=a+b; model.addAttribute("msg","The result is:"+res); return "test"; } }
Think: The benefits of using path variables?
- Make the path simpler;
- It's easier to get the parameters, and the framework automatically converts the types.
- Access parameters can be constrained by the type of path variable. If the type is different, the corresponding request method cannot be accessed. If the path accessed here is/commit/1/a, the path and method do not match, and the parameter conversion does not fail.
Source: The spirit says, if there is infringement, please contact to delete!
Let's modify the corresponding parameter type and test again
@Controller public class RestFulController { @PostMapping("/add/{a}/{b}") public String test1(@PathVariable int a,@PathVariable String b, Model model){ // int res=a+b; String res=a+b; model.addAttribute("msg","Result 1 is:"+res); return "test"; } }
Source: The spirit says, if there is infringement, please contact to delete!
Specify the request type using the method property
The type used to constrain requests can narrow the request range. Specify the types of request predicates such as GET, POST, HEAD, OPTIONS, PUT, PATCH, DELETE, TRACE, etc.
Let's test:
- Add a method
//Map access path, must be a POST request @RequestMapping(value = "/hello",method = {RequestMethod.POST}) public String test(Model model){ model.addAttribute("msg", "hello!"); return "test"; }
We use the browser address bar for access. The default is Get request. Error 405:
Source: The spirit says, if there is infringement, please contact to delete!
If POST is modified to GET, it is normal;
//Map access path, must be Get request @RequestMapping(value = "/hello",method = {RequestMethod.GET}) public String test(Model model){ model.addAttribute("msg", "hello!"); return "test"; }
Source: The spirit says, if there is infringement, please contact to delete!
Summary:
The @RequestMapping annotation for Spring MVC handles HTTP requests such as GET, PUT, POST, DELETE, and PATCH.
All address bar requests default to HTTP GET type
There are several variations of annotation at the method level:Combining annotations
@GetMapping @PostMapping @PutMapping @DeleteMapping @PatchMapping
@GetMapping is a combined annotation
@Controller public class RestFulController { //Mapping Access Path @GetMapping("/commit/{a}/{b}") public String test2(@PathVariable int a,@PathVariable String b, Model model){ String res=a+b; model.addAttribute("msg","Result 2 is:"+res); return "test"; } }
7. SpringMVC: Result jump in three ways (forwarding, redirecting)
7.1,ModelAndView
Set the ModelAndView object to jump to the specified page based on the view name and view parser.
Page: {View Parser Prefix} + viewName +{View Parser Suffix}
<!-- view resolver --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver"> <!-- prefix --> <property name="prefix" value="/WEB-INF/jsp/" /> <!-- Suffix --> <property name="suffix" value=".jsp" /> </bean>
Corresponding controller s class
public class ControllerTest01 implements Controller { public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception { //Return a model view object ModelAndView mv = new ModelAndView(); mv.addObject("msg","ControllerTest01"); mv.setViewName("test"); return mv; } }
7.2,ServletAPI
No view resolver is required by setting the Servlet API.
- Output through HttpServletResponse
- Redirect via HttpServletResponse
- Forwarding via HttpServletResponse
@Controller public class ResultGo { @RequestMapping("/m1/t1") public void test1(HttpServletRequest req, HttpServletResponse rsp) throws IOException { rsp.getWriter().println("Hello,Spring BY servlet API"); } @RequestMapping("/m2/t2") public void test2(HttpServletRequest req, HttpServletResponse rsp) throws IOException { rsp.sendRedirect("/index.jsp"); } @RequestMapping("/m3/t3") public void test3(HttpServletRequest req, HttpServletResponse rsp) throws Exception { //Forward req.setAttribute("msg","/m3/t3"); req.getRequestDispatcher("/WEB-INF/jsp/test.jsp").forward(req,rsp); } }
7.3,SpringMVC
Forwarding and redirection via SpringMVC - no view resolver is required;
View parser needs to be commented out before testing
package com.kk.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; @Controller public class ModelTest01 { // @RequestMapping("/m1/t1") // public String test(HttpServletRequest request, HttpServletResponse response){ // HttpSession session = request.getSession(); // System.out.println(session.getId()); // // return "/test.jsp"; // } // @RequestMapping("/m1/t1") // public String test(Model model){ // model.addAttribute("msg","ModelTest01"); // //Forward // return "forward:/WEB-INF/jsp/test.jsp"; // } //http://localhost:8080/index.jsp?msg=ModelTest01 @RequestMapping("/m1/t1") public String test2(Model model){ model.addAttribute("msg","ModelTest01"); //redirect return "redirect:/index.jsp"; } }
Forwarding and redirection via SpringMVC - with a view parser;
Redirection does not require a view resolver, it is essentially a request for a new place, so pay attention to the path problem.
You can redirect to another request implementation.
@Controller public class ResultSpringMVC2 { @RequestMapping("/m1/t1") public String test1(){ //Forward return "test"; } @RequestMapping("/m2/t2") public String test2(){ //redirect return "redirect:/index.jsp"; //return "redirect:hello.do"; / /hello.do For another request/ } }
8. Data Processing (Receive Request Parameters and Data Echo)
8.1. Processing submitted data
1. The submitted domain name and the parameter name of the processing method are identical
Submit data: http://localhost:8080/user/t1?name=dada
@Controller @RequestMapping("/user") public class UserController { @GetMapping("/t1") public String test(tring name, Model model){ //1. Receive Front End Parameters System.out.println("The parameter that receives the front end is:"+name); //2. Pass the returned results to the front-end Model model.addAttribute("msg",name); //3. View Delivery return "test"; } }
Background output: dada
2. The submitted domain name and the parameter name of the processing method are inconsistent
Submit data: http://localhost:8080/user/t1?username=dada
Processing method:
@Controller @RequestMapping("/user") public class UserController { @GetMapping("/t1") public String test(@RequestParam("username") String name, Model model){ //1. Receive Front End Parameters System.out.println("The parameter that receives the front end is:"+name); //2. Pass the returned results to the front-end Model model.addAttribute("msg",name); //3. View Delivery return "test"; } }
Background output:
Require that the submitted form field and the object have the same attribute name, the parameter can be used with the object
1. Entity Classes
package com.kk.pojo; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.ToString; @Data @AllArgsConstructor @NoArgsConstructor @ToString public class User { private int id; private String name; private int age; }
Processing method:
package com.kk.controller; import com.kk.pojo.User; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; @Controller @RequestMapping("/user") public class UserController { //The front end receives an object id name age /* 1.Receive parameters passed by front-end users, determine the name of the parameter, and assume that the name is directly in the method, can be used directly 2.Suppose you pass an object User that matches the field name in the User object, otherwise ok does not match if the name stays the same */ @GetMapping("/t2") public String test2(User user){ System.out.println(user); return "test"; } }
Submit data:http://localhost:8080/user/t2?id=1&name=King&age=17
Background output: User{id=1, name='king', age=17}
8.2, Data display to front
First: through ModelAndView
public class ControllerTest01 implements Controller { public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception { //Return a model view object ModelAndView mv = new ModelAndView(); mv.addObject("msg","ControllerTest01"); mv.setViewName("test"); return mv; } }
Second: through ModelMap
ModelMap
@RequestMapping("/hello") public String hello(@RequestParam("username") String name, ModelMap model){ //Encapsulate the data to be displayed in the view //Equivalent to req.setAttribute ("name"); model.addAttribute("msg",name); System.out.println(name); return "hello"; }
The third is through a Model
Model
@RequestMapping("/m1/t1") public String hello(@RequestParam("username") String name, Model model){ //Encapsulate the data to be displayed in the view //Equivalent to req.setAttribute ("name"); model.addAttribute("msg",name); System.out.println(name); return "test"; }
8.3. Contrast
For beginners, the simple difference is:
Model Only a few methods are suitable for storing data, simplifying novice pairs Model Operations and understanding of objects; ModelMap Inherited LinkedMap ,In addition to implementing some of its own methods, the same inheritance LinkedMap Methods and characteristics; ModelAndView While storing data, you can set the returned logical view to control the jump of the display layer.
9. Data Processing (Scrambling)
Test steps:
1. We can write a submission form on the first page
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <form action="/e/t1" method="post"> <input type="text" name="name"> <input type="submit"> </form> </body> </html>
2. Write corresponding processing classes in the background
@Controller public class EncodingController { @RequestMapping("/e/t1") public String test1(String name, Model model){ System.out.println(name); model.addAttribute("msg",name);//Using the view parser, pass data to return test (that is, the test.jsp page) return "test"; } }
3. Enter the Chinese test and find garbled code
It must be said that scrambling is a very common problem in our development, and it's also a problem that makes our programming apes bigger!
Previously, scrambling was resolved through filters, and SpringMVC provided us with a filter that we can configure in web.xml.
Modified xml file needs to restart server!
<!--2.To configure SpringMVC Scrambled filtering of--> <filter> <filter-name>encoding</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>utf-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>encoding</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
In some extreme cases, this filter does not support get very well.
Processing method:
1. Modify the tomcat configuration file: Set the encoding!
<Connector URIEncoding="utf-8" port="8080" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" />
2. Custom Filters
package com.kk.filter; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.Map; public class GenericEncodingFilter implements Filter { public void destroy() { } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { System.out.println("==========================="); //Processing character encoding for response HttpServletResponse myResponse=(HttpServletResponse) response; myResponse.setContentType("text/html;charset=UTF-8"); // Transition to Agreement Related Objects HttpServletRequest httpServletRequest = (HttpServletRequest) request; // Enhancement of request packaging HttpServletRequest myrequest = new MyRequest(httpServletRequest); chain.doFilter(myrequest, response); } public void init(FilterConfig filterConfig) throws ServletException { } } //Custom request object, wrapper class for HttpServletRequest class MyRequest extends HttpServletRequestWrapper { private HttpServletRequest request; //Marker whether or not to code private boolean hasEncode; //Define a constructor that can pass in an HttpServletRequest object to decorate it public MyRequest(HttpServletRequest request) { super(request);// super must be written this.request = request; } // Override Required Enhancement Methods @Override public Map getParameterMap() { // Get Request First String method = request.getMethod(); if (method.equalsIgnoreCase("post")) { // post request try { // Handle post scrambling request.setCharacterEncoding("utf-8"); return request.getParameterMap(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } else if (method.equalsIgnoreCase("get")) { // get request Map<String, String[]> parameterMap = request.getParameterMap(); if (!hasEncode) { // Ensure that get manual encoding logic runs only once for (String parameterName : parameterMap.keySet()) { String[] values = parameterMap.get(parameterName); if (values != null) { for (int i = 0; i < values.length; i++) { try { // Handle get scrambling values[i] = new String(values[i] .getBytes("ISO-8859-1"), "utf-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } } } hasEncode = true; } return parameterMap; } return super.getParameterMap(); } //Take a value @Override public String getParameter(String name) { Map<String, String[]> parameterMap = getParameterMap(); String[] values = parameterMap.get(name); if (values == null) { return null; } return values[0]; // Return the first value of the parameter } //Take all values @Override public String[] getParameterValues(String name) { Map<String, String[]> parameterMap = getParameterMap(); String[] values = parameterMap.get(name); return values; } }
3. Register on the web:
<filter> <filter-name>encoding</filter-name> <filter-class>com.kk.filter.GenericEncodingFilter</filter-class> </filter> <filter-mapping> <filter-name>encoding</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
This is also some of the capitals I looked for on the Internet. In general, SpringMVC's default scrambling handling is already a good solution!
Normally, use the SringMVC filter and register it on the web!
<filter> <filter-name>encoding</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>utf-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>encoding</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
10. JSON Explanation
9.1. What is JSON?
- JSON (JavaScript Object Notation), a lightweight data exchange format, is widely used.
- Stores and represents data in a text format that is completely independent of the programming language.
- The concise and clear hierarchy makes JSON the ideal data exchange language.
- It is easy for people to read and write, easy for machine to parse and generate, and effectively improves the efficiency of network transmission.
In the JavaScript language, everything is an object. Therefore, any type of JavaScript support can be represented by JSON, such as strings, numbers, objects, arrays, etc. See his requirements and syntax format:
- Objects are represented as key-value pairs and data is separated by commas
- Curly brackets to save objects
- Square brackets hold arrays
JSON key-value pairs are a way to save JavaScript objects in much the same way that JavaScript objects are written. Key names in key/value pair combinations are written in front and wrapped in double quotation marks'', using colons: delimited, followed by values:
{"name": "kk"} {"age": "17"} {"sex": "male"}
JSON is a string representation of a JavaScript object. It uses text to represent information about a JS object and is essentially a string
var obj = {a: 'Hello', b: 'World'}; //This is an object, note that key names can also be wrapped in quotes var json = '{"a": "Hello", "b": "World"}'; //This is a JSON string, essentially a string
JSON and JavaScript Object Interchange
- To convert from a JSON string to a JavaScript object, use the JSON.parse() method:
var obj = JSON.parse('{"a": "Hello", "b": "World"}'); //The result is {a:'Hello', b:'World'}
- To convert from a JavaScript object to a JSON string, use the JSON.stringify() method:
var json = JSON.stringify({a: 'Hello', b: 'World'}); //The result is'{'a':'Hello','b':'World'}'
Code Testing
1. Create a new module, springmvc-05-json, add web support
2. Create a new json-1.html under the web directory and write the test content
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script type="text/javascript"> //Writing with a JavaScript object var user={ name:"Small White", age:17, sex:"male" }; //Converting a js object to a json object var json=JSON.stringify(user); console.log(json); console.log("========================"); //Converting a json object to a JavaScript object var obj=JSON.parse(json); console.log(obj); </script> </head> <body> </body> </html>
3. Open in IDEA with browser and view console output!
9.2. Controller returns JSON data
1.jackson
- Jackson should be a better json parsing tool now
- Of course, there is more than one tool, such as Alibaba's fastjson.
- We use Jackson here, and use it to import its jar package;
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.10.0</version> </dependency>
- Configure the configuration required by SpringMVC
web.xml
<?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"> <!--1.register servlet--> <servlet> <servlet-name>SpringMVC</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!--Specify by initialization parameters SpringMVC Configuration file location, associated--> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc-servlet.xml</param-value> </init-param> <!-- Start sequence, the smaller the number, the earlier to start --> <load-on-startup>1</load-on-startup> </servlet> <!--All requests will be springmvc intercept --> <servlet-mapping> <servlet-name>SpringMVC</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <filter> <filter-name>encoding</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>utf-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>encoding</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
springmvc-servlet.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 https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!-- Automatically scan specified packages, and submit all comment classes below to IOC Container Management --> <context:component-scan base-package="com.kuang.controller"/> <!-- view resolver --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver"> <!-- prefix --> <property name="prefix" value="/WEB-INF/jsp/" /> <!-- Suffix --> <property name="suffix" value=".jsp" /> </bean> </beans>
We randomly write a User entity class, then we write our test Controller;
public class User { private String name; private int age; private String sex; public User() { } public User(String name, int age, String sex) { this.name = name; this.age = age; this.sex = sex; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } @Override public String toString() { return "User{" + "name='" + name + '\'' + ", age=" + age + ", sex='" + sex + '\'' + '}'; } }
- Here we need two new things, one is the @ResponseBody and the other is the ObjectMapper object. Let's look at the specific usage
Controller
package com.kk.controller; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.kk.pojo.User; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; @Controller public class UserController { @RequestMapping("/j1") @ResponseBody //As long as the ResponseBody is added, it will not try to parse, it will return a string directly public String Json1() throws JsonProcessingException { //jackson ObjectMapper ObjectMapper mapper=new ObjectMapper(); //Create an object User user = new User("1 Number",17,"male"); //Convert user to Json String str = mapper.writeValueAsString(user); return str; } }
-
Configure Tomcat and start the test!
-
We need to set his encoding format to utf-8 and the type it returns.
-
Modify the following code by using the produces property of @RequestMaping
//produces: Specify the response body return type and encoding @RequestMapping(value = "/j1",produces = "application/json;charset=utf-8")
- Test again, http://localhost : 8080/j1, scrambling problem OK!
[Note: Use json to remember to deal with garbage]
Code optimization
Unified resolution of random code
The previous method is cumbersome, and if there are many requests in the project, each one needs to be added, which can be specified uniformly through the Spring configuration so that it doesn't have to be processed every time!
We can add a message StringHttpMessageConverter conversion configuration to the springmvc configuration file!
<!--JSON Configuration of Scrambling Problem--> <mvc:annotation-driven> <mvc:message-converters register-defaults="true"> <bean class="org.springframework.http.converter.StringHttpMessageConverter"> <constructor-arg value="UTF-8"/> </bean> <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="objectMapper"> <bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean"> <property name="failOnEmptyBeans" value="false"/> </bean> </property> </bean> </mvc:message-converters> </mvc:annotation-driven>
Return json String Unified Resolution
Use @RestController directly on the class so that all the methods inside will only return the json string, instead of adding @ResponseBody to each one! We normally use @RestController in front-end and back-end separate development, which is very convenient!
//@Controller calls the view resolver @RestController //Returns a string public class UserController { // @RequestMapping(value = "/j1",produces = "application/json;charset=utf-8") @RequestMapping(value = "/j1") // @ResponseBody //As long as ResponseBody is added, it will not attempt to parse, it will return a string directly //Use RestController instead of ResponseBody public String Json1() throws JsonProcessingException { //jackson ObjectMapper ObjectMapper mapper=new ObjectMapper(); //Create an object User user = new User("1 Number",17,"male"); //Convert user to Json String str = mapper.writeValueAsString(user); return str; } }
Start the tomcat test and the results will be output normally!
Test Set Output
Add a new method
//@Controller calls the view resolver @RestController //Returns a string public class UserController { // @RequestMapping(value = "/j1",produces = "application/json;charset=utf-8") @RequestMapping(value = "/j1") // @ResponseBody //As long as ResponseBody is added, it will not attempt to parse, it will return a string directly //Use RestController instead of ResponseBody public String Json1() throws JsonProcessingException { //jackson ObjectMapper ObjectMapper mapper=new ObjectMapper(); //Create an object User user = new User("1 Number",17,"male"); //Convert user to Json String str = mapper.writeValueAsString(user); return str; } @RequestMapping(value = "/j2") public String Json2() throws JsonProcessingException { ObjectMapper mapper=new ObjectMapper(); //Working with collections List<User> userList=new ArrayList<User>(); User user1 = new User("1 Number",17,"male"); User user2 = new User("1 Number",17,"male"); User user3 = new User("1 Number",17,"male"); User user4 = new User("1 Number",17,"male"); User user5 = new User("1 Number",17,"male"); User user6 = new User("1 Number",17,"male"); User user7 = new User("1 Number",17,"male"); userList.add(user1); userList.add(user2); userList.add(user3); userList.add(user4); userList.add(user5); userList.add(user6); userList.add(user7); String str = mapper.writeValueAsString(userList); return str; } }
Start the tomcat test and the results will be output normally!
Output Time Object
Add a new method
@RequestMapping("/json3")
public String json3() throws JsonProcessingException {
@RequestMapping("/j3") public String json3() throws JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); //Create time an object, java.util.Date Date date = new Date(); //Parse our object into json format String str = mapper.writeValueAsString(date); return str; } }
Run result:
- The default date format becomes a number, milliseconds from January 1, 1970, to the current date!
- By default, Jackson converts time to timestamps
Solution: Cancel timestamps and customize time format
//@Controller calls the view resolver @RestController //Returns a string public class UserController { @RequestMapping(value = "/j3") public String Json3() throws JsonProcessingException { ObjectMapper mapper=new ObjectMapper(); //Use ObjectMapper to format output //Methods that do not use timestamps mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,false); Date date = new Date(); //The default format for ObjectMapper time parsing is timestamp Timestamp //Custom date format SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String format = sdf.format(date); String str = mapper.writeValueAsString(format); return str; } }
Run result: Successful output time!
That's okay!
Mode 1:
@RequestMapping("/j3") @ResponseBody public String json6() throws JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); Date date = new Date(); //Custom date format SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // objectMapper, the default format for time parsing is Timestamp, time clipping return mapper.writeValueAsString(sdf.format(date)); }
Mode 2:
//@Controller calls the view resolver @RestController //Returns a string public class UserController { @RequestMapping(value = "/j3") public String Json3() throws JsonProcessingException { ObjectMapper mapper=new ObjectMapper(); //Use ObjectMapper to format output //Methods that do not use timestamps mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,false); //Custom date format SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); mapper.setDateFormat(sdf); Date date = new Date(); //The default format for ObjectMapper time parsing is timestamp Timestamp return mapper.writeValueAsString(date); } }
Extract as Tool Class
This is cumbersome if you want to use it regularly; we can encapsulate the code into a tool class; let's write it
package com.kk.utils; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import java.text.SimpleDateFormat; public class JsonUtils { public static String getJson(Object object){ return getJson(object,"yyyy-MM-dd HH:mm:ss"); } public static String getJson(Object object,String dateFormat){ ObjectMapper mapper=new ObjectMapper(); //Methods that do not use timestamps mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,false); //Custom date format SimpleDateFormat sdf = new SimpleDateFormat(dateFormat); mapper.setDateFormat(sdf); try { return mapper.writeValueAsString(object); } catch (JsonProcessingException e) { e.printStackTrace(); } return null; } }
With tool classes, the code is simpler!
@RequestMapping(value = "/j4") public String Json4() throws JsonProcessingException { Date date=new Date(); // return JsonUtils.getJson(date,"yyyy-MM-dd HH:mm:ss"); return JsonUtils.getJson(date); }
2.FastJson
fastjson.jar is a special package developed by Ali for Java development. It can easily convert JSON object to JavaBean object, convert JavaBean object to JSON string, and convert JSON object to JSON string. There are many ways to convert json, and the result is the same.
fastjson's pom dependency!
<dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.60</version> </dependency>
There are three main classes of fastjson:
- [JSONObject represents json object]
- JSONObject implements the Map interface and suspects that the underlying operations of JSONObject are implemented by Map.
- JSONObject corresponds to a json object. Data in a json object can be obtained through various forms of get() methods, and the number of key-value pairs and whether they are empty can be obtained by such methods as size(), isEmpty(). The essence of this is to implement the Map interface and invoke methods in the interface.
- [JSONArray represents an array of json objects]
- Internally, there are methods in the List interface to complete the operation.
- [JSON represents the transformation of JSONObject and JSONArray]
- Analysis and Use of JSON Class Source Code
- Observe these methods carefully, mainly to convert json objects, json object arrays, javabean objects, and json strings to each other.
Code test, we create a new test class
//@Controller calls the view resolver @RestController //Returns a string public class UserController { @RequestMapping(value = "/j5") public String Json5() throws JsonProcessingException { ObjectMapper mapper=new ObjectMapper(); //Working with collections List<User> userList=new ArrayList<User>(); User user1 = new User("1 Number",17,"male"); User user2 = new User("1 Number",17,"male"); User user3 = new User("1 Number",17,"male"); User user4 = new User("1 Number",17,"male"); User user5 = new User("1 Number",17,"male"); User user6 = new User("1 Number",17,"male"); User user7 = new User("1 Number",17,"male"); userList.add(user1); userList.add(user2); userList.add(user3); userList.add(user4); userList.add(user5); userList.add(user6); userList.add(user7); String s = JSON.toJSONString(userList); return s; } }
Test:
http://localhost:8080/j5
11. Ajax Research
-
AJAX = Asynchronous JavaScript and XML (asynchronous JavaScript and XML).
-
AJAX is a technology that updates some pages without reloading the entire page.
-
Ajax is not a new programming language, but a technology for creating better, faster, and more interactive Web applications.
-
In 2005, Google made AJAX popular through its Google Suggest, which automatically helps you complete search words.
-
Google Suggest uses AJAX to create a very dynamic web interface: when you enter keywords in Google's search box, JavaScript sends those characters to the server, and the server returns a list of search suggestions.
-
Just like the search box of Baidu in China!
-
Traditional web pages (those that do not use ajax technology) require reloading the entire page to update content or submit a form.
-
Web pages using ajax technology can achieve asynchronous local updates by exchanging a small amount of data in the background server.
-
With Ajax, users can create direct, highly available, richer, and more dynamic Web user interfaces that are close to local desktop applications.
Fake Ajax
We can use a tag on the front end to fake an ajax look. iframe tag
1. Create a new module: sspringmvc-06-ajax and import web support!
2. Write an ajax-frame.html test using iframe and feel the effect below
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>iframe Test Experience Page No Refresh</title> <script> function go(){ var url=document.getElementById("url").value; document.getElementById("iframe1").src=url; } </script> </head> <body> <div> <p>Please enter an address:</p> <p> <input type="text" id="url" value="https://blog.csdn.net/weixin_50569789?spm=1000.2115.3001.5343"> <input type="button" value="Submit" onclick="go()"> </p> </div> <div> <iframe id="iframe1" style="width: 100%;height: 500px;"></iframe> </div> </body> </html>
3. Use IDEA to open a browser and test it!
AJAX allows you to:
- When registering, enter a user name to automatically detect if the user already exists.
- Prompt for username password error when logged on
- When deleting rows of data, the row ID is sent to the background, and the background is deleted in the database. When the database is deleted successfully, rows of data are deleted in the page DOM.
- ...
jQuery.ajax
Pure JS native implementation of Ajax we will not explain here, directly use jquery provided, easy to learn and use, avoid duplicate wheel, interested students can learn about JS native XMLHttpRequest!
The core of Ajax is the XMLHttpRequest object (XHR). XHR provides an interface for sending requests to the server and parsing server responses. New data can be obtained from the server asynchronously.
jQuery provides several AJAX-related methods.
With the jQuery AJAX method, you can use HTTP Get and HTTP Post to request text, HTML, XML, or JSON from a remote server - and you can load these external data directly into the selected elements of a Web page.
jQuery is not a producer, but a natural mover.
jQuery Ajax is essentially an XMLHttpRequest, encapsulated for easy invocation!
jQuery.ajax(...) Some parameters: url: Request Address type: Request method, GET,POST(1.9.0 After use method) headers: Request Header data: Data to send contentType: Content Encoding Type to Send Information to Server(default: "application/x-www-form-urlencoded; charset=UTF-8") async: Is it asynchronous timeout: Set request timeout (milliseconds) beforeSend: Functions executed before sending a request(Overall situation) complete: Callback functions executed after completion(Overall situation) success: Callback functions executed after success(Overall situation) error: Callback function executed after failure(Overall situation) accepts: Tell the server what types of data the current client can accept by requesting the hair to be sent to the server dataType: Converts the data returned on the server side to the specified type "xml": Convert Server-side Return to xml format "text": Convert Server-side Return to Normal Text Format "html": Converts the returned content from the server to plain text format, and inserts DOM If contains JavaScript Label, it will try to execute. "script": Try to treat the return value as JavaScript To execute, and then convert the server-side returns to normal text format "json": Convert the server-side returns to the appropriate JavaScript object "jsonp": JSONP Format Use JSONP When a function is called formally, such as "myurl?callback=?" jQuery Will be replaced automatically ? Is the correct function name to execute the callback function
Simple case: (front-end interaction)
1. Configure the configuration files for web.xml and application, and copy the above case [remember static resource filtering and annotation-driven configuration]
web.xml
<?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:application.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> <filter> <filter-name>encoding</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>utf-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>encoding</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
application
<?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 https://www.springframework.org/schema/mvc/spring-mvc.xsd"> <context:component-scan base-package="com.kk.controller"/> <mvc:annotation-driven/> <!-- Static Resource Filtering--> <mvc:default-servlet-handler/> <mvc:annotation-driven/> <!-- 3.To configure jsp display ViewResolver view resolver --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> <property name="prefix" value="/WEB-INF/jsp/" /> <property name="suffix" value=".jsp" /> </bean> </beans>
2. Write an AjaxController
package com.kk.controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @RestController public class AjaxController { @RequestMapping("/t1") public String test(){ return "hello"; } @RequestMapping("a1") //Initiate a request public void a1(String name, HttpServletResponse response) throws IOException { System.out.println("a1:param=>"+name); if ("kk".equals(name)){ response.getWriter().print("true"); }else{ response.getWriter().print("false"); } } }
3. Import jquery, you can use online CDN or download import
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script> <script src="${pageContext.request.contextPath}/statics/js/jquery-3.1.1.min.js"></script>
4. Write index.jsp tests
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>$Title$</title> <script src="${pageContext.request.contextPath}/static/js/jquery-3.6.0.js"></script> <script> function a() { $.post({ url:"${pageContext.request.contextPath}/a1", data:{"name":$("#Username'). val ()}, //Get the value of the input box success:function (data,status) { console.log("data="+data); console.log("status="+status); },error:function () { } }) } </script> </head> <body> <%-- Initiate a request when you lose focus(Carry information)Background--%> User name:<input type="text" id="username" onblur="a()"> </body> </html>
5. Start the tomcat test! Open the browser's console and when we leave the input box with the mouse, we will see an ajax request sent out! It is the result returned to us in the background! The test was successful!
Springmvc implementation
Entity Class User
package com.kk.pojo; public class User { private String name; private int age; private String sex; public User() { } public User(String name, int age, String sex) { this.name = name; this.age = age; this.sex = sex; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } @Override public String toString() { return "User{" + "name='" + name + '\'' + ", age=" + age + ", sex='" + sex + '\'' + '}'; } }
Let's get a collection object and show it on the front page
@RequestMapping("a2") public List<User> a2(){ List<User> userList = new ArrayList<User>(); //Add data userList.add(new User("Java",1,"male")); userList.add(new User("Linus",1,"male")); userList.add(new User("Mysql",1,"male")); return userList; }
Front End Page
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> <script src="${pageContext.request.contextPath}/static/js/jquery-3.6.0.js"></script> <script> $(function () { $("#btn").click(function(){ $.post({ url:"${pageContext.request.contextPath}/a2", success:function (data) { console.log(data) var html="" for (let i = 0; i < data.length; i++) { html+="<tr>"+ "<td>"+data[i].name+"</td>"+ "<td>"+data[i].age+"</td>"+ "<td>"+data[i].sex+"</td>"+ "</tr>" } $("#content").html(html); } }) }) }) </script> </head> <body> <input type="button" value="Loading data" id="btn"> <table> <tr> <td>Full name</td> <td>Age</td> <td>Gender</td> </tr> <tbody id="content"> <%-- Data: Get from the background--%> </tbody> </table> </body> </html>
Successfully achieved data echo!
Ajax Authentication User Name Case
AjaxController
@RequestMapping("/a3") public String a3(String name,String pwd) { String msg=""; if (name != null) { if ("admin".equals(name)) { msg="OK"; }else { msg="Error in username!"; } } if (pwd != null) { if ("123456".equals(pwd)) { msg="OK"; }else { msg="Wrong password!"; } } return msg; }
json scrambling problem needs to be configured in application
<?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 https://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!--Automatically scan all annotation classes under the specified package for delivery IOC Container Management--> <context:component-scan base-package="com.kk.controller"/> <mvc:annotation-driven/> <!--JSON Configuration of Scrambling Problem--> <mvc:annotation-driven> <mvc:message-converters register-defaults="true"> <bean class="org.springframework.http.converter.StringHttpMessageConverter"> <constructor-arg value="UTF-8"/> </bean> <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="objectMapper"> <bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean"> <property name="failOnEmptyBeans" value="false"/> </bean> </property> </bean> </mvc:message-converters> </mvc:annotation-driven> <!-- Static Resource Filtering--> <mvc:default-servlet-handler/> <!-- 3.To configure jsp display ViewResolver view resolver --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> <property name="prefix" value="/WEB-INF/jsp/" /> <property name="suffix" value=".jsp" /> </bean> </beans>
login.jsp page
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> <script src="${pageContext.request.contextPath}/static/js/jquery-3.6.0.js"></script> <script> function a1() { $.post({ url:"${pageContext.request.contextPath}/a3", data:{"name":$("#name").val()}, //Get data from front end success:function (data){ if (data.toString()==='OK'){ $("#userInfo").css("color","green"); }else{ $("#userInfo").css("color","red"); } $("#UserInfo'). HTML (data); //Feedback data to front-end pages // console.log(data.toString()); //convert to string } }) } function a2() { $.post({ url:"${pageContext.request.contextPath}/a3", data:{"pwd":$("#PWD').val()}, //Get data from front end success:function (data){ if (data.toString()==='OK'){ $("#pwdInfo").css("color","green"); }else{ $("#pwdInfo").css("color","red"); } $("#PwdInfo'). HTML (data); //Feedback data to front-end pages // console.log(data.toString()); //convert to string } }) } </script> </head> <body> <p> User name:<input type="text" id="name" οnblur="a1()"> <span id="userInfo"></span> </p> <p> Password:<input type="text" id="pwd" οnblur="a2()"> <span id="pwdInfo"></span> </p> </body> </html>
Dynamic request response, local refresh, that's it!
Case acquisition baidu interface
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>JSONP Baidu Search</title> <style> #q{ width: 500px; height: 30px; border:1px solid #ddd; line-height: 30px; display: block; margin: 0 auto; padding: 0 10px; font-size: 14px; } #ul{ width: 520px; list-style: none; margin: 0 auto; padding: 0; border:1px solid #ddd; margin-top: -1px; display: none; } #ul li{ line-height: 30px; padding: 0 10px; } #ul li:hover{ background-color: #f60; color: #fff; } </style> <script> // 2. Step 2 // Define demo functions (analysis interfaces, data) function demo(data){ var Ul = document.getElementById('ul'); var html = ''; // Add content if search data exists if (data.s.length) { // Hidden ul appears Ul.style.display = 'block'; // Searched data loops are appended to LIS for(var i = 0;i<data.s.length;i++){ html += '<li>'+data.s[i]+'</li>'; } // Loop li write ul Ul.innerHTML = html; } } // 1. Step 1 window.onload = function(){ // Get Input Box and ul var Q = document.getElementById('q'); var Ul = document.getElementById('ul'); // Event mouse up Q.onkeyup = function(){ // If the input box is not equal to empty if (this.value != '') { // Loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop JSONPz key key loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop loop Loops // create label var script = document.createElement('script'); //Assign to src given the address to be cross-domain //Here is the cross-domain address to request. I wrote the cross-domain address of Baidu Search script.src ='https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd='+this.value+'&cb=demo'; // Append combined script tags with src to body document.body.appendChild(script); } } } </script> </head> <body> <input type="text" id="q" /> <ul id="ul"> </ul> </body> </html>
Interceptor
Summary
Processor interceptors for SpringMVC are similar to Filter filters in Servlet development for preprocessing and postprocessing processors. Developers can define some interceptors themselves to implement specific functions.
**The difference between filters and interceptors:**Interceptors are a concrete application of AOP thinking.
Filter
- Part of the servlet specification that any java web project can use
- After configuring /* in url-pattern, all resources to be accessed can be intercepted
Interceptor
- Interceptors are the Spring MVC framework itself, and can only be used by projects that use the Spring MVC framework
- Interceptors will only intercept access to the controller methods, and will not intercept access to jsp/html/css/image/js
custom interceptor
So how do you implement interceptors?
To customize interceptors, you must implement the HandlerInterceptor interface.
1. Create a new Moudule, springmvc-07-Interceptor, add web support
2. Configure web.xml and springmvc-servlet.xml files
3. Write an interceptor
package com.kk.config; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; //Interceptor public class MyInterceptor implements HandlerInterceptor { //return true executes next interceptor release //return false does not execute the next interceptor @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("======================Pre-processing========================"); return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println("======================After treatment========================"); HandlerInterceptor.super.postHandle(request, response, handler, modelAndView); } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println("=====================Clear========================="); HandlerInterceptor.super.afterCompletion(request, response, handler, ex); } } //You need to configure it in application.xml after writing here
4. Configure interceptors in the springmvc (or application.xml) configuration file
<!-- Interceptor Configuration--> <mvc:interceptors> <mvc:interceptor> <!-- Include all requests below this request /admin/ada/daad--> <mvc:mapping path="/**"/> <bean class="com.kk.config.MyInterceptor"/> </mvc:interceptor> </mvc:interceptors>
5. Write a Controller to receive requests
//Test interceptor controller @Controller public class InterceptorController { @RequestMapping("/interceptor") @ResponseBody public String testFunction() { System.out.println("The method in the controller executed"); return "hello"; } }
6. Front-end index.jsp
<a href="${pageContext.request.contextPath}/interceptor">Interceptor Test</a>
7. Start the tomcat test!
Use interceptors to verify that users are logged on (authenticate users)
Ideas for implementation
1. There is a landing page and a controller access page needs to be written.
2. The landing page has an action to submit a form. It needs to be processed in the controller. Determine if the username password is correct. If it is correct, write user information to session. Return to successful landing.
3. Intercept user requests to determine whether the user is logged on. If the user is already logged on. Release, if the user is not logged on, jump to the logon page
Test:
1. Write a landing page to create a new JSP folder in the web-inf directory of the web, and then create a new login.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <%-- stay web-inf All pages or resources below can only be accessed by controller perhaps servlet Access--%> <h1>Landing Page</h1> <form action="${pageContext.request.contextPath}/user/login" method="post"> User name: <input type="text" name="username"/> Password: <input type="password" name="password"/> <input type="submit" value="Land"> </form> </body> </html>
2. Write a Controller to process the request
package com.kk.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import javax.servlet.http.HttpSession; @Controller @RequestMapping("/user") public class LoginController { @RequestMapping("/main") public String main(){ return "main"; } @RequestMapping("/goLogin") public String login(){ return "login"; //Click Login to jump to the landing page } @RequestMapping("/login") public String login(HttpSession session, String username, String password, Model model){ System.out.println("login=>"+username); //Exist user information in session session.setAttribute("userLoginInfo",username); model.addAttribute("username",username); return "main"; //Click Submit to log on and jump to the home page } @RequestMapping("/goOut") public String goOut(HttpSession session){ session.removeAttribute("userLoginInfo"); return "main"; //Click Logout to jump to the home page } }
3. Write a new main.jsp that jumps to the home page after successful login. Create a new main.jsp under the new JSP folder under the web-inf directory of the web
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <h1>home page</h1> <%-- Use model Display data to front end--%> <span>${username}</span> <p> <a href="${pageContext.request.contextPath}/user/goOut">Cancellation</a> </p> </body> </html>
5. Write user login interceptor
package com.kk.config; import org.springframework.web.servlet.HandlerInterceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; public class LoginInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { HttpSession session = request.getSession(); // Released Judgment: Judging what landed //Release on landing page if (request.getRequestURI().contains("Login")){ return true; } //Explain that I am submitting a login if (request.getRequestURI().contains("login")){ return true; } //First login without session if (session.getAttribute("userLoginInfo")!=null){ return true; } //Judging when not logged in request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request,response);//redirect return false; } }
6. Register interceptors in the Sprgmvc (application.xml) configuration file
<!-- Crosscut is used aop thought--> <!-- Interceptor Configuration--> <mvc:interceptors> <mvc:interceptor> <!-- Include all requests below this request /admin/ada/daad--> <mvc:mapping path="/user/**"/> <bean class="com.kk.config.LoginInterceptor"/> </mvc:interceptor> </mvc:interceptors>
7. Restart the Tomcat test again!
OK, test login interception function is correct.
File Upload and Download
Dead work
File upload is one of the most common features in project development. Spring MVC supports file upload well, but MultipartResolver is not installed by default in the Spring MVC context, so it cannot handle file upload by default. If you want to use Spring's file upload function, you need to configure MultipartResolver in the context.
Front-end form requirements: In order to upload a file, the method of the form must be set to POST and the enctype set to multipart/form-data. Only in this case will the browser send the file selected by the user to the server as binary data;
Give a detailed description of the enctype property in the form:
- application/x-www=form-urlencoded: By default, only the value attribute value in the form field is processed. Forms that use this encoding process the value in the form field as a URL encoding.
- multipart/form-data: This encoding process form data as a binary stream, which encapsulates the contents of the file specified in the file field into the request parameters and does not encode the characters.
- text/plain: Characters are not encoded except for converting spaces to'+', which works well when sending mail directly from a form.
<form action="" enctype="multipart/form-data" method="post"> <input type="file" name="file"/> <input type="submit"> </form>
Once enctype is set to multipart/form-data, browsers process form data as a binary stream, while processing file uploads involves resolving the original HTTP response on the server side. In 2003, Apache Software Foundation released the open source Commons FileUpload component, which quickly became the best option for Servlet/JSP programmers to upload files.
- The Servlet 3.0 specification already provides a way to handle file uploads, but this upload needs to be done in the Servlet.
- Spring MVC offers simpler encapsulation.
- Spring MVC provides direct support for file upload, which is implemented using Plug and Play MultipartResolver.
- Spring MVC implements a MultipartResolver implementation class using Apache Commons FileUpload technology:
- CommonsMultipartResolver. Therefore, SpringMVC file upload also depends on components of Apache Commons FileUpload.
File Upload
1. Import the jar package uploaded by the file, commons-fileupload, Maven will automatically help us import his dependent package commons-io package;
<dependencies><!--Use maximum version for file upload--> <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.4</version> </dependency> <!--servlet-api Import a higher version of--> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</version> </dependency>
2. Configure bean s:multipartResolver
[Attention!!!! The id of this bena must be: multipartResolver, otherwise uploading the file will result in 400 errors! Pit a hole here, lesson!]
Common methods of CommonsMultipartFile:
- String getOriginalFilename(): Get the original name of the uploaded file
- InputStream getInputStream(): Get the file stream
- void transferTo(File dest): Save the uploaded file to a directory file
test
3. Write front-end pages
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>$Title$</title> </head> <body> <form action="${pageContext.request.contextPath}/upload" enctype="multipart/form-data" method="post"> <input type="file" name="file"/> <input type="submit"> </form> </body> </html>
4,Controller
Mode 1:
package com.kk.controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.commons.CommonsMultipartFile; import javax.servlet.http.HttpServletRequest; import java.io.*; @RestController public class FileController { //@RequestParam("file") encapsulates the file from the name=file control into a CommonsMultipartFile object //Bulk upload of CommonsMultipartFile is an array @RequestMapping("/upload") public String fileUpload(@RequestParam("file") CommonsMultipartFile file , HttpServletRequest request) throws IOException { //Get the file name: file.getOriginalFilename(); String uploadFileName = file.getOriginalFilename(); //If the file name is empty, go back to the home page directly! if ("".equals(uploadFileName)){ return "redirect:/index.jsp"; } System.out.println("Upload File Name : "+uploadFileName); //Upload Path Save Settings String path = request.getServletContext().getRealPath("/upload"); //If the path does not exist, create one File realPath = new File(path); if (!realPath.exists()){ realPath.mkdir(); } System.out.println("Upload file save address:"+realPath); InputStream is = file.getInputStream(); //File Input Stream OutputStream os = new FileOutputStream(new File(realPath,uploadFileName)); //File Output Stream //Read Write Out int len=0; byte[] buffer = new byte[1024]; while ((len=is.read(buffer))!=-1){ os.write(buffer,0,len); os.flush(); } os.close(); is.close(); return "redirect:/index.jsp"; } }
Mode 2:
Use file.Transto to save the uploaded file
1. Write Controller
/* * Use file.Transto to save the uploaded file */ @RequestMapping("/upload2") public String fileUpload2(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException { //Upload Path Save Settings String path = request.getServletContext().getRealPath("/upload"); File realPath = new File(path); if (!realPath.exists()){ realPath.mkdir(); } //Upload File Address System.out.println("Upload file save address:"+realPath); //Write the file directly through the CommonsMultipartFile method (note this time) file.transferTo(new File(realPath +"/"+ file.getOriginalFilename())); return "redirect:/index.jsp"; }
2. Front-end form submission address modification
3. Access submission test, OK!
File Download
File download steps:
1. Set response header
2. Read Files - InputStream
3. Write out the file - OutputStream
4. Perform operations
5. Close the flow (turn on and then off)
Code implementation:
@RequestMapping(value="/download") public String downloads(HttpServletResponse response , HttpServletRequest request) throws Exception{ //Address of picture to download String path = request.getServletContext().getRealPath("/upload"); String fileName = "img.jpg"; //1. Set response header response.reset(); //Set page not cached, empty buffer response.setCharacterEncoding("UTF-8"); //Character Encoding response.setContentType("multipart/form-data"); //Binary Transfer Data //Set Response Header response.setHeader("Content-Disposition", "attachment;fileName="+ URLEncoder.encode(fileName, "UTF-8")); File file = new File(path,fileName); //2. Read File--Input Stream InputStream input=new FileInputStream(file); //3. Write Out File--Output Stream OutputStream out = response.getOutputStream(); byte[] buff =new byte[1024]; int index=0; //4. Perform Write Out while((index= input.read(buff))!= -1){ out.write(buff, 0, index); out.flush(); } out.close(); input.close(); return null; }
Front end
<a href="${pageContext.request.contextPath}/static/img.png">Click Download</a>
Test, File Download OK
End!!!
) Encapsulate the file from name=file control into a CommonsMultipartFile object
//Bulk upload of CommonsMultipartFile is an array
@RequestMapping("/upload")
public String fileUpload(@RequestParam("file") CommonsMultipartFile file , HttpServletRequest request) throws IOException {
//Get the file name: file.getOriginalFilename(); String uploadFileName = file.getOriginalFilename(); //If the file name is empty, go back to the home page directly! if ("".equals(uploadFileName)){ return "redirect:/index.jsp"; } System.out.println("Upload File Name : "+uploadFileName); //Upload Path Save Settings String path = request.getServletContext().getRealPath("/upload"); //If the path does not exist, create one File realPath = new File(path); if (!realPath.exists()){ realPath.mkdir(); } System.out.println("Upload file save address:"+realPath); InputStream is = file.getInputStream(); //File Input Stream OutputStream os = new FileOutputStream(new File(realPath,uploadFileName)); //File Output Stream //Read Write Out int len=0; byte[] buffer = new byte[1024]; while ((len=is.read(buffer))!=-1){ os.write(buffer,0,len); os.flush(); } os.close(); is.close(); return "redirect:/index.jsp"; }
}
#### Mode 2: **Use file.Transto To save the uploaded file** 1,To write Controller ```java /* * Use file.Transto to save the uploaded file */ @RequestMapping("/upload2") public String fileUpload2(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException { //Upload Path Save Settings String path = request.getServletContext().getRealPath("/upload"); File realPath = new File(path); if (!realPath.exists()){ realPath.mkdir(); } //Upload File Address System.out.println("Upload file save address:"+realPath); //Write the file directly through the CommonsMultipartFile method (note this time) file.transferTo(new File(realPath +"/"+ file.getOriginalFilename())); return "redirect:/index.jsp"; }
2. Front-end form submission address modification
3. Access submission test, OK!
File Download
File download steps:
1. Set response header
2. Read Files - InputStream
3. Write out the file - OutputStream
4. Perform operations
5. Close the flow (turn on and then off)
Code implementation:
@RequestMapping(value="/download") public String downloads(HttpServletResponse response , HttpServletRequest request) throws Exception{ //Address of picture to download String path = request.getServletContext().getRealPath("/upload"); String fileName = "img.jpg"; //1. Set response header response.reset(); //Set page not cached, empty buffer response.setCharacterEncoding("UTF-8"); //Character Encoding response.setContentType("multipart/form-data"); //Binary Transfer Data //Set Response Header response.setHeader("Content-Disposition", "attachment;fileName="+ URLEncoder.encode(fileName, "UTF-8")); File file = new File(path,fileName); //2. Read File--Input Stream InputStream input=new FileInputStream(file); //3. Write Out File--Output Stream OutputStream out = response.getOutputStream(); byte[] buff =new byte[1024]; int index=0; //4. Perform Write Out while((index= input.read(buff))!= -1){ out.write(buff, 0, index); out.flush(); } out.close(); input.close(); return null; }
Front end
<a href="${pageContext.request.contextPath}/static/img.png">Click Download</a>
Test, File Download OK
End!!!