Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What's the use of SpringMVC?

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly shows you "what is the use of SpringMVC", the content is easy to understand, clear, hope to help you solve your doubts, the following let the editor lead you to study and learn "what is the use of SpringMVC" this article?

Overview

To understand SpringMVC, take a look at a process diagram:

From the flow chart, we can see:

The receiving front end sends the Request request. Find the corresponding processor to process the request according to the mapping path, and return ModelAndView when the processing is complete. Perform view parsing, view rendering, and return the response result.

The summary is: receive parameters, define the mapping path, jump the page, and return the response result.

Of course, this is only the most basic core function, in addition to defining interceptors, global exception handling, file uploads and downloads, and so on.

First, build a project

In the previous old project, because there was no SpringBoot and no automatic configuration, you needed to use the web.xml file to define a DispatcherServlet. Now Internet applications basically use SpringBoot, so I will directly use SpringBoot for demonstration. It's simple to introduce dependencies:

Org.springframework.boot

Spring-boot-starter-web

Second, define Controller

There are five ways to define a Controller processor using SpringMVC.

2.1implement the Controller interface

Early SpringMVC was defined in this way:

/ * *

* @ author Ye Hongzhi official account: java technology enthusiast

* @ name DemoController

* @ date 2020-08-25 22:28

* * /

@ org.springframework.stereotype.Controller ("/ demo/controller")

