SSM Framework Learning-Spring MVC

SSM Framework Learning (3) - Spring MVC

I. MVC Model

mvc mode is not described here, please refer to: SSM Framework Learning (1) - Introduction to SSM Framework

II. Sring Web MVC Brief Introduction and Work Flow

2.1 Introduction to Spring Web MVC

Spring Web MVC is one of the most important modules of Spring Framework. It uses the idea of MVC architecture pattern to decouple the responsibilities of the web layer. It is convenient for us to develop Web programs with MVC structure simply and quickly. Moreover, its API encapsulates some common functions in Web development and simplifies the process of web program development.

Spring Web MVC Core Components:

  • Dispatcher Servlet (Controller, Request Dispatch)
  • Handler Mapping (processor mapper, request dispatch)
  • Controller (Processor, Request Processing Flow)
  • Model AndView (Model, Encapsulating Business Processing Results and Views)
  • ViewResolver (View, View Display Processor)

2.2 Spring Web MVC workflow

1. The user initiates a request to the Dispatcher Servlet (front-end controller), which filters out which requests can access the Servlet and which cannot. That's what url-pattern does, and springmvc.xml configuration files are added.
2. The front-end controller will find Handler Mapping (processor mapper), and complete the url-to-controller mapping component through the processor mapper. Simply speaking, the URL configured or annotated in spring mvc.xml and the corresponding processor class will be found and stored, and stored with map < url, handler >.
3. Handler Mapping has a mapping relationship and finds the processor corresponding to the url. Handler Mapping will return the processor (Hnadler) and add many interceptors before returning.
4. After the Dispatcher Servlet gets the Handler, it finds the Handler Adapter (processor adapter), through which it accesses the processor and executes the processor.
5. Execution Processor (generally referred to as Controller)
6. The processor returns a ModelAndView object to the Handler Adapter.
7. Return the ModelAndView object to the front-end controller (Dispatcher Servlet) through the Handler Adapter.
8. The front-end controller requests ViewResolver (View Resolver) to parse the view, and parses it into a real view (jsp) according to the logical view name. In fact, it is to search the view stored in the Model AndView object at the beginning of the year and find the corresponding page to form the view object.
9. Return the view object to the front-end controller, where there are both data and views in the ModelAndView object.
10. View rendering is to put the data in the ModelAndView object into the request domain for the page to load the data.
11. Through the eighth step, the corresponding page is found by name, and through the tenth step, the request field has the required data, then the view can be rendered, and finally it can be returned.

3. Building Spring Web MVC working environment

  1. Import the jar package
  • commons-logging.jar
  • spring-beans-5.1.3.RELEASE.jar
  • spring-context-5.1.3.RELEASE.jar
  • spring-core-5.1.3.RELEASE.jar
  • spring-expression-5.1.3.RELEASE.jar

In addition to importing

  • spring-aop-5.1.3.RELEASE.jar

Baidu Disk Download Address: Click Download
git Download Address: Click Download

  1. Configure the Internal ResourceViewResource (View Parser)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    <!--Configuration view parser-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!--Configure the prefix and suffix of the view parser with the file type name-->
        <property name="prefix" value="/jsp/"/>
        <property name="suffix" value=".jsp"/>
     </bean>
</beans>

The Internal ResourceViewResolver view parser is used to encapsulate and jump the internal resources of the application. For internal lookup rules, logical view names are configured as prefix and suffix, that is, prefix + view name + suffix.

  1. Configure the front-end controller in web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <!--Configuration of Front-end Controller-->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:config/SpringMVC.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>
</web-app>

load-on-startup:
1.load-on-startup Whether the element tag container should be in web Load this when the application starts servlet,(Instantiate and invoke init()Method)
2.It must be an integer, representing servlet Loading order
3.If the value of the element is negative or is not set, the container will be Servlet Reload when requested.
4.If the value is positive or zero, it means that the container is sandwiched and initialized when the application starts. servlet,The smaller the value, servlet The higher the priority, the more it will be loaded first. When the values are the same, the container will now load in its own order.

  1. Create a JSP folder and create hello.jsp, hello.jsp content in the JSP folder.
  2. Write a processor class (Controller class, which is responsible for the implementation of specific business logic processing, can call services, DAO and other components, programming needs to implement the Controller interface and agreed methods)
package controller;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author zqq
 * @create 2019-08-04-19:07
 */
public class HelloController implements Controller {
    @Override
    public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
        System.out.println("Control begins to execute");
        return new ModelAndView("hello");
    }
}

Introduction to ModelAndView Components:
After implementing the agreed Hadler Request method to process business logic, the controller component needs to return a ModelAndView object. Its main function is to encapsulate the data processed in the background in ModelAndView, and finally transfer the data to the view layer, which also contains a url showing the view (jsp) of the data. address
Common constructors are:

  1. ModelAndView(String viewName):
    viewName: View name, which is the name of the jsp to be displayed. ViewResolver, the view parser, finds the jsp by parsing the ModelAndView object.
  2. ModelAndView(String viewName,Map model)
    model: Processed result data, multiple data stored by key-value, easy to extract these data in the view one by one.
  1. Configure the applicationContext.xml configuration file
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="helloController" class="controller.HelloController"/>
    <!--Configure the processor mapper through which user-specific requests can be mapped to the specified controller On Components-->
    <bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
        <property name="mappings">
            <props>
                <!--key Is the access path, value It's about visiting. controller Of bean Of id-->
                <prop key="hello.do">helloController</prop>
            </props>
        </property>
    </bean>
</beans>

Test success or failure:

Enter in the browser: http://localhost:8080/FirstWeb/hello.do
See if there's anything you wrote in hello.jsp

4. Annotation-based spring development

  1. @ Controller annotation

The common way to implement controller class is to inherit a specific parent class or implement a specific interface, but if you use the @Controller annotation to fame @Controller annotation, you can make the controller class not inherit a specific class and implement a specific interface, but use the controller interface to implement a specified method, which will lead to the controller. Classes can only handle a single request action, while classes with @Controller annotation reputation can support multiple request actions at the same time, which is more flexible.

  1. @ Request Mapping Annotation

@ RequestMapping annotations can be used on both classes and methods, indicating that the class or method corresponds to a customer's request. With this annotation, you don't need to configure Handler Mapping and Handler one by one.

  • The Spring Distribution Processor scans the method that uses the Controller annotation class and checks whether the method uses the @RequestMapping annotation, whereas the @RequestMapping annotation method is the real processor for processing requests, so the two annotations are usually used together.
    Import the jar package:
  • spring-web-5.1.3.RELEASE.jar
  • spring-webmvc-5.1.3.RELEASE.jar

Configure spring mvc. XML

    <!--Scanning Annotation-->
    <context:component-scan base-package="controller"/>
    <!--scanning RequestMapping annotation-->
    <mvc:annotation-driven/>

Modify the HelloController file as follows:

package controller;

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

/**
 * @author zqq
 * @create 2019-08-04-19:07
 */

@Controller
@RequestMapping("hello")
public class HelloController{
    @RequestMapping("data")
    public String data(){
            return "hello";
   }
}

Test success or failure:
Access address: http://localhost:8080/FirstWeb/hello/data.do
Check to see if the contents of the hello.jsp file appear

V. Receiving and Passing Page Value

5.1 Page Value Receiving

  1. Getting with HttpServletRequest
  2. Use the @RequestParam annotation
  3. Encapsulating Bean Objects with Automatic Encapsulation

Modify the hello.jsp file as follows:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h1>Hello</h1>
	<a href="${pageContext.request.contextPath}/index/user.do">Go to Home Page</a>
	<a href="${pageContext.request.contextPath}/index/data.do?uname=Alice">Test parameter transfer</a>
	
	<form action="${pageContext.request.contextPath}/index/register.do" method="post">
		<div>
			User name:<input name="userName" type="text">
		</div>
		<div>
			Password:<input name="password" type="password">
		</div>
		<div>
			Age:<input name="age" type="text">
		</div>
		<div>
			Phone number:<input name="phoneNumber" type="text">
		</div>
		<input type="submit" value="Submission"/>
	</form>
</body>
</html> 

New index.jsp, as follows:

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h1>Welcome to Home Page</h1>
	<h2>${message }</h2>
	<h2>${userName }</h2>
	<h2>${user.userNmae }----${user.password }</h2>
</body>
</html>

New IndexController.java, as follows:

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

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

import cn.goktech.entity.User;

@Controller
@RequestMapping("/index")
public class IndexController {
	//String,ModelAndView,Model,Map,void,View
	@RequestMapping("/user")
	public String index(HttpServletRequest request){
		System.out.println("annotation Controller Successful visit");
		request.setAttribute("message", "Annotation access Controller Success!");
		//request.getParameter("userName"); use this method to get data from the front end
		return "index";
	}
	/*
	 * Transfer data:
	 * 1.request
	 * 2.@RequestParam("uname"):Gets the value of the specified parameter passed by the page
	 * 3.Getting multiple fields can be accepted by the class, but name in the form corresponds to the field of the class one by one.
	 */
	@RequestMapping("/data")
	public String getData(@RequestParam("uname") String userName,Map<String, String> map) {
		System.out.println(userName);
		map.put("userName", userName);
		return "index";
	}
	@RequestMapping("/register")
	public String register(@ModelAttribute("user")  User user) {
		System.out.println(user.getUserName()+"----"+user.getPassword());
		return "index";
	}
}

5.2 Passing Values to Pages

  1. Using HttpRequest Servlet and session
@RequestMapping("login")
public String  checkLogin(String userName ,String  pswd,HttpServletRequest  req){
	UserBean user=userService.login(userName ,password );
	req.setAttribute("loginMesg", "Successful login");
	req.getSession().setAttribute("loginuser",user);
	model.addAttribute("user",user);
	return "userCenter";
}

Using the EL expression on the jsp page, you can get the values loginMesg,{loginMesg},loginMesg,{user.userName}.

  1. Use Map to Pass Values to Pages
public String test1(Map<String, String> map){
	/** Without a map instance, Spring will help us create it.
	* The effect is the same as request.setAttribut(), so the value can be obtained by ${key1} in jsp
	*/
	map.put("key1", "value-1"); 
	map.put("key2", "value-2"); 
	return "userCenter";
}
  1. Using Model and ModelMap to Pass Values to Pages

Adding ModelMap or Model parameters to the Controller processing method has the same effect. Model is an interface that inherits the ModelMap class. ModelMap also inherits Map.

@RequestMapping("login.do")
public String  checkLogin(ModelMap model ){
	UserBean user=userService.login(userName ,password );
	// The use of Model is the same here, and there is no way to set the jsp address to jump in either of them.
	model.addAttribute("user",user);
	return "seccess"
}
//ModelMap data is passed to the jsp page using Attribute of HttpServletRequest
  1. Pass values to pages using ModelAndView

For the target method of the controller, whether the return values are String, View, Map or Model Map, Spring MVC encapsulates them internally as a Model AndView object and returns them to the view parser.
The Model AndView class, as its name indicates, represents the objects of Model and View in the program, but it can facilitate you to return these two objects once. Model and View are still separate concepts, like Model Map, which only contains models.

@RequestMapping("login.do")
public ModelAndView checkLogin(String userName ,String  password ){
	UserBean user=userService.login(userName ,password );
	Map<String Object> data=new HashMap<String Object>();
	data.put("user",user);
	return new ModelAndView("seccess",data);
}
  1. Passing values using @ModelAttribute
@Controller 
public class HelloWorldController { 
    @ModelAttribute("user") 
    public User addAccount() { 
        return new User("jz","123"); 
     } 

    @RequestMapping(value = "/helloWorld") 
    public String helloWorld(@ModelAttribute("user") User user) { 
           user.setUserName("jizhou"); 
           return "helloWorld"; 
        } 
  }

@ ModelAttribute("user") User user annotates method parameters. The value of the parameter user comes from the model attribute in the addAccount() method. If the method body is not marked @SessionAttributes("user"), then scope is request, and if it is marked, scope is session. @ Model Attribute data is passed to the jsp page using Attribute of HttpServletRequest.

  1. Pass values using @SessionAttribte
import java.util.HashMap;
import java.util.Map;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

import cn.goktech.entity.User;

@SessionAttributes(value= {"user"},types= {String.class})
@Controller
public class RegisterController {
	
//	@RequestMapping("/register")
//	public String register(Model model,User user) {
//		model.addAttribute("user", user);
//		return "userInfo";
//	}
	
	@RequestMapping("/register")
	public ModelAndView register(User user) {
		Map<String, Object> data = new HashMap<>();
		data.put("user", user);
		return new ModelAndView("userInfo", data);
	}
	
	
	@RequestMapping("/userInfo")
	public String register(@RequestParam("name") String name,@RequestParam("age") String age, @RequestParam("gender") String gender,Model model) {
		System.out.println("name--"+name);
		System.out.println("age--"+age);
		System.out.println("gender--"+gender);
		
		User user = new User();
		user.setName(name);
		user.setAge(age);
		user.setGender(gender);
		model.addAttribute("user", user);
		return "userInfo";
	}
	
}

After registration, the user is saved in session, accessible by accessing / userinfo

VI. Filters

Spring provides a Character Encoding Filter filter to solve the scrambling code if it encounters Chinese scrambling code in submitting forms, and sets the filter in web.xml.

 <!--Configure Character Set Filters-->
    <filter>
        <filter-name>CEF</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>CEF</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

VII. Interceptors

Interceptors play an important role in Spring MVC, such as intercepting user requests and processing them accordingly. For example, it can be used to verify permission, or to determine whether the user is logged in.

There are two main ways to realize interceptor function:
First: Implementing the Handler Interceptor interface
Second: Implementing the WebRequest Interceptor interface

In the actual application process, we usually intercept user requests by implementing Handler Interceptor interface or inheriting abstract classes of Handler Interceptor Adapter, copying preHandle(), postHandle() and afterCompletion().

Configuration in Spring MVC.xml:

    <!--Configure Logon Interceptor-->
    <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/**"/><!--Intercept all requests-->
            <mvc:exclude-mapping path="/index.do"/><!--Setting permission to pass requests-->
            <mvc:exclude-mapping path="/logging.do"/><!--Setting Requests Allowed to Pass-->
            <bean class="controller.HelloController"/>
        </mvc:interceptor>
    </mvc:interceptors>

Write interceptor:

public class CheckLogin implements HandlerInterceptor{
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		HttpSession session = request.getSession();
		// If login information already exists, intercept it or return false
		if (session.getAttribute("currentUser") != null) {
			return true;
		}else {
			request.setAttribute("message", "Please login first");
			request.getRequestDispatcher("index.do").forward(request, response);
			return false;
		}
	}
	
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub
		HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
	}
	
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub
		HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
	}
}

The Handler Interceptor interface is received in three ways

  1. PreHandle: This method calls the interceptor's preHandle() method after the front-end controller receives the request. This means that the interceptor can continue to call back. If the return value is false, it means the interrupt request (no more calls back).
  2. PosHandle: The purpose of this method is to intercept the processor. It executes after the processor processes, that is, after the controller method calls, but it executes before the Dispatcher Servlet renders the view, that is to say, you can operate on the Model AndView in this method.
  3. After Completion: After the entire request is completed, some resource cleanup can be done

The difference between interceptors and filters

Same: they are all AOP (Aspect Programming) ideas, can achieve permission checking, logging and other functions.
Different:

  1. The scope of use is different: filters are special classes defined in the Servlet specification, interceptors are special classes provided by the Spring framework, filters can only be used in Web programs, interceptors can be used in web applications as well as in applications.
  2. Use resources differently: Interceptors are Spring components that can use any resources in Sring to inject bean objects, transaction management, etc. through IOC, but filters cannot.
  3. Interception depth is different: Filter can only play a role in Servlet, and the interceptor can penetrate into the method before and after, exception throw before and after, interceptor has greater flexibility, so in spring framework, interceptor is preferred.

8. Redirection and request forwarding

Spring uses forwarding to locate views by default. If you need to redirect, you can use two ways:

Way 1: Use prefixes

	@RequestMapping("/forward")
	public String login(String userName,String password,Model model) {
		model.addAttribute("userName", userName);
		model.addAttribute("password", password);
		System.out.println(model.toString());
		//return "redirect:show.do"; // redirect
		return "forward:show.do"; //Request forwarding
	}

Mode 2: If the return value is a Model AndView, use Redirect View

public ModelAndView checkLogin(String userName ,String  password){
	UserBean user=userService.login(userName ,password );
	RedirectView view=new RedirectView("toIndex.do");
	return  new  ModelAndView(view);
}

9. Spring exception handling

  1. Using the simple exception handler provided by Spring MVC

With SimpleMapping Exception Resolver, we can map different exceptions to different jsp pages (configured through Exception Mappings properties). At the same time, we can also specify a default exception prompt page for all exceptions (through the defaultErrorView property configuration), and Spring will display the exception information with this default configuration if the exception thrown does not have a corresponding mapping in the exception Mappings.
The Spring MVC configuration is as follows:

<! - exception handling 1: back-end error-free - > <
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
		// When an exception occurs, the default page
		<property name="defaultErrorView" value="error"></property>
		<property name="exceptionMappings">
			<props>
				// When an exception occurs, the default page
				<prop key="java.lang.Exception">error</prop>
			</props>
		</property>
	</bean> -->
  1. Implementing Handler Exception Resolver Interface Custom Exception Processor
    Configuration in Spring MVC.xml is as follows:
<! - Exception handling mode 2: Backend will not report errors - > Exception handling mode 2
<bean class="cn.goktech.exception.MyExceptionResolver"></bean>

Customize an exception class:

//Custom exception parser
public class MyExceptionResolver implements HandlerExceptionResolver{

	@Override
	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object obj,
			Exception ex) {
		System.out.println("Enter the custom exception parser");
		Map<String, Object> map = new HashMap<>();
		map.put("exception", ex);
		//When an exception occurs, carry the exception to the specified exception handling interface
		return new ModelAndView("error",map);
	}
	
}

3. Use @ExceptionHandler annotation for exception handling and @Controller Advice for global exception handling

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
/**
 * @author 17933
 *Define global exception handling classes
 */
@ControllerAdvice
public class GlobalControllerException {
	
	@ExceptionHandler
	public String testException(Exception e) {
		System.err.println(e.toString());
		System.out.println("Here is the global exception handling class...");
		e.printStackTrace();
		return "error";
	}
}

Here is a good article on the use of these two notes: @ Controller Advice + @ExceptionHandler handles Controller layer exceptions globally

X. Document upload

Spring MVC file upload is handled by MultipartResolver (MultipartResolver), which is an interface with the following two implementation classes:

1. Commons MultipartResolver: This approach relies on the commons Fileupload project under Apeach to process multipart requests, and the jar package of the response must be introduced when using it.

  • commons-io-2.2.jar and commons-fileupload-1.3.2.jar

2. Standar Servlet MultipartResolver: He's a product of Spring 3.1 and doesn't need to introduce jar packages.

Commons MultipartResolver implements file upload:

  1. Configure Spring's xml:
Commons MultipartResolver implements file upload: When configuring id names, you need to pay attention to the following fixed names, otherwise the error will be reported - > 1.
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
	<property name="defaultEncoding" value="utf-8"/>
	<property name="maxUploadSize" value="1048576"/>
</bean>
  1. Use post submission and add enctype attribute with a value of multipart/from-data
<form action="${pageContext.request.contextPath }/upload.do" method="post" enctype="multipart/form-data">
	<div>
		User name:<input type="text" name="userName">
	</div>
	<div>
		Password:<input type="password" name="password">
	</div>
	<div>
		Age:<input type="text" name="age">
	</div>
	<div>
		Document 1:<input type="file" name="fs">
	</div>
	<div>
		Document II:<input type="file" name="fs">
	</div>
	<div>
		Document III:<input type="file" name="fs">
	</div>
	<div>
		<input type="submit" value="Submission">
	</div>
</form>

3. Write the file upload method on the controller component:

@RequestMapping("/upload")
	public String upLoad(@RequestParam("fs") MultipartFile[]  fs,User user) {
		System.out.println(user.getUserName()+","+user.getPassword()+","+user.getAge());
		
		//File storage location
		String uploadPath = "D://SpringUpload";
		File file = new File(uploadPath);
		if (!file.exists()) {
			file.mkdirs();
		}
		
		//Source File - > Object File
		for (MultipartFile f : fs) {//Multi-file traversal
			if (f.isEmpty()) {
				continue;
			}
			File filetarget = new File(uploadPath+File.separator+f.getOriginalFilename());
			try {
				f.transferTo(filetarget);
			} catch (IllegalStateException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return "success";
	}

Data validation

_Front-end page code is vulnerable to attack and change, and the reliability of this verification method is not high. So when we have higher requirements for data security, we will also re-check the data submitted by users on the server side, but if the server side through handwritten regular expressions to achieve data verification is undoubtedly better than the other side. More tedious, bring us unnecessary workload.
_In Springmvc, we can use the Validation rules provided by the validator (essentially an interface) for data Validation. The way is to validate the input content through JSR-303 annotations. The annotation @Valid is used to indicate that the Bean needs to enable annotational Validation, and then the corresponding rules are validated by a series of annotations provided by the specification.

  1. Air check
annotation explain
@Null The annotated element must be null
@NotNull The annotated element must not be null
@NotBlank Verify that the string is not null and the length is greater than 0
@NotEmpty The commented string must be non-null
  1. boolean verification
annotation explain
@AssertTrue The annotated element must be True
@AssertFalse The annotated element must be false
  1. NUMERICAL VERIFICATION
  • integer
annotation explain
@Min(value) The annotated element must be a number whose value must be greater than or equal to the specified minimum
@Max(value) The commented element must be a number whose value must be less than or equal to the specified maximum
@Range(min=,max=,message=) The annotated elements must be within the appropriate scope
  • decimal
annotation explain
@DecimalMin(value) The annotated element must be a number whose value must be greater than or equal to the specified minimum
@DecimalMax(value) The commented element must be a number whose value must be less than or equal to the specified maximum
@Digits(integer=,fraction=) Verify that the string is a number in the specified format, that the interger specifies integer precision, and that fraction specifies decimal precision
  1. Date validation
annotation explain
@Past Verify that Date and Calendar objects are before the current time
@Future Verify that the Date and Calendar objects are after the current time
  1. Regular Verification
annotation explain
@Pattern(regex=) The annotated element must conform to the specified regular expression and can only be added to String type data.
  1. Length Verification
annotation explain
@Size(max=, min=) The size of the annotated element must be within the specified range
@Length(min=,max=) The size of the commented string must be within the specified range
  1. Other validation
annotation explain
@Email The annotated element must be an e-mail address. If it is null, it will pass without verification.
@CreditCardNumber Credit card verification
@ScriptAssert(lang= ,script=, alias=) Complex business logic can be verified by scripts
@URL(protocol=,host=, port=,regexp=, flags=) Address Verification

jar package for data validation;

  • classmate-1.5.0.jar
  • hibernate-validator-6.0.16.Final.jar
  • jboss-logging-3.4.0.Final.jar
  • validation-api-2.0.1.Final.jar
    Baidu Disk Download: Click Download
    git Download: Click Download
  1. Configure Spring MVC.xml as follows:
<!-- Configuration data validation annotations -->
<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
	<property name="providerClass" value="org.hibernate.validator.HibernateValidator"/>
</bean>
<!--automatic logon validator-->
<mvc:annotation-driven validator="validator"></mvc:annotation-driven>
  1. Annotation of Field to Realize Data Verification
ublic class Student {
	@NonNull
	private int id;
	
	@Length(min=2,max=6,message="Name length must be 2-6 position")
	private String name;
	
	@Pattern(regexp="^[0-9]{6,12}$",message="Password must be 6 to 12 digits")
	private String password;
	
	@Pattern(regexp="^1[3-9][0-9]{9}$",message="Incorrect telephone number format")
	private String phoneNumber;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getPhoneNumber() {
		return phoneNumber;
	}

	public void setPhoneNumber(String phoneNumber) {
		this.phoneNumber = phoneNumber;
	}
}
  1. In the controller, when @Valid is added to the entity class, the data is checked. If there is an error message, it will be encapsulated into getFieldErrors() in the BindingResult instance. By returning a List of all error messages, the validator will encapsulate each error message into a FieldError object with a package in it. Message information containing error fields and error prompts.
@RequestMapping("/register")
public String register(@Valid Student student,BindingResult er,Map<String, Object> map) {
	if (er.hasErrors()) {
		List<FieldError> fe = er.getFieldErrors();//Encapsulate all error checks into a list
		for (FieldError f : fe) {
			//getFiled gets the field where the error occurred and getDefaultMessage returns the error message
			System.out.println(f.getField()+"----"+f.getDefaultMessage());
			map.put(f.getField(), f.getDefaultMessage());
		}
	}
	return "register";
}

JSON Data Transmission

  1. The required jar packages are as follows:
  • jackson-core-2.5.0.jar core jar package
  • jackson-annotations-2.5.0.jar Annotation Pack, Providing Annotation Function
  • jackson-databind-2.5.0.jar Data binding packages (optional), providing correlation based on "object binding" and "tree model" API.
  • jackson-core-asl-1.9.7.jar
  • jackson-mapper-asl-1.9.7. jar These two packages are implemented java Objects and json Free conversion between data.
  1. The background sends json format to the page, just using the @ResponseBody annotation.
@RequestMapping("/json")
@ResponseBody   //Return data as json
public User getJson() {
	User  user = new User();
	user.setUserName("Alice");
	user.setAge(18);
	user.setPassword("123456");
	return user;
}
  1. Using ajax to transmit data from the front end to the back end, single data can be received by @RequestParam("name"), multiple data can be received by @RequestBody entity class, or by Map.
@RequestMapping("/login")
@ResponseBody
public String ajax(@RequestBody User user,Model model) {
	System.out.println("username="+user.getUserName());
	if (user.getUserName().equals("This is a budding cat.")) {
		return "true";
	}
	return "false";
}

Tags: Spring JSP xml Java

Posted on Tue, 06 Aug 2019 02:16:50 -0700 by flycast