Get started with spring MVC

Spring MVC

Spring MVC is the mainstream enterprise level development framework to realize MVC design pattern. As a sub module of spring framework, it is more convenient to develop without integration.

What is MVC design pattern?

The application is divided into three layers: Controller, Model and View. The Controller receives the client request, calls the Model to generate business data and passes it to View.

Spring MVC encapsulates this process, shields a lot of underlying code and opens interfaces, so that developers can complete Web development based on MVC mode more easily and conveniently.

Core components of Spring MVC

  • Dispatcher servlet: the front controller is the core of the whole process control. It controls the execution of other components, carries out unified scheduling, and reduces the coupling between components, which is equivalent to the commander in chief.
  • Handler: processor, which completes specific business logic, equivalent to Servlet or Action.
  • Handler mapping: after the dispatcher servlet receives the request, it maps different requests to different handlers through HandlerMapping.
  • HandlerInterceptor: processor interceptor, which is an interface. If you need to complete some interception processing, you can implement this interface.
  • HandlerExecutionChain: processor execution chain, including two parts: Handler and HandlerInterceptor (the system will have a default HandlerInterceptor. If you need to set additional interception, you can add interceptors).
  • HandlerAdapter: processor adapter. Before the Handler executes the business method, it needs to perform a series of operations, including form data validation, data type conversion, encapsulating form data into JavaBean s, etc. these operations are completed by HandlerApater. Developers only need to focus on the processing of business logic, DispatcherServlet executes different handlers through the HandlerAdapter.
  • ModelAndView: the model data and view information are loaded and returned to the dispatcher servlet as the processing result of the Handler.
  • ViewResolver: a view parser, which is used by dispatchservlet to parse logical views into physical views, and finally respond the rendering results to the client.

Workflow of Spring MVC

  • The client request was received by the dispacherservlet.
  • Map to Handler according to HandlerMapping.
  • Generate Handler and HandlerInterceptor.
  • Handler and HandlerInterceptor are returned to the dispatcherservlet together in the form of HandlerExecutionChain.
  • DispatcherServlet calls the Handler method through the HandlerAdapter to complete business logic processing.
  • The Handler returns a ModelAndView to the dispatcher servlet.
  • The dispatcher servlet passes the obtained ModelAndView object to the ViewResolver View parser, and parses the logical View into a physical View.
  • ViewResovler returns a View to the dispatcher servlet.
  • The dispatcher servlet renders the View according to the View (fills the Model data Model into the View).
  • DispatcherServlet responds the rendered results to the client.

The Spring MVC process is very complex and simple in actual development, because most components do not need to be created and managed by developers, but only need to be configured through configuration files. Only handlers and views really need to be processed by developers.

How to use?

  • Create Maven project, POM xml
<dependencies>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>5.0.11.RELEASE</version>
    </dependency>

</dependencies>
  • On the web Configures DispatcherServlet in XML.
<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>
  
  <servlet>
    <servlet-name>dispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springmvc.xml</param-value>
    </init-param>
  </servlet>
  
  <servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  
</web-app>
  • springmvc.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">

    <!-- Automatic scanning -->
    <context:component-scan base-package="com.southwind"></context:component-scan>

    <!-- Configure view parser -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>

</beans>
  • Create Handler
package com.southwind.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class HelloHandler {

    @RequestMapping("/index")
    public String index(){
        System.out.println("Yes index...");
        return "index";
    }
}

Spring MVC annotation

  • @RequestMapping

Spring MVC maps the URL request to the business method through the @ RequestMapping annotation. You can add @ RequestMapping at the class definition and method definition of the Handler. Adding @ RequestMapping at the class definition is equivalent to adding one more access path to the client.

  • @Controller

@The Controller is added at the class definition. The class is managed by an IoC container (combined with the automatic scanning configuration of springmvc.xml). At the same time, it becomes a Controller and can receive client requests.

package com.southwind.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/hello")
public class HelloHandler {

    @RequestMapping("/index")
    public String index(){
        System.out.println("Yes index...");
        return "index";
    }
}
  • @RequestMapping related parameters

1. Value: Specifies the actual address of the URL request, which is the default value of @ RequestMapping.

@RequestMapping("/index")
public String index(){
    System.out.println("Yes index...");
    return "index";
}

be equal to

@RequestMapping(value="/index")
public String index(){
    System.out.println("Yes index...");
    return "index";
}

2. Method: Specifies the method type of the request, such as GET, POST, PUT and delete.

@RequestMapping(value = "/index",method = RequestMethod.GET)
public String index(){
    System.out.println("Yes index...");
    return "index";
}

The above code indicates that the index method can only receive GET requests.

3. params: Specifies that the request must contain some parameters, otherwise the method cannot be called.

@RequestMapping(value = "/index",method = RequestMethod.GET,params = {"name","id=10"})
public String index(){
    System.out.println("Yes index...");
    return "index";
}

The above code indicates that the request must contain two parameters: name and id, and the value of id must be 10.

For parameter binding, add @ RequestParam annotation to complete the mapping between HTTP request parameters and business method parameters in the formal parameter list.

@RequestMapping(value = "/index",method = RequestMethod.GET,params = {"name","id=10"})
public String index(@RequestParam("name") String str,@RequestParam("id") int age){
    System.out.println(str);
    System.out.println(age);
    System.out.println("Yes index...");
    return "index";
}

