Introduction to Spring MVC configuration

Source: Internet
Author: User
Tags map class

One, Spring MVC overview

Spring MVC is the Spring Framework's implementation of the MVC design pattern, and with spring MVC we can quickly build flexible, loosely coupled web services. Before we go into the specifics of spring MVC, let's look at its request handling process:

1.1 Springmvc's request process
1. 请求会首先发送到DispatchServlet,这是spring的前置Servlet,它会接收请求并转发给spring的MVC controller,也就是业务controller2. DispatchServlet通过HandlerMapping确定将请求转发给哪个controller,HandlerMapping主要通过请求中的URL确定映射关系的3. DispatchServlet将请求转发给确定的controller之后,controller负责处理这个请求,一般会通过调用service层进行业务逻辑处理4. 当controller处理完请求后,它会把业务处理结果封装成model,为了使处理结果的model在页面上更好的展示,controller还会指定展示model对应的view(比如一个JSP页面),当controller确定了model和view之后,会把它们以请求的形式再转发给DispatchServlet5. DispatchServlet通过查询ViewResolver找到view对应的页面6. DispatchServlet最终把model交给页面进行渲染7. 页面对model进行渲染,将结果展示到客户端,整个请求结束
1.2 Configuring Spring MVC

In fact, the core of spring MVC is dispatchservlet, the process of configuring spring MVC is the process of configuring Dispatchservlet.

1.2.1 Configuration Dispatchservlet

Spring is configured in two ways, one through the Web. XML configuration and the other through Java configuration, where we mainly talk about how to configure in Web. xml:

  <?xml version= "1.0" encoding= "UTF-8"? ><web-app version= "2.5" xmlns= "http://java.sun.com/xml/ns /javaee "xmlns:xsi=" http://www.w3.org/2001/XMLSchema-instance "xsi:schemalocation=" http://java.sun.com/xml/ns/ Javaeehttp://java.sun.com/xml/ns/javaee/web-app_2_5.xsd "><context-param> <param-name> Contextconfiglocation</param-name> <param-value>/web-inf/spring/root-context.xml</param-value ></context-param><listener> <listener-class>    Org.springframework.web.context.ContextLoaderListener </listener-class></listener><servlet> <servlet-name>spring</servlet-name> <servlet-class> Org.springframework.web.servlet.DispatcherServlet </servlet-class> <load-on-startup>1</ Load-on-startup></servlet><servlet-mapping> <servlet-name>spring</servlet-name> < Url-pattern>/</url-pattern></servlet-mapping>  

Some people may not be quite sure why this is configured, but before you go into specifics, let's introduce the two contexts in spring MVC.

1.2.2 Understanding of two context

We know that spring has a core container called ApplicationContext, and all the spring components are managed by this applicationcontext. However, in a Web project, Spring maintains two context:

1. Webcontext

The first context is the Webcontext created by Dispatchservlet, which is responsible for loading Web component-related beans such as controllers, view resolvers, handler mapping, etc. The corresponding configuration file is {servlet-name}-servlet.xml , in the example above, the name of the servlet that we configured is spring, so it loads the Spring-servlet.xml configuration file as the context by default.

But we can also specify a webcontext configuration file location, such as specifying a configuration file under the/web-inf/spring/appservlet/servlet-context.xml path:

<servlet>    <servlet-name>appServlet</servlet-name>    <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class>    <init-param>        <param-name>contextConfigLocation</param-name>        <param-value>            /WEB-INF/spring/appServlet/servlet-context.xml        </param-value>    </init-param>    <load-on-startup>1</load-on-startup></servlet>

2. Rootcontext

Rootcontext is loaded by Contextlistener, which primarily loads application components other than Web components, such as JDBC, MyBatis, and so on. The <context-param> label specifies the location of the Rootcontext configuration file and <listener> is loaded by the listener class specified by the label.

1.2.3 Enable Spring MVC

The above configuration is basically OK, but a full spring MVC application also requires controller, service, view and other components, which will be described in detail later, now we first configure in Spring-servlet.xml:

  <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-4.0.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/MVC/HTTP Www.springframework.org/schema/mvc/spring-mvc-4.0.xsd Http://www.springframework.org/schema/context/HTTP Www.springframework.org/schema/context/spring-context-4.0.xsd "> <mvc:annotation-driven/> <context: Component-scan base-package= "Com.springmvc.demo"/> <bean class= " Org.springframework.web.servlet.view.InternalResourceViewResolver "> <property name=" prefix "value="/web-inf /views/"/> <property name=" suffix "value=". jsp "/> </bean></beans>  

<mvc:annotation-driven/>The label function is to open the annotation
<context:component-scan/>The purpose of the label is to enable automatic packet scanning, so that the spring framework automatically scans the annotated classes for inclusion in the Webcontext.

With the configuration above, the main configuration of spring MVC has been completed and we can now write the components of spring MVC, starting with the controller.

Two, write a controller 2.1 write a simple controller
@Controllerpublic class HomeController {@RequestMapping(value="/", method= RequestMethod.GET)    public String home() {        return "home";    }}