Public class DemoController implements Controller {

@ Override

Public ModelAndView handleRequest (HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {

/ / Business processing

Return null

}

}

2.2 implement the HttpRequestHandler interface

Similar to the first way, but also by implementing the interface:

/ * *

* @ author Ye Hongzhi official account: java technology enthusiast

* @ name HttpDemoController

* @ date 2020-08-25 22:45

* * /

@ Controller ("/ http/controller")

Public class HttpDemoController implements HttpRequestHandler {

@ Override

Public void handleRequest (HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {

/ / Business processing

}

}

2.3 implement the Servlet interface

This approach is no longer recommended, but it can be seen here that the underlying SpringMVC uses Servlet.

@ Controller ("/ servlet/controller")

Public class ServletDemoController implements Servlet {

/ / the following is the Servlet lifecycle method

@ Override

Public void init (ServletConfig servletConfig) throws ServletException {

}

@ Override

Public ServletConfig getServletConfig () {

Return null

}

@ Override

Public void service (ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {

}

@ Override

Public String getServletInfo () {

Return null

}

@ Override

Public void destroy () {

}

}

Because this method is not recommended, the adapter is not loaded by default, and you need to add:

@ Configuration

@ EnableWebMvc

Public class WebMvcConfig extends WebMvcConfigurerAdapter {

@ Bean

Public SimpleServletHandlerAdapter simpleServletHandlerAdapter () {

Return new SimpleServletHandlerAdapter ()

}

}

2.4 use @ RequestMapping

This approach is the most commonly used, because the above way definitions require the use of a class to define a path, which results in a lot of classes. Using annotations is relatively lightweight.

@ Controller

@ RequestMapping ("/ requestMapping/controller")

Public class RequestMappingController {

@ RequestMapping ("/ demo")

Public String demo () {

Return "HelloWord"

}

}

2.4.1 support Restful style

It also supports Restful style, and uses the method attribute to define how to operate on resources:

@ RequestMapping (value = "/ restful", method = RequestMethod.GET)

Public String get () {

/ / query

Return "get"

}

@ RequestMapping (value = "/ restful", method = RequestMethod.POST)

Public String post () {

/ / create

Return "post"

}

@ RequestMapping (value = "/ restful", method = RequestMethod.PUT)

Public String put () {

/ / Update

Return "put"

}

@ RequestMapping (value = "/ restful", method = RequestMethod.DELETE)

Public String del () {

/ / Delete

Return "post"

}

2.4.2 support URL such as Ant style / / match / antA or / antB

RequestMapping ("/ ant?")

Public String ant () {

Return "ant"

}

/ / match / ant/a/create or / ant/b/create and other URL

@ RequestMapping ("/ ant/*/create")

Public String antCreate () {

Return "antCreate"

}

/ / match / ant/create or / ant/a/b/create and other URL

@ RequestMapping ("/ ant/**/create")

Public String antAllCreate () {

Return "antAllCreate"

}

2.5 using HandlerFunction

The last one is to use HandlerFunction functional interface, which is introduced after Spring5.0, which is mainly used for the development of responsive interface, that is, the development of Webflux.

Those who are interested can search for relevant materials on the Internet to learn, which may take a lot of space, so I won't repeat it here.

Third, receiving parameters

After defining the Controller, you need to receive the parameters passed in from the front end. How to receive them?

3.1 receive common parameters

Write the name of the receiving parameter on the @ RequestMapping mapping method:

@ RequestMapping (value = "/ restful", method = RequestMethod.POST)

Public String post (Integer id, String name, int money) {

System.out.println ("id:" + id + ", name:" + name + ", money:" + money)

Return "post"

}

3.2 @ RequestParam parameter name binding

If you do not want to use the parameter name as the parameter name, you can use @ RequestParam to bind the parameter name:

/ * *

* value: parameter name

* required: whether this parameter must be included in request. Default is true.

* defaultValue: default parameter value

, /

@ RequestMapping (value = "/ restful", method = RequestMethod.GET)

Public String get (@ RequestParam (value = "userId", required = false, defaultValue = "0") String id) {

System.out.println ("id:" + id)

Return "get"

}

3.3 @ PathVariable path parameters

The placeholder {xxx} parameter in URL is mapped to the input parameter of the action method through @ PathVariable. The demo code is as follows:

@ RequestMapping (value = "/ restful/ {id}", method = RequestMethod.GET)

Public String search (@ PathVariable ("id") String id) {

System.out.println ("id:" + id)

Return "search"

}

3.4 @ RequestHeader binding request header attribute

How to get the information about the request header?

Use the @ RequestHeader annotation, which is similar to @ RequestParam:

@ RequestMapping ("/ head")

Public String head (@ RequestHeader ("Accept-Language") String acceptLanguage) {

Return acceptLanguage

}

3.5 @ CookieValue the cookie value of the binding request

Get the value of Cookie in Request:

@ RequestMapping ("/ cookie")

Public String cookie (@ CookieValue ("_ ga") String _ ga) {

Return _ ga

}

3.6 bind request parameters to POJO object

A User entity class is defined:

Public class User {

Private String id

Private String name

Private Integer age

/ / getter, setter method

}

Define an @ RequestMapping operation method:

@ RequestMapping ("/ body")

Public String body (User user) {

Return user.toString ()

}

As long as the request parameter is the same as the property name, it is automatically populated into the user object:

3.6.1 cascading attributes are supported

Now there is an additional Address class to store address information:

Public class Address {

Private String id

Private String name

/ / getter, setter method

}

Add the address attribute to the User:

Public class User {

Private String id

Private String name

Private Integer age

Private Address address

/ / getter, setter method

}

When passing parameters, as long as address.name and address.id are passed, it will be automatically populated:

3.6.2 @ InitBinder resolves property name conflicts when receiving multiple objects

Wouldn't there be conflicts if two POJO objects have the same property name? For example, user and address just now, in which they both have the attributes of id and name. If they receive them at the same time, they will conflict:

/ / both user and address have id and name attributes

@ RequestMapping (value = "/ twoBody", method = RequestMethod.POST)

Public String twoBody (User user, Address address) {

Return user.toString () + "," + address.toString ()

}

At this point, you can bind the parameter name with @ InitBinder:

@ InitBinder ("user")

Public void initBindUser (WebDataBinder webDataBinder) {

WebDataBinder.setFieldDefaultPrefix ("u.")

}

@ InitBinder ("address")

Public void initBindAddress (WebDataBinder webDataBinder) {

WebDataBinder.setFieldDefaultPrefix ("addr.")

}

3.6.3 @ Requestbody automatically parses JSON strings encapsulated into objects

A json string is passed in the front end, which is automatically converted into a pojo object. The demo code:

@ RequestMapping (value = "/ requestBody", method = RequestMethod.POST)

Public String requestBody (@ RequestBody User user) {

Return user.toString ()

}

Note that to use the POST request, the sender's Content-Type is set to application/json and the data is a json string:

Some people even like to use a Map to receive:

But do not use Map to receive, otherwise the code will be very difficult to maintain, the elder brother may not understand what data is in your Map, so it is best to define a POJO object.

IV. Parameter type conversion

In fact, the SpringMVC framework itself has a lot of built-in type converters, such as the number you pass in the string and the input parameter you receive as int,long, which will automatically convert it for you.

Under the package org.springframework.core.convert.converter, as shown in the figure:

Sometimes if the built-in type converter is not enough to meet the business needs, how to expand it, it is very simple, let me operate. What is a Java technology enthusiast (tactical backwards).

First of all, as an example, the built-in converter implements the Converter interface, which I also implement:

Public class StringToDateConverter implements Converter {

@ Override

Public Date convert (String source) {

SimpleDateFormat sdf = new SimpleDateFormat ("yyyy-MM-dd")

Try {

/ / convert String to Date type

Return sdf.parse (source)

} catch (Exception e) {

/ / Type conversion error

E.printStackTrace ()

}

Return null

}

}

Then register the converter with the Spring container:

@ Configuration

Public class ConverterConfig extends WebMvcConfigurationSupport {

@ Override

Protected void addFormatters (FormatterRegistry registry) {

/ / add a type converter

Registry.addConverter (new StringToDateConverter ())

}

}

Let's take a look at the test. All date strings are automatically converted to Date, which is very convenient:

Fifth, page jump

Before the front and rear ends are separated, the work of page jump is controlled by the back end, and the data is displayed by JSP. Although Internet projects rarely use JSP now, I think I still need to learn, because some old projects still use JSP, or need refactoring.

If you return a string directly in the RequestMapping method, it will not jump to the specified JSP page, so you need to do some configuration.

The first step is to add the Maven configuration for parsing jsp.

Org.apache.tomcat.embed

Tomcat-embed-jasper

7.0.59

Javax.servlet

Jstl

Second, add a view parser.

@ Configuration

Public class WebAppConfig extends WebMvcConfigurerAdapter {

@ Bean

Public InternalResourceViewResolver viewResolver () {

InternalResourceViewResolver viewResolver = new InternalResourceViewResolver ()

ViewResolver.setPrefix (/)

ViewResolver.setSuffix (".jsp")

ViewResolver.setViewClass (JstlView.class)

Return viewResolver

}

}

The third step is to set the configuration of IDEA.

Step four, create a jsp page.

Step 5, create the Controller controller.

@ Controller

@ RequestMapping ("/ view")

Public class ViewController {

@ RequestMapping ("/ hello")

Public String hello () throws Exception {

Return "hello"

}

}

This is done, start the project, visit / view/hello and see:

It's that simple, isn't it?

6. @ ResponseBody

If you use front-end separation, the page jump does not need the back-end control, the back-end only needs to return json, how to return?

You can use the @ ResponseBody annotation, which automatically converts the object into json data to return.

The @ ResponseBody annotation can be placed on a class or method. The source code is as follows:

/ / used in classes and methods

@ Target ({ElementType.TYPE, ElementType.METHOD})

@ Retention (RetentionPolicy.RUNTIME)

@ Documented

Public @ interface ResponseBody {

}

Show me:

@ RequestMapping ("/ userList")

@ ResponseBody

Public List userList () throws Exception {

List list = new ArrayList ()

List.add (new User ("1", "Yao Daqiu", 18)

List.add (new User ("2", "Li Xing", 18))

List.add (new User ("3", "Dongmin", 18))

Return list

}

Test / view/userList:

7. @ ModelAttribute

There are many uses of @ ModelAttribute, which will be explained below.

7.1 is used in methods with no return value

In the Controller class, the @ ModelAttribute annotated method is executed before all RequestMapping methods are executed.

@ Controller

@ RequestMapping ("/ modelAttribute")

Public class ModelAttributeController {

/ / execute this method first

@ ModelAttribute

Public void modelAttribute (Model model) {

/ / put data in the request field

Model.addAttribute ("userName", "official account: java technology enthusiast")

}

@ RequestMapping ("/ index")

Public String index () {

/ / Jump to inex.jsp page

Return "index"

}

}

The index.jsp page is as follows:

Home page

${userName}

Like a Controller interceptor, the @ ModelAttribute annotated method is executed before the RequestMapping method is executed. So use it with caution.

Start the project and visit / modelAttribute/index to see:

Even if the value of the userName attribute is not put in the index () method, the jsp page can get it because the modelAttribute () method is already in before the index () method is executed.

7.2 put it on a method that has a return value

In fact, the order of calls is the same, and it is also executed before the RequestMapping method, except that the return value of the method helps you put it directly into the request field.

/ / put it on the method with parameters

@ ModelAttribute

Public User userAttribute () {

/ equivalent to model.addAttribute ("user", new User ("1", "Java technology enthusiast", 18))

Return new User ("1", "Java technology enthusiast", 18)

}

@ RequestMapping ("/ user")

Public String user () {

Return "user"

}

Create a user.jsp:

Home page

ID:$ {user.id}

Name: ${user.name}

Age: ${user.age}

Test it:

The attribute value placed in the request field defaults to the lowercase hump of the class name. What if you want to customize it? Quite simply, it can be written like this:

/ / Custom property name is "u"

@ ModelAttribute ("u")

Public User userAttribute () {

Return new User ("1", "Java technology enthusiast", 18)

}

/ * *

JSP is going to write something like this:

ID:$ {u.id}

Name: ${u.name}

Age: ${u.age}

, /

7.3. put @ Controller on the RequestMapping method

@ RequestMapping ("/ modelAttribute")

Public class ModelAttributeController {

@ RequestMapping ("/ jojo")

@ ModelAttribute ("attributeName")

Public String jojo () {

Return "JOJO! I'm not a man anymore!"

}

}

In this case, the value returned by the RequestMapping method is not the JSP view. Instead, you put the return value into the property value in the request field, which is named attributeName. The view is the URL on the RequestMapping annotation, so create a corresponding JSP page:

Home page

${attributeName}

Test it:

7.4 put it on the method input parameter

Put it on the input parameter, which means to extract the corresponding attribute value from the previous Model and use it as the input parameter in the input method. As follows:

@ ModelAttribute ("u")

Public User userAttribute () {

Return new User ("1", "Java technology enthusiast", 18)

}

@ RequestMapping ("/ java")

Public String user1 (@ ModelAttribute ("u") User user) {

/ / get the value returned by the @ ModelAttribute ("u") method and print it out

System.out.println ("user:" + user)

Return "java"

}

Test it:

8. Interceptor

Interceptor is the key content, and interceptors are often used, such as login verification, permission verification and so on. How does SpringMVC add interceptors?

Quite simply, implement the HandlerInterceptor interface, which has three methods that need to be rewritten.

PreHandle (): called before the business processor processes the request. Pretreatment. PostHandle (): executes after the business processor processes the request execution and before the view is generated. Post-processing. AfterCompletion (): called after the DispatcherServlet has fully processed the request, it can be used to clean up resources, and so on. Return processing (the page has been rendered)

Custom interceptor, implemented interface HandlerInterceptor:

Public class DemoInterceptor implements HandlerInterceptor {

@ Override

Public boolean preHandle (HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

/ / preprocessing. If true is returned, execution will continue. If login verification is required, it can not be verified by returning false, or true is returned if it is passed.

System.out.println ("execute preHandle () method")

Return true

}

@ Override

Public void postHandle (HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

/ / Post-processing

System.out.println ("execute postHandle () method")

}

@ Override

Public void afterCompletion (HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

/ / called after the DispatcherServlet has fully processed the request

System.out.println ("execute afterCompletion () method")

}

}

Then add the interceptor to the Spring container:

@ Configuration

Public class ConverterConfig extends WebMvcConfigurationSupport {

@ Override

Public void addInterceptors (InterceptorRegistry registry) {

Registry.addInterceptor (new DemoInterceptor ()) .addPathPatterns ("/ *")

}

}

/ * * represents all paths. Test it:

IX. Global exception handling

SpringMVC itself handles some exceptions globally, so there is a built-in exception handler, where is it?

Just look at the class diagram of the HandlerExceptionResolver interface:

You can see from the class diagram that there are four types of exception handlers:

DefaultHandlerExceptionResolver, the default exception handler. Return different exception views based on different types of exceptions. SimpleMappingExceptionResolver, a simple mapping exception handler. Resolve the exception by configuring the relationship between the exception class and the view. ResponseStatusExceptionResolver, status code exception handler. Resolve exceptions with @ ResponseStatus annotation types. ExceptionHandlerExceptionResolver, exception handler in annotated form. Exception parsing of the method annotated by @ ExceptionHandler.

The first default exception handler is the built-in exception handler, which is generally ignored for some common exception handling. The last three are the ones that need to be paid attention to and are used to expand.

9.1 SimpleMappingExceptionResolver

It translates to a simple mapping exception handler. The purpose is that we can specify some kind of exception and jump to the specified page when the exception is thrown. Please see the demo.

The first step is to add a spring-config.xml file and put it in the resources directory. The name of the file can be found in the text:

Err

The second step is to load the xml file in the startup class:

@ SpringBootApplication

@ ImportResource ("classpath:spring-config.xml")

Public class SpringmvcApplication {

Public static void main (String [] args) {

SpringApplication.run (SpringmvcApplication.class, args)

}

}

The third step is to create an err.jsp page under the webapp directory:

Exception page

An exception occurred. This is a 500 page.

This is done. Write an interface to test it:

@ Controller

@ RequestMapping ("/ exception")

Public class ExceptionController {

@ RequestMapping ("/ index")

Public String index (String msg) throws Exception {

If ("null" .equals (msg)) {

/ / A null pointer exception is thrown

Throw new NullPointerException ()

}

Return "index"

}

}

The effect is as follows:

This kind of exception handler can hardly be seen in projects where front and rear ends are separated.

9.2 ResponseStatusExceptionResolver

This exception handler is mainly used to handle exceptions with @ ResponseStatus annotations. Take a look at the demo code:

Customize an exception class and decorate it with the @ ResponseStatus annotation:

/ / HttpStatus enumerates all the status codes. A 400 response code is returned here.

@ ResponseStatus (value = HttpStatus.BAD_REQUEST)

Public class DefinedException extends Exception {

}

Write a Controller interface for testing:

@ RequestMapping ("/ defined")

Public String defined (String msg) throws Exception {

If ("defined" .equals (msg)) {

Throw new DefinedException ()

}

Return "index"

}

Start the project and test it, and the results are as follows:

9.3 ExceptionHandlerExceptionResolver

Exception handlers in the form of annotations, which are the most frequently used. It is very simple and convenient to use.

First, define a custom exception BaseException:

Public class BaseException extends Exception {

Public BaseException (String message) {

Super (message)

}

}

The second step is to define an error prompt entity class ErrorInfo:

Public class ErrorInfo {

Public static final Integer OK = 0

Public static final Integer ERROR =-1

Private Integer code

Private String message

Private String url

/ / getter 、 setter

}

The third step is to define the global exception handling class GlobalExceptionHandler:

/ / RestControllerAdvice is used here, which is a combination of @ ResponseBody and @ ControllerAdvice

/ / the prompt that converts the entity class to JSON format is returned, which conforms to the architecture of the separation of front and rear ends.

@ RestControllerAdvice

Public class GlobalExceptionHandler {

/ / A BaseException is customized here. When a BaseException exception is thrown, it will be handled by this method.

@ ExceptionHandler (BaseException.class)

Public ErrorInfo errorHandler (HttpServletRequest req, BaseException e) throws Exception {

ErrorInfo r = new ErrorInfo ()

R.setMessage (e.getMessage ())

R.setCode (ErrorInfo.ERROR)

R.setUrl (req.getRequestURL () .toString ())

Return r

}

}

When you are done, write a test interface:

@ RequestMapping ("/ base")

Public String base (String msg) throws Exception {

If ("base" .equals (msg)) {

Throw new BaseException ("Test throws BaseException exception, Oye!")

}

Return "index"

}

Start the project and test:

The above is all the content of this article "what's the use of SpringMVC?" Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report