The above code indicates that the requested parameter name and id are assigned to the formal parameters str and age respectively, and the data type conversion is automatically completed. The "10" is converted to the int type 10 and then assigned to age. These tasks are completed by the HandlerAdapter.

Spring MVC also supports RESTful URL s.

Traditional type: http://localhost:8080/hello/index?name=zhangsan&id=10

REST: http://localhost:8080/hello/index/zhangsan/10

@RequestMapping("/rest/{name}/{id}")
public String rest(@PathVariable("name") String name,@PathVariable("id") int id){
    System.out.println(name);
    System.out.println(id);
    return "index";
}

Complete the mapping of request parameters and formal parameters through the @ PathVariable annotation.

  • Mapping cookies

Spring MVC can directly obtain the Cookie value in the business method through mapping.

@RequestMapping("/cookie")
public String cookie(@CookieValue(value = "JSESSIONID") String sessionId){
    System.out.println(sessionId);
    return "index";
}
  • Use JavaBean binding parameters

Spring MVC will automatically match the request parameter name and JavaBean attribute name, automatically fill in the attribute value for the object, and support associative attributes at the same time.

package com.southwind.entity;

import lombok.Data;

@Data
public class Address {
    private String value;
}
package com.southwind.entity;

import lombok.Data;

@Data
public class User {
    private long id;
    private String name;
    private Address address;
}
<%--
  Created by IntelliJ IDEA.
  User: southwind
  Date: 2019-03-13
  Time: 15:33
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <form action="/hello/save" method="post">
        user id: <input type="text" name="id"/><br/>
        user name:<input type="text" name="name"/><br/>
        User address:<input type="text" name="address.value"/><br/>
        <input type="submit" value="register"/>
    </form>
</body>
</html>
@RequestMapping(value = "/save",method = RequestMethod.POST)
public String save(User user){
    System.out.println(user);
    return "index";
}

If there is a Chinese garbled code problem, just click on the web XML can be added with Spring MVC's own filter.

<filter>
    <filter-name>encodingFilter</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>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>
  • Forwarding and redirection of JSP pages:

Spring MVC responds to JSP S in the form of forwarding by default.

1. Forward

@RequestMapping("/forward")
public String forward(){
    return "forward:/index.jsp";
    //        return "index";
}

2. Redirect

@RequestMapping("/redirect")
public String redirect(){
    return "redirect:/index.jsp";
}

Spring MVC data binding

Data binding: directly obtain the parameters in the client HTTP request in the back-end business method, and map the request parameters to the formal parameters of the business method. The data binding in Spring MVC is completed by the HandlerAdapter.

  • Basic data type
@RequestMapping("/baseType")
@ResponseBody
public String baseType(int id){
    return id+"";
}

@ResponseBody means that Spring MVC will directly respond the return value of the business method to the client. If @ ResponseBody annotation is not added, Spring MVC will pass the return value of the business method to DispatcherServlet, and then DispatcherServlet will call ViewResolver to parse the return value and map it to a JSP resource.

  • Packaging
@RequestMapping("/packageType")
@ResponseBody
public String packageType(@RequestParam(value = "num",required = false,defaultValue = "0") Integer id){
    return id+"";
}

The wrapper class can receive null. When the HTTP request has no parameters, the wrapper class is used to define the data type of the formal parameter, and the program will not throw an exception.

@RequestParam

value = "num": assign the parameter named num in the HTTP request to the formal parameter id.

requried: set whether num is required. true means required, false means not required, and can be omitted.

defaultValue = "0": if there is no num parameter in the HTTP request, the default value is 0

  • array
@RestController
@RequestMapping("/data")
public class DataBindHandler {
    @RequestMapping("/array")
    public String array(String[] name){
        String str = Arrays.toString(name);
        return str;
    }
}

@RestController indicates that the controller will directly respond to the return value of the business method to the client without view resolution.

@Controller means that the return value of each business method of the controller will be sent to the view parser for parsing. If you only need to respond to the data to the client without view parsing, you need to add @ ResponseBody at the corresponding business method definition.

@RestController
@RequestMapping("/data")
public class DataBindHandler {
    @RequestMapping("/array")
    public String array(String[] name){
        String str = Arrays.toString(name);
        return str;
    }
}

Equivalent to

@Controller
@RequestMapping("/data")
public class DataBindHandler {
    @RequestMapping("/array")
    @ResponseBody
    public String array(String[] name){
        String str = Arrays.toString(name);
        return str;
    }
}
  • List

Spring MVC does not support direct conversion of List type, so you need to wrap the List collection.

Collection encapsulation class

package com.southwind.entity;

import lombok.Data;

import java.util.List;

@Data
public class UserList {
    private List<User> users;
}

JSP

<%--
  Created by IntelliJ IDEA.
  User: southwind
  Date: 2019-03-14
  Time: 09:12
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <form action="/data/list" method="post">
        User 1 No.:<input type="text" name="users[0].id"/><br/>
        User 1 Name:<input type="text" name="users[0].name"/><br/>
        User 2 No.:<input type="text" name="users[1].id"/><br/>
        User 2 Name:<input type="text" name="users[1].name"/><br/>
        User 3 No.:<input type="text" name="users[2].id"/><br/>
        User 3 Name:<input type="text" name="users[2].name"/><br/>
        <input type="submit" value="Submit"/>
    </form>
</body>
</html>

Business method

@RequestMapping("/list")
public String list(UserList userList){
    StringBuffer str = new StringBuffer();
    for(User user:userList.getUsers()){
        str.append(user);
    }
    return str.toString();
}

Handle @ ResponseBody Chinese garbled code in springmvc Configure the message converter in XML.

<mvc:annotation-driven>
    <!-- Message converter -->
    <mvc:message-converters register-defaults="true">
        <bean class="org.springframework.http.converter.StringHttpMessageConverter">
            <property name="supportedMediaTypes" value="text/html;charset=UTF-8"></property>
        </bean>
    </mvc:message-converters>
</mvc:annotation-driven>
  • Map

Custom encapsulation class

package com.southwind.entity;

import lombok.Data;

import java.util.Map;

@Data
public class UserMap {
    private Map<String,User> users;
}

Business method

@RequestMapping("/map")
public String map(UserMap userMap){
    StringBuffer str = new StringBuffer();
    for(String key:userMap.getUsers().keySet()){
        User user = userMap.getUsers().get(key);
        str.append(user);
    }
    return str.toString();
}

JSP

<%--
  Created by IntelliJ IDEA.
  User: southwind
  Date: 2019-03-14
  Time: 09:12
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <form action="/data/map" method="post">
        User 1 No.:<input type="text" name="users['a'].id"/><br/>
        User 1 Name:<input type="text" name="users['a'].name"/><br/>
        User 2 No.:<input type="text" name="users['b'].id"/><br/>
        User 2 Name:<input type="text" name="users['b'].name"/><br/>
        User 3 No.:<input type="text" name="users['c'].id"/><br/>
        User 3 Name:<input type="text" name="users['c'].name"/><br/>
        <input type="submit" value="Submit"/>
    </form>
</body>
</html>
  • JSON

The data in JSON format generated by the client is directly bound to the formal parameters of the business method through Spring MVC.

Processing Spring MVC failed to load static resources on the web Add configuration static resources to XML.

<servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>*.js</url-pattern>
</servlet-mapping>

JSP

<%--
  Created by IntelliJ IDEA.
  User: southwind
  Date: 2019-03-14
  Time: 10:35
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <script type="text/javascript" src="js/jquery-3.3.1.min.js"></script>
    <script type="text/javascript">
        $(function(){
           var user = {
               "id":1,
               "name":"Zhang San"
           };
           $.ajax({
               url:"/data/json",
               data:JSON.stringify(user),
               type:"POST",
               contentType:"application/json;charset=UTF-8",
               dataType:"JSON",
               success:function(data){
                   alter(data.id+"---"+data.name);
               }
           })
        });
    </script>
</head>
<body>

</body>
</html>

Business method

@RequestMapping("/json")
public User json(@RequestBody User user){
    System.out.println(user);
    user.setId(6);
    user.setName("Zhang Liu");
    return user;
}

The transformation between JSON and JavaBean in Spring MVC needs the help of fastjson, POM XML introduces related dependencies.

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.32</version>
</dependency>

springmvc. Add fastjson configuration to XML.

<mvc:annotation-driven>
    <!-- Message converter -->
    <mvc:message-converters register-defaults="true">
        <bean class="org.springframework.http.converter.StringHttpMessageConverter">
            <property name="supportedMediaTypes" value="text/html;charset=UTF-8"></property>
        </bean>
        <!-- to configure fastjson -->
        <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter4"></bean>
    </mvc:message-converters>
</mvc:annotation-driven>

Spring MVC model data parsing

Built in objects corresponding to the four scopes of JSP: pageContext, request, session and application.

The binding of model data is completed by ViewResolver. In actual development, we need to add model data first and then hand it to ViewResolver for binding.

Spring MVC provides the following ways to add model data:

  • Map
  • Model
  • ModelAndView
  • @SessionAttribute
  • @ModelAttribute

Bind the schema data to the request object.

1,Map

@RequestMapping("/map")
public String map(Map<String,User> map){
    User user = new User();
    user.setId(1L);
    user.setName("Zhang San");
    map.put("user",user);
    return "view";
}

JSP

<%--
  Created by IntelliJ IDEA.
  User: southwind
  Date: 2019-03-14
  Time: 11:36
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page isELIgnored="false" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    ${requestScope.user}
</body>
</html>

2,Model

@RequestMapping("/model")
public String model(Model model){
    User user = new User();
    user.setId(1L);
    user.setName("Zhang San");
    model.addAttribute("user",user);
    return "view";
}

3,ModelAndView

@RequestMapping("/modelAndView")
public ModelAndView modelAndView(){
    User user = new User();
    user.setId(1L);
    user.setName("Zhang San");
    ModelAndView modelAndView = new ModelAndView();
    modelAndView.addObject("user",user);
    modelAndView.setViewName("view");
    return modelAndView;
}

@RequestMapping("/modelAndView2")
public ModelAndView modelAndView2(){
    User user = new User();
    user.setId(1L);
    user.setName("Zhang San");
    ModelAndView modelAndView = new ModelAndView();
    modelAndView.addObject("user",user);
    View view = new InternalResourceView("/view.jsp");
    modelAndView.setView(view);
    return modelAndView;
}

@RequestMapping("/modelAndView3")
public ModelAndView modelAndView3(){
    User user = new User();
    user.setId(1L);
    user.setName("Zhang San");
    ModelAndView modelAndView = new ModelAndView("view");
    modelAndView.addObject("user",user);
    return modelAndView;
}

@RequestMapping("/modelAndView4")
public ModelAndView modelAndView4(){
    User user = new User();
    user.setId(1L);
    user.setName("Zhang San");
    View view = new InternalResourceView("/view.jsp");
    ModelAndView modelAndView = new ModelAndView(view);
    modelAndView.addObject("user",user);
    return modelAndView;
}

@RequestMapping("/modelAndView5")
public ModelAndView modelAndView5(){
    User user = new User();
    user.setId(1L);
    user.setName("Zhang San");
    Map<String,User> map = new HashMap<>();
    map.put("user",user);
    ModelAndView modelAndView = new ModelAndView("view",map);
    return modelAndView;
}

@RequestMapping("/modelAndView6")
public ModelAndView modelAndView6(){
    User user = new User();
    user.setId(1L);
    user.setName("Zhang San");
    Map<String,User> map = new HashMap<>();
    map.put("user",user);
    View view = new InternalResourceView("/view.jsp");
    ModelAndView modelAndView = new ModelAndView(view,map);
    return modelAndView;
}

@RequestMapping("/modelAndView7")
public ModelAndView modelAndView7(){
    User user = new User();
    user.setId(1L);
    user.setName("Zhang San");
    ModelAndView modelAndView = new ModelAndView("view","user",user);
    return modelAndView;
}

@RequestMapping("/modelAndView8")
public ModelAndView modelAndView8(){
    User user = new User();
    user.setId(1L);
    user.setName("Zhang San");
    View view = new InternalResourceView("/view.jsp");
    ModelAndView modelAndView = new ModelAndView(view,"user",user);
    return modelAndView;
}

4,HttpServletRequest

@RequestMapping("/request")
public String request(HttpServletRequest request){
    User user = new User();
    user.setId(1L);
    user.setName("Zhang San");
    request.setAttribute("user",user);
    return "view";
}

5,@ModelAttribute

  • Define a method that is specifically used to return objects to be populated into the model data.
@ModelAttribute
public User getUser(){
    User user = new User();
    user.setId(1L);
    user.setName("Zhang San");
    return user;
}
@ModelAttribute
public void getUser(Map<String,User> map){
    User user = new User();
    user.setId(1L);
    user.setName("Zhang San");
    map.put("user",user);
}
@ModelAttribute
public void getUser(Model model){
    User user = new User();
    user.setId(1L);
    user.setName("Zhang San");
    model.addAttribute("user",user);
}
  • There is no need to process model data in the business method, just return to the view.
@RequestMapping("/modelAttribute")
public String modelAttribute(){
    return "view";
}

Bind model data to session object

1. Use the native Servlet API directly.

@RequestMapping("/session")
public String session(HttpServletRequest request){
    HttpSession session = request.getSession();
    User user = new User();
    user.setId(1L);
    user.setName("Zhang San");
    session.setAttribute("user",user);
    return "view";
}

@RequestMapping("/session2")
public String session2(HttpSession session){
    User user = new User();
    user.setId(1L);
    user.setName("Zhang San");
    session.setAttribute("user",user);
    return "view";
}

2,@SessionAttribute

@SessionAttributes(value = {"user","address"})
public class ViewHandler {
}

For all business methods in ViewHandler, as long as the objects with key = "user" and key = "address" are added to the request, Spring MVC will automatically add the data to the session and save the key unchanged.

@SessionAttributes(types = {User.class,Address.class})
public class ViewHandler {
}

For all business methods in ViewHandler, as long as objects with data types of User and Address are added to the request, Spring MVC will automatically add the data to the session and save the key unchanged.

Bind the model data to the application object

@RequestMapping("/application")
public String application(HttpServletRequest request){
    ServletContext application = request.getServletContext();
    User user = new User();
    user.setId(1L);
    user.setName("Zhang San");
    application.setAttribute("user",user);
    return "view";
}

Spring MVC custom data converter

Data converter refers to converting the parameters in the client HTTP request into the formal parameters defined in the business method. User defined means that developers can independently design the conversion method. HandlerApdter has provided general conversion, String to int, String to double, form data encapsulation, etc., but the HandlerAdapter cannot convert in special business scenarios, Developers need to customize the converter.

The client inputs String type data "2019-03-03", and the user-defined converter converts the data into Date type objects.

  • Create a DateConverter converter and implement the converter interface.
package com.southwind.converter;

import org.springframework.core.convert.converter.Converter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateConverter implements Converter<String, Date> {

    private String pattern;

    public DateConverter(String pattern){
        this.pattern = pattern;
    }

    @Override
    public Date convert(String s) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(this.pattern);
        Date date = null;
        try {
            date = simpleDateFormat.parse(s);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }
}
  • springmvc.xml configuration converter.
<!-- Configure custom converter -->
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
    <property name="converters">
        <list>
            <bean class="com.southwind.converter.DateConverter">
                <constructor-arg type="java.lang.String" value="yyyy-MM-dd"></constructor-arg>
            </bean>
        </list>
    </property>
</bean>

<mvc:annotation-driven conversion-service="conversionService">
    <!-- Message converter -->
    <mvc:message-converters register-defaults="true">
        <bean class="org.springframework.http.converter.StringHttpMessageConverter">
            <property name="supportedMediaTypes" value="text/html;charset=UTF-8"></property>
        </bean>
        <!-- to configure fastjson -->
        <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter4"></bean>
    </mvc:message-converters>
</mvc:annotation-driven>
  • JSP
<%--
  Created by IntelliJ IDEA.
  User: southwind
  Date: 2019-03-14
  Time: 14:47
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <form action="/converter/date" method="post">
        Please enter a date:<input type="text" name="date"/>(yyyy-MM-dd)<br/>
        <input type="submit" value="Submit"/>
    </form>
</body>
</html>
  • Handler
package com.southwind.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

@RestController
@RequestMapping("/converter")
public class ConverterHandler {

    @RequestMapping("/date")
    public String date(Date date){
        return date.toString();
    }
}

String to Student

StudentConverter

package com.southwind.converter;

import com.southwind.entity.Student;
import org.springframework.core.convert.converter.Converter;

public class StudentConverter implements Converter<String, Student> {
    @Override
    public Student convert(String s) {
        String[] args = s.split("-");
        Student student = new Student();
        student.setId(Long.parseLong(args[0]));
        student.setName(args[1]);
        student.setAge(Integer.parseInt(args[2]));
        return student;
    }
}

springmvc.xml

<!-- Configure custom converter -->
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
    <property name="converters">
        <list>
            <bean class="com.southwind.converter.DateConverter">
                <constructor-arg type="java.lang.String" value="yyyy-MM-dd"></constructor-arg>
            </bean>
            <bean class="com.southwind.converter.StudentConverter"></bean>
        </list>
    </property>
</bean>

<mvc:annotation-driven conversion-service="conversionService">
    <!-- Message converter -->
    <mvc:message-converters register-defaults="true">
        <bean class="org.springframework.http.converter.StringHttpMessageConverter">
            <property name="supportedMediaTypes" value="text/html;charset=UTF-8"></property>
        </bean>
        <!-- to configure fastjson -->
        <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter4"></bean>
    </mvc:message-converters>
</mvc:annotation-driven>

JSP

<%--
  Created by IntelliJ IDEA.
  User: southwind
  Date: 2019-03-14
  Time: 15:23
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <form action="/converter/student" method="post">
        Please enter student information:<input type="text" name="student"/>(id-name-age)<br/>
        <input type="submit" value="Submit"/>
    </form>
</body>
</html>

Handler

@RequestMapping("/student")
public String student(Student student){
    return student.toString();
}

Spring MVC REST

REST: Representational State Transfer, state transition of resource presentation layer, is a mainstream Internet software architecture at present. It has clear structure, standard specification, easy to understand and easy to expand.

  • Resource

An entity on the network, or a specific information existing in the network, a text, a picture, a song, a video, etc., in short, is a specific existence. A URI (uniform resource locator) can be used to point to it. Each resource has a corresponding specific URI. To obtain the resource, you only need to access the corresponding URI.

  • Presentation layer

The specific forms of resources, such as text, can be expressed in txt format, HTML, XML, JSON and other formats.

  • State Transfer

If the client wants to operate a resource in the server, it needs to make the server perform state transition in some way. This transition is based on the presentation layer, which is called "presentation layer state transition".

characteristic

  • URL s are more concise.
  • It is conducive to resource sharing between different systems. Resource sharing can be realized only by observing certain specifications and without other configuration.

How to use

The specific operation of REST is that the four verbs representing the operation mode in the HTTP protocol correspond to the CRUD basic operation respectively.

GET is used to GET resources.

POST is used to represent a new resource.

PUT is used to indicate modifying resources.

DELETE is used to DELETE resources.

Handler

package com.southwind.controller;

import com.southwind.entity.Student;
import com.southwind.entity.User;
import com.southwind.repository.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.Collection;

@RestController
@RequestMapping("/rest")
public class RESTHandeler {

    @Autowired
    private StudentRepository studentRepository;

    @GetMapping("/findAll")
    public Collection<Student> findAll(HttpServletResponse response){
        response.setContentType("text/json;charset=UTF-8");
        return studentRepository.findAll();
    }

    @GetMapping("/findById/{id}")
    public Student findById(@PathVariable("id") long id){
        return studentRepository.findById(id);
    }

    @PostMapping("/save")
    public void save(@RequestBody Student student){
        studentRepository.saveOrUpdate(student);
    }

    @PutMapping("/update")
    public void update(@RequestBody Student student){
        studentRepository.saveOrUpdate(student);
    }

    @DeleteMapping("/deleteById/{id}")
    public void deleteById(@PathVariable("id") long id){
        studentRepository.deleteById(id);
    }

}

StudentRepository

package com.southwind.repository;

import com.southwind.entity.Student;

import java.util.Collection;

public interface StudentRepository {
    public Collection<Student> findAll();
    public Student findById(long id);
    public void saveOrUpdate(Student student);
    public void deleteById(long id);
}

StudentRepositoryImpl

package com.southwind.repository.impl;

import com.southwind.entity.Student;
import com.southwind.repository.StudentRepository;
import org.springframework.stereotype.Repository;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

@Repository
public class StudentRepositoryImpl implements StudentRepository {

    private static Map<Long,Student> studentMap;

    static{
        studentMap = new HashMap<>();
        studentMap.put(1L,new Student(1L,"Zhang San",22));
        studentMap.put(2L,new Student(2L,"Li Si",23));
        studentMap.put(3L,new Student(3L,"Wang Wu",24));
    }

    @Override
    public Collection<Student> findAll() {
        return studentMap.values();
    }

    @Override
    public Student findById(long id) {
        return studentMap.get(id);
    }

    @Override
    public void saveOrUpdate(Student student) {
        studentMap.put(student.getId(),student);
    }

    @Override
    public void deleteById(long id) {
        studentMap.remove(id);
    }
}

Spring MVC file upload and download

Single file upload

The bottom layer is to use the Apache fileupload component to complete the upload, which is encapsulated by Spring MVC.

  • pom.xml
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.5</version>
</dependency>

<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.3</version>
</dependency>
  • JSP
<%--
  Created by IntelliJ IDEA.
  User: southwind
  Date: 2019-03-15
  Time: 09:09
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page isELIgnored="false" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <form action="/file/upload" method="post" enctype="multipart/form-data">
        <input type="file" name="img"/>
        <input type="submit" value="upload"/>
    </form>
    <img src="${path}">
</body>
</html>

1. The type of input is set to file.

2. The method of the form is set to post (the get request can only pass the file name to the server)

3. The enctype of from is set to multipart form data (if not set, only the file name can be passed to the server)

  • Handler
package com.southwind.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

@Controller
@RequestMapping("/file")
public class FileHandler {

    @PostMapping("/upload")
    public String upload(MultipartFile img, HttpServletRequest request){
        if(img.getSize()>0){
            //Get the file path to save the uploaded file
            String path = request.getServletContext().getRealPath("file");
            //Get the uploaded file name
            String name = img.getOriginalFilename();
            File file = new File(path,name);
            try {
                img.transferTo(file);
                //Save the uploaded file path
                request.setAttribute("path","/file/"+name);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "upload";
    }
}
  • springmvc.xml
<!-- Configure upload component -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean>
  • web.xml add the following configuration, otherwise the client cannot access png
<servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>*.png</url-pattern>
</servlet-mapping>

Multi file upload

pom.xml

<dependency>
    <groupId>jstl</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
</dependency>

<dependency>
    <groupId>taglibs</groupId>
    <artifactId>standard</artifactId>
    <version>1.1.2</version>
</dependency>

JSP

<%--
  Created by IntelliJ IDEA.
  User: southwind
  Date: 2019-03-15
  Time: 09:32
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <form action="/file/uploads" method="post" enctype="multipart/form-data">
        file1:<input type="file" name="imgs"/><br/>
        file2:<input type="file" name="imgs"/><br/>
        file3:<input type="file" name="imgs"><br/>
        <input type="submit" value="upload"/>
    </form>
    <c:forEach items="${files}" var="file" >
        <img src="${file}" width="300px">
    </c:forEach>
</body>
</html>

Handler

@PostMapping("/uploads")
public String uploads(MultipartFile[] imgs,HttpServletRequest request){
    List<String> files = new ArrayList<>();
    for (MultipartFile img:imgs){
        if(img.getSize()>0){
            //Get the file path to save the uploaded file
            String path = request.getServletContext().getRealPath("file");
            //Get the uploaded file name
            String name = img.getOriginalFilename();
            File file = new File(path,name);
            try {
                img.transferTo(file);
                //Save the uploaded file path
                files.add("/file/"+name);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    request.setAttribute("files",files);
    return "uploads";
}

download

  • JSP
<%--
  Created by IntelliJ IDEA.
  User: southwind
  Date: 2019-03-15
  Time: 10:36
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <a href="/file/download/1">1.png</a>
    <a href="/file/download/2">2.png</a>
    <a href="/file/download/3">3.png</a>
</body>
</html>
  • Handler
@GetMapping("/download/{name}")
public void download(@PathVariable("name") String name, HttpServletRequest request, HttpServletResponse response){
    if(name != null){
        name += ".png";
        String path = request.getServletContext().getRealPath("file");
        File file = new File(path,name);
        OutputStream outputStream = null;
        if(file.exists()){
            response.setContentType("application/forc-download");
            response.setHeader("Content-Disposition","attachment;filename="+name);
            try {
                outputStream = response.getOutputStream();
                outputStream.write(FileUtils.readFileToByteArray(file));
                outputStream.flush();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if(outputStream != null){
                    try {
                        outputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}

Spring MVC form tag library

  • Handler
@GetMapping("/get")
public ModelAndView get(){
    ModelAndView modelAndView = new ModelAndView("tag");
    Student student = new Student(1L,"Zhang San",22);
    modelAndView.addObject("student",student);
    return modelAndView;
}
  • JSP
<%--
  Created by IntelliJ IDEA.
  User: southwind
  Date: 2019-03-15
  Time: 10:53
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page isELIgnored="false" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h1>Student information</h1>
    <form:form modelAttribute="student">
        student ID: <form:input path="id"/><br/>
        Student Name:<form:input path="name"/><br/>
        Student age:<form:input path="age"/><br/>
        <input type="submit" value="Submit"/>
    </form:form>
</body>
</html>

1. The syntax of importing Spring MVC form tag library into JSP page is very similar to that of importing JSTL tag library. The prefix prefix can be customized, usually defined as from.

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>

2. Bind the form with the model data, complete the binding through the modelAttribute attribute, and set the value of modelAttribute to the key value corresponding to the model data.

Handeler:modelAndView.addObject("student",student);
JSP:<form:form modelAttribute="student">

3. After the form is bound, take out the value of the model data and bind it to different tags. Complete by setting the path attribute of the tag, and set the value of the path attribute to the attribute name corresponding to the model data.

student ID: <form:input path="id"/><br/>
Student Name:<form:input path="name"/><br/>
Student age:<form:input path="age"/><br/>

Common form labels

  • from
<form:from modelAttribute="student"/>

The rendering is < form > < / from > in HTML, and the specific model data is bound through the modelAttribute attribute.

  • input
<form:input path="name"/>

The < input type = "text" / > in HTML is rendered. The from tag is bound to the model data, and the input tag is bound to the attribute value in the model data. The path attribute can correspond to the attribute name in the model data, and supports and associated operations.

<from:input path="address.name"/>
  • password
<form:password path="password"/>

The < input type = "password" / > in HTML is rendered, which is bound with the attribute value of the model data through the path attribute, and the value of the password tag will not be displayed on the page.

  • checkbox
<form:checkbox path="hobby" value="read"/>
student.setFlag(false);
checkbox: <form:checkbox path="flag" value="flag"></form:checkbox><br/>

The < input type = "checkbox" / > in HTML is rendered. boolean, array and collection can be bound by binding path to the attribute value of model data.

If the boolean value is bound, if the value of the variable is true, it means that the check box is selected; otherwise, it means that it is not selected.

If an array or collection is bound, and the elements in the array / collection are equal to the value of the checkbox, select.

student.setHobby(Arrays.asList("read","watch movie","play a game"));
modelAndView.addObject("student",student);
Hobbies:<form:checkbox path="hobby" value="Photography"></form:checkbox>Photography<br/>
<form:checkbox path="hobby" value="read"></form:checkbox>read<br/>
<form:checkbox path="hobby" value="Listen to the music"></form:checkbox>Listen to the music<br/>
<form:checkbox path="hobby" value="watch movie"></form:checkbox>watch movie<br/>
<form:checkbox path="hobby" value="Travel"></form:checkbox>Travel<br/>
<form:checkbox path="hobby" value="play a game"></form:checkbox>play a game<br/>
<input type="submit" value="Submit"/>
  • checkboxes
<form:checkboxes items=${student.hobby} path="selecHobby"/>

The rendering is a group of < input type = "checkbox" / > in HTML, which is a simplification of < form: checkbox / >. It needs to be used in combination with the items and path attributes. Items binds the traversed set or array, and path binds the selected set or array. It can be understood that items is the full optional set, and path is the default selected set.

student.setHobby(Arrays.asList("Photography","read","Listen to the music","watch movie","Travel","play a game"));
student.setSelectHobby(Arrays.asList("Photography","read","Listen to the music"));
modelAndView.addObject("student",student);
Hobbies:<form:checkboxes path="selectHobby" items="${student.hobby}"/><br/>

It should be noted that path can directly bind the attribute value of the model data, while items needs to obtain data from the domain object in the form of EL expression, and the attribute name cannot be written directly.

  • rabiobutton
<from:radiobutton path="radioId" value="0"/>

A < input type = "radio" / > in HTML is rendered. If the bound data is equal to the value value of the tag, it is selected, otherwise it is not selected.

student.setRadioId(1);
modelAndView.addObject("student",student);
radiobutton:<form:radiobutton path="radioId" value="1"/>radiobutton<br/>
  • radiobuttons
<form:radiobuttons itmes="${student.grade}" path="selectGrade"/>

A group of < input type = "radio" / > in HTML is rendered, which needs to be used in combination with the items and path attributes. Items binds the traversed collection or array, and path binds the selected value. Items is all optional types, and path is the default selected option. The usage is consistent with < form: checkboxes / >.

Map<Integer,String> gradeMap = new HashMap<>();
gradeMap.put(1,"first grade");
gradeMap.put(2,"second grade");
gradeMap.put(3,"Third grade");
gradeMap.put(4,"fourth grade");
gradeMap.put(5,"fifth grade");
gradeMap.put(6,"Sixth grade");
student.setGradeMap(gradeMap);
student.setSelectGrade(3);
modelAndView.addObject("student",student);
Student grade:<form:radiobuttons items="${student.gradeMap}" path="selectGrade"/><br/>
  • select
<form:select items="${student.citys}" path="selectCity"/>

A < select / > tag in HTML is rendered, which needs to be used in combination with the items and path attributes. Items binds the traversed collection or array, and path binds the selected value. The usage is consistent with < from: RadioButtons / >.

Map<Integer,String> cityMap = new HashMap<>();
cityMap.put(1,"Beijing");
cityMap.put(2,"Shanghai");
cityMap.put(3,"Guangzhou");
cityMap.put(4,"Shenzhen");
student.setCityMap(cityMap);
student.setSelectCity(3);
modelAndView.addObject("student",student);
City:<form:select items="${student.cityMap}" path="selectCity"></form:select><br/>
  • options

form:select is used in combination with form:options. from:select only defines the path attribute, adds a sub tag form:options inside the form:select tag, sets the items attribute, and obtains the traversed collection.

City:<form:select path="selectCity">
  				<form:options items="${student.cityMap}"></form:options>
				</form:select><br/>
  • option

    form:select is used in combination with form:option. from:select defines the path attribute and sets the value value for each form:option. This item is selected by default.

City:<form:select path="selectCity">
            <form:option value="1">Hangzhou</form:option>
            <form:option value="2">Chengdu</form:option>
            <form:option value="3">Xi'an</form:option>
        </form:select><br/>
  • textarea

A < textarea / > in HTML is rendered, and the path binds the attribute value of the model data as the default value of the text input field.

student.setIntroduce("Hello, I'm...");
modelAndView.addObject("student",student);
Information:<form:textarea path="introduce"/><br/>
  • errors

Processing error information is generally used for data verification. This label needs to be used in combination with the verifier of Spring MVC.

Spring MVC data verification

Spring MVC provides two data verification methods: 1. Based on the Validator interface. 2. Use the Annotation JSR - 303 standard for verification.

The method based on the Validator interface needs to customize the Validator validator. The validation rules of each data need to be completed manually by the developer. Using the Annotation JSR - 303 standard does not need to customize the Validator. The validation rules of each attribute can be directly added to the entity class through annotation. This method is more convenient and recommended for practical development.

Based on Validator interface

  • Entity class Account
package com.southwind.entity;

import lombok.Data;

@Data
public class Account {
    private String name;
    private String password;
}
  • Customize the verifier AccountValidator and implement the Validator interface.
package com.southwind.validator;

import com.southwind.entity.Account;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

public class AccountValidator implements Validator {
    @Override
    public boolean supports(Class<?> aClass) {
        return Account.class.equals(aClass);
    }

    @Override
    public void validate(Object o, Errors errors) {
        ValidationUtils.rejectIfEmpty(errors,"name",null,"Name cannot be empty");
        ValidationUtils.rejectIfEmpty(errors,"password",null,"Password cannot be empty");
    }
}
  • controller
package com.southwind.controller;

import com.southwind.entity.Account;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/validator")
public class ValidatorHandler {

    @GetMapping("/login")
    public String login(Model model){
        model.addAttribute("account",new Account());
        return "login";
    }

    @PostMapping("/login")
    public String login(@Validated Account account, BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            return "login";
        }
        return "index";
    }
}
  • springmvc.xml configuration validator.
<bean id="accountValidator" class="com.southwind.validator.AccountValidator"></bean>
<mvc:annotation-driven validator="accountValidator"></mvc:annotation-driven>
  • JSP
<%--
  Created by IntelliJ IDEA.
  User: southwind
  Date: 2019-03-18
  Time: 10:31
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page isELIgnored="false" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ taglib prefix="from" uri="http://www.springframework.org/tags/form" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <form:form modelAttribute="account" action="/validator/login" method="post">
        full name:<form:input path="name"/><from:errors path="name"></from:errors><br/>
        password:<form:input path="password"/><from:errors path="password"></from:errors><br/>
        <input type="submit" value="Sign in"/>
    </form:form>
</body>
</html>

Annotation JSR - 303 standard

For verification using the Annotation JSR - 303 standard, you need to import dependent jar files that support this standard. Here we use Hibernate Validator.

  • pom.xml
<!-- JSR-303 -->
<dependency>
  <groupId>org.hibernate</groupId>
  <artifactId>hibernate-validator</artifactId>
  <version>5.3.6.Final</version>
</dependency>

<dependency>
  <groupId>javax.validation</groupId>
  <artifactId>validation-api</artifactId>
  <version>2.0.1.Final</version>
</dependency>

<dependency>
  <groupId>org.jboss.logging</groupId>
  <artifactId>jboss-logging</artifactId>
  <version>3.3.2.Final</version>
</dependency>
  • Add relevant validation rules directly to the entity class by annotation.
package com.southwind.entity;

import lombok.Data;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;

@Data
public class Person {
    @NotEmpty(message = "User name cannot be empty")
    private String username;
    @Size(min = 6,max = 12,message = "Password 6-12 position")
    private String password;
    @Email(regexp = "^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\\\\.[a-zA-Z0-9-]+)*\\\\.[a-zA-Z0-9]{2,6}$",message = "Please enter the correct email format")
    private String email;
    @Pattern(regexp = "^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(18[0,5-9]))\\\\\\\\d{8}$",message = "Please enter the correct phone number")
    private String phone;
}
  • ValidatorHandler
@GetMapping("/register")
public String register(Model model){
    model.addAttribute("person",new Person());
    return "register";
}

@PostMapping("/register")
public String register(@Valid Person person, BindingResult bindingResult){
    if(bindingResult.hasErrors()){
        return "register";
    }
    return "index";
}
  • springmvc.xml
<mvc:annotation-driven />
  • JSP
<%--
  Created by IntelliJ IDEA.
  User: southwind
  Date: 2019-03-18
  Time: 11:29
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page isELIgnored="false" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <form:form modelAttribute="person" action="/validator/register2" method="post">
        user name:<form:input path="username"></form:input><form:errors path="username"/><br/>
        password:<form:password path="password"></form:password><form:errors path="password"/><br/>
        Email:<form:input path="email"></form:input><form:errors path="email"/><br/>
        Telephone:<form:input path="phone"></form:input><form:errors path="phone"/><br/>
        <input type="submit" value="Submit"/>
    </form:form>
</body>
</html>

Detailed verification rules:

@Null the annotated element must be null

@NotNull annotated element cannot be null

@Min(value) the annotated element must be a number and its value must be greater than or equal to the specified minimum value

@Max(value) the annotated element must be a number whose value must be less than or equal to the specified maximum value

@The annotated element of Email must be an Email address

@Pattern the annotated element must conform to the corresponding regular expression

@Length the size of the annotated element must be within the specified range

@NotEmpty the value of the annotated string must be non empty

Null and Empty are different results. String str = null, str is null, string str = '', str is not null, and its value is Empty.

Keywords: Java Spring Spring MVC mvc

Added by luketheduck on Wed, 12 Jan 2022 21:34:38 +0200