declaring a controller component: writing a controller is simple, @controller annotation declares that the current class is a controller class, and in the configuration above we open the Componentscan, Classes that are annotated by @controller are automatically loaded into the spring application context. Of course we use the @component component effect is the same, but @controller more can reflect the controller role.

To define the request path: The HomeController class has only one home () method, and also carries a @requestmapping annotation, and the Value property in the annotation defines the access path of the method as "/", which defines the method property to handle only the GET request.

define render View: we can see that the home () method is simple and returns only a "home" string. By default, the string returned by the method is parsed into the name of the view by default, and Dispatcherservlet will let Viewresolver parse the view name corresponding to the real view page. We have already configured a internalresourceviewresolver, and the returned home will be parsed/web-inf/views/home.jsp.

After writing the controller, we can test the test class and write a test controller:

public class HomeControllerTest {    @Test    public void testHomePage() throws Exception {        HomeController controller = new HomeController();        Assert.assertEquals("home", controller.home());    }    @Test    public void testHomePageMVC() throws Exception {        HomeController controller = new HomeController();        MockMvc mockMvc = MockMvcBuilders.standaloneSetup(controller).build();        mockMvc.perform(MockMvcRequestBuilders.get("/")).andExpect(MockMvcResultMatchers.view().name("home"));    }}
2.2 Defining a path mapping for a class hierarchy

In fact, annotations @RequestMapping can be both annotated and annotated, and when the annotation class is accessed, all methods in the class must be accompanied by a classpath. In addition, @RequestMapping the value can be an array of paths, and when an array is passed in, we can access the class through any of the paths in the array.

@Controller@RequestMapping({"/", "/homepage"})public class HomeController {    ...}
2.3 Return model data to the view layer

We know that normally, the controller will return the result data to the view layer when it finishes processing the business. To do this, SPRINGMVC provides the model class to encapsulate the result data, the encapsulation process is automatic, and we only need to add the model parameter to the method:

public String getUsers(Model model) {    model.addAttribute( userService.findSpittles( Long.MAX_VALUE, 20));    return "userView";}

Model is actually a Map,view layer will automatically parse the data in the model, and then render the results to the client side. The above model.addAttribute method does not specify that the Key,key value is set to the object's type name by default, such as the object type in the example above List<User> , then the key value defaults to: userList . The string value returned at the end of the method userView is directly the name of the view.

Of course we can also explicitly specify the key value of the return data model:

public String getUsers(Model model) {    model.addAttribute("userList", userService.findUsers( Long.MAX_VALUE, 20));    return "userView";}

If we do not want to use the Spring model class, we can also replace the model with the Java.util.Map class, the two effects are exactly the same:

public String getUsers(Map map) {    map.addAttribute("userList", userService.findUsers( Long.MAX_VALUE, 20));    return "userView";}

In addition to the above two ways, we can also write:

@RequestMapping(method=RequestMethod.GET)public List<User> getUsers() {    return userService.findUsers(Long.MAX_VALUE, 20));}

This method is special, we do not set the returned model, and do not specify the rendering model of the view, just return the processed result object. In this case, Spring MVC will automatically put the returned object into the model, whose key is the type name of the object, that is userList . The corresponding view name is the same as the request path name, for example our request path is:

@Controller@RequestMapping("/users")public class UserController {    ... ...}

Then the view that corresponds to the rendering result is users .

Third, processing the request data

SPRINGMVC provides a variety of data transfer methods:

    • QueryParameter: Query Parameters
    • Form Parameters: Form parameters
    • Path variables: Paths variable

Let's explain each of these.

3.1 Getting query parameters

What is the query parameter first? For example, we have a request in which the parameter values are in the http://localhost:8080/user/queryUsers?pageNo=1&count=5 URL? The following arguments pass through, this way is the query parameter value. If you want to parse the values in the query parameters, we need to use the @requestparam annotation, which maps the request parameters to the method parameters:

@RequestMapping(value = "/getUsersByPage", method = RequestMethod.GET)public String getUsersByPage(@RequestParam(value = "pageNo",defaultValue = "1") long pageNo,@RequestParam(value = "count",defaultValue = "5") long count ,Model model) {    model.addAttribute(userService.getAllUsers());    return "userListPageView";}

It is important to note that we can specify the default value of the parameter when we configure the request parameter, and when the parameter value passed by the client does not exist or is empty, the default value is used, and one point, because the query parameters are all string types, the default value here is also the string type.

In addition to passing parameter values through query parameters, there is also a popular way to pass parameter values through a request path, especially when discussing building resource-based services . (Note: A resource-based service can be simply considered that all requests are for resources, and all the returned results are resources)

3.2 Obtaining parameters by request path

For example, we have a need to query user information according to the user ID, through the way described above we can do this:

@RequestMapping(value = "/queryUser", method = RequestMethod.GET)public String queryUser(@RequestParam(value = "employeeId") long employeeId,Model model){    model.addAttribute(manager.queryEmployeeVO(employeeId));    return "employee";}

So our customer's request path should be this: /employee/queryEmployee ?employeeId=12345 , although it can also meet the requirements, but this is not very consistent with the resource-based concept. Ideally, the resource should be determined by the request path, not by the request parameter. Or, the request parameter should not be used to describe a resource. /employee/12345This is clearly better than the request /employee/queryEmployee ?employeeId=12345 , which defines the resource to be queried, while the latter emphasizes the operation with parameters.

To achieve the goal of building a resource-based controller, Spring MVC allows a placeholder to be included in the request path, with a placeholder name enclosed in a pair of {} characters. When a client requests a resource, the other parts of the request path are used to match the resource path, and the placeholder portion is used to transfer the parameter values directly. Here's how to pass the parameter values in a path through a placeholder:

@RequestMapping(value ="/{userId}", method = RequestMethod.GET)public String queryUser(@PathVariable(value = "userId") long userId, Model model){    model.addAttribute(userService.queryUser(employeeId));    return "userView";}

As you can see from the example above, there is an annotation in the method parameter that @PathVariable means that it is passed to the annotated variable regardless of the value at the placeholder in the request path @PathVariable . For example, according to the above configuration, if our request is /employee/12345 , then it 123456 will pass into userId the value. It is important to note that if the method parameter value is the same as the placeholder name, we can omit @PathVariable the property value in:

@RequestMapping(value ="/{userId}", method = RequestMethod.GET)public String queryUser(@PathVariable long userId, Model model){    model.addAttribute(userService.queryUser(employeeId));    return "userView";}

It is still possible to use query parameters and path parameters when the amount of data requested is very small, but sometimes the amount of data that we request is very large, and then it is a bit inappropriate to use either of the above methods, then we need to consider the third way: form parameters.

Iv. Processing of form data

A Web application is more than just presenting data to the user, and many times it needs to interact with the user to get user data, and forms are the most common way to get user data.

For example, we have a registration form:

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %><%@ page session="false" %>
4.1 Write a controller that receives form data

The form is submitted as post, so our controller should accept a POST request:

@Controller@RequestMapping("/user")public class RegisterController {    @Autowired    private RegisterService registerService;    @RequestMapping(value="/register", method=RequestMethod.POST)    public String processRegistration(User user) {        registerService.register(user);        return "redirect:/user/" + user.getName();    }}

In the above example, the received request is a post, and the registration method has a parameter containing the user object, which contains the name, password, Accountno property, springmvc resolves the same name parameter from the request and assigns it to the object property, based on the name.

When the registration method saves the user information, it returns a string that is different from what was redirect:/user/ mentioned earlier, and it returns a redirect Redirect request instead of a view name. Because the returned string contains a redirect: redirect keyword, when the InternalResourceViewResolver class encounters the keyword, it will intercept the string and parse it into a redirect request instead of the view name.

InternalResourceViewResolverIn addition to being able to identify the redirect: keyword, it recognizes the keyword and forward: forward: parses the string containing the keyword into the forward request.

4.2 Verifying forms

After Spring3.0, SPRINGMVC supports the Java Validation API, and the Java Validation API provides annotations to constrain object property values, which are:

Annotations explain
@AssertFalse The annotated element must be a Boolean type and is false.
@AssertTrue The annotated element must is a Boolean type and be true.
@DecimalMax The annotated element must be a number whose value are less than or equal toa given bigdecimalstring value.
@DecimalMin The annotated element must be a number whose value is greater than orequal to a given bigdecimalstring value.
@Digits The annotated element must is a number whose value has a specified number of digits.
@Future The value of the annotated element must is a date in the future.
@Max The annotated element must be a number whose value was less than or equal to a given value.
@Min The annotated element must be a number whose value is greater than or equal to a given value.
@NotNull The value of the annotated element must not is null.
@Null The value of the annotated element must is null.
@Past The value of the annotated element must is a date in the past.
@Pattern The value of the annotated element must match a given regular expression.
@Size The value of the annotated element must is either a String, a collection, or an array whose length fits within the given R Ange.

We can use these annotations to add some validation to the user object, such as non-null and string length validation:

public class User {    @NotNull    @Size(min=3,max=20)    private String name;    @NotNull    @Size(min=6,max=20)    private String password;    @NotNull    @Size(min=3,max=20)    private String accountNo;}

We also need to @Valid enable parameter validation for the user through the tag in the method:

@RequestMapping(value="/register", method=RequestMethod.POST)public String processRegistration(@Valid User user, Errors errors) {    if(errors.hasErrors()){        return "register";    }    registerService.register(user);    return "redirect:/user/" + user.getName();}

In the example above, we added the @valid annotation before the user parameter in the method, which tells the spring framework to enable validation of the object. If any validation errors are found, the error message will be encapsulated in the errors object, and we can errors.hasErrors() determine by the method whether the validation passed.

To be Continued ...

Introduction to Spring MVC configuration

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.