Spring MVC does not use any annotations to process (jQuery) Ajax requests (based on XML configuration)

Keywords: Java Spring JSON log4j

1. Spring

The spring framework is a lightweight solution, a potential one-stop shop for building enterprise ready applications. Spring framework is a Java platform, which provides comprehensive infrastructure support for Java application development. Spring deals with the infrastructure, so you can focus on the application. Spring enables you to build applications from "plain Java objects" (POJOs) and apply enterprise services non invasively to POJOs. This feature is applicable to the Java SE programming model and all and part of Java EE. However, spring is modular, allowing you to use only those parts you need without having to introduce the rest. You can use the IoC container with any Web framework at the top, but you can also use only Hibernate integration code or JDBC abstraction layer. The spring framework supports declarative transaction management, remote access to logic through RMI or Web services, and various options for persisting data. It provides a full-featured MVC framework and enables you to integrate AOP transparently into your software. Spring is designed to be non intrusive, which means that your domain logic code usually doesn't depend on the framework itself. In your integration layer, such as the data access layer, there will be some dependencies on the data access technology and the spring library. However, it should be easy to isolate these dependencies from the rest of the code base. Spring's two core features: IoC (inversion of control), AOP (aspect oriented programming). IoC function: to give control of objects to container management. AOP function: face-to-face programming (such as log printing), the underlying use of dynamic agent implementation. The spring framework contains functions organized into about 20 modules. These modules are divided into core containers, data access / integration, Web, AOP (aspect oriented programming), detection, messaging and testing. For the whole framework of spring, its design principle is "open to extension, closed to modification" (OOP design principle). Of course, spring has a lot of powerful functions. Let's briefly introduce them here, until now.

2. Spring MVC

Spring MVC is the original web framework based on Servlet API, which has been included in the spring framework since the beginning, and it is seamlessly connected with the spring framework. The full name should be Spring Web MVC, which comes from the module spring webmvc. But usually we call it spring MVC. The spring MVC framework is designed around a dispatcher Servlet (core controller), which distributes requests to various processors, supports configurable processor mapping, view rendering, localization, time zone and theme rendering, and even supports file upload. "Open to extension" is an important design principle of Spring Web MVC framework. Some methods in the Spring Web MVC core class library are defined as final methods. The data binding of Sp'ring MVC is very flexible and convenient, the view analysis is also very flexible and convenient, and provides many powerful annotation mechanisms. Of course, the power of spring MVC can't be achieved in one or two sentences. We should refer to its documents and study in depth. It's better to study the source code. There's not much to say here, until the point.

3. Spring MVC handles (jQuery) Ajax requests (the foreground does not send data, and the background returns normal strings)

Development environment: Eclipse+Tomcat+Spring MVC+Jackson+JSP+jQuery+Ajax

This blog is relatively long. It was originally a small demo. It's not worth writing such a long blog. No, I think it's worth it, because I feel that I can write it (haha! Put on a wave). These are written by the author word by word. Of course, there are some references (I hate copy and paste the most). With my understanding, I have fully practiced the code. I have written them from the beginning to the end, and I have also accumulated my knowledge and improved my experience. Please read the Spring MVC document and Spring document carefully. After reading this, you can't Only master Ajax, realize the benefits of Spring, and be familiar with the execution process of Spring MVC, as well as the interesting log printing. Of course, you can also get the jar package for free (with source code link), Baidu has (basically free). So some ordinary jar packages are free. There is no need to spend some money to live a development package. In essence, the framework is just a template. We can follow the framework's specifications to develop. After all, using some frameworks makes our development simple and efficient. I think it's better to understand the underlying core principles, so that we can quickly make decisions and solve bug s in our development. I'm serious about blogging.

(1) construction environment

Create a new Java Web project in Eclipse and deploy the project to the Tomcat container. Here is the structure of the project:

 

The basic structure of the project is very simple, there is nothing to say. Let's talk about the jar package in lib. Since we want to use Spring MVC for development, we must import its development package. As mentioned above, Spring MVC is actually integrated in Spring, so it is also imported into Spring development package. This time, we use the spring-framework-4.0.0.RELEASE development package.

Spring development package: the package used by spring AOP for aspect oriented programming. Spring aspects provides support for AspectJ (a faceted oriented framework), which includes access to configuration files, creation and management of beans, and all classes related to inversion of control and dependency injection operations. Spring core is the core package (core tool class) of spring. Spring expression is the expression language of spring. Spring JDBC contains all classes encapsulated when spring and JDBC data access. It provides the best implementation using spring JDBC (using jdbc template). Spring ORM is spring's extension of DAO features, supporting some ORM (object relational mapping) frameworks (such as MyBatis, Hibernate, etc.). Spring test provides a simple encapsulation of Junit and other testing frameworks, which makes it easier and faster for us to test spring code. Spring TX package provides consistent declarative programming management for JDBC, Hibernate, JDO, JPA, etc. Spring web contains the core classes needed when spring framework is used in web application development. Spring webmvc contains all classes related to the spring webmvc framework.

log4j log packet. If you don't direct this package, you will report an error.

Jasckson's three packages (I've said it many times in previous blogs). Here is the reason for importing Jackson package. 1. The built-in json and object converter of spring MVC relies on the Jackson class library. (the bottom layer is implemented by encapsulating some of Jackson's methods.). 2. It's simple and easy to use, and the efficiency is OK. Of course, you can also implement your own json to object converter.

The three jar packages of com.springsource are mainly used to provide spring's support for some Apache services. Tomcat is Apache's. If you don't import these three packages, an error will be reported. Of course, here is just a part of the commonly used packages of spring, and others (I'm looking for the spring development package under Baidu). This development also didn't use all of these spring packages, mainly to introduce them. OK, the jar package is finished. Let's develop. The purpose of not using any annotations here is just to configure the implementation based on XML. In fact, our use of annotations will be a lot easier and more convenient (later will be updated). This article is mainly for you to be familiar with the execution process of Spring MVC, and use some of its most original configurations and methods. It's convenient for you to know something deeper, as well as some core things of Spring MVC. Because we use annotation every day, but we don't know the mechanism and principle of annotation. What's the use of annotation. And annotations replace the more complex operations and methods we developed before. Sometimes when we study something, we can't just stay on the surface and use it. If we go deep into the bottom, we will have unexpected gains and understanding.

(2) write jsp file

   

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
            + path + "/";
%>
<!DOCTYPE html>
<html>
<head>
<base href="<%=basePath%>">
<title>I LOVE YOU</title>
<link rel="stylesheet" type="text/css" href="">
<script type="text/javascript" src="index.js"></script>
<script type="text/javascript" src="jquery-3.2.1.min.js"></script>


</head>
<body>


<button id="mybutton1" value="springmvc Handle ajax request" onclick="fun1()" >(jquery)ajax Request (do not send data)</button>
<spand id="show1" />

<br/>
<hr/>

</body>

Quite simply, a button is defined. The < span > tag is used to display the content. The page introduces the customized js file and jQeury's js file (note the name and path).

(3) write js file

/**
 * 
 */
//Use jquery Submission ajax Request (without data)
function fun1(){
    
    $.ajax({
        
        type:"POST",                    //Sending mode
        url:"UserController1",                //Request address
        data:"",                           //Data is empty.
        success:function(data){             //Callback function after success
            
            $("#show1").html(data);            //Page display content
            
        }            
    });
}

Simply, I wrote a fun1() function. Used to respond to buttons. Although it doesn't make much sense to discuss whether the client doesn't send data, let's discuss it here. When we study java fundamentals, we often talk about "empty". Isn't it? This is mainly to familiarize ourselves with the process of code execution. After all, the process of our study is from shallow to deep. Talk less.

(4) write controller class

package com.controller;

import java.io.IOException;

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

import org.springframework.web.HttpRequestHandler;

public class UserController1 implements HttpRequestHandler{


    @Override
    public void handleRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // TODO Auto-generated method stub
        response.setCharacterEncoding("UTF-8");    
        String str = "I am a springmvc";        
        try {
            response.getWriter().print(str);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }    
    }    
}

Here, a controller class is defined, and the HttpRequestHandler interface is implemented, and the abstract methods in the interface are implemented. Method, a string is defined, and the response is used to get the print stream for output. In Spring MVC. In general, when we write a controller (that is, a handler, which is used to process the client's requests), it should be recognized by Spring MVC as a controller class, because there is no annotation here. So we have two ways.

The first is to write a controller class, implement the org.springframework.web.servlet.mvc.Controller interface, and then give it to the core controller to call the corresponding processor adapter for processing. However, to implement the controller, the abstract method public abstract ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) must be implemented. This method must return a ModelAndView object, and what we do is to process string data and json data. So we don't choose to implement the controller interface here.
The second is to write the controller class, implement the org.springframework.web.HttpRequestHandler interface, and then give it to the core controller to call the corresponding processor adapter for processing, and implement the abstract methods. I can Baidu the execution process of Spring MVC, not much here.

public abstract void handleRequest(HttpServletRequest request, HttpServletResponse response) we notice that this method has no return value, so it is convenient for us to process string data and json data. Notice that there are two parameters, request and response (this is the Servlet thing). Supported parameter types supported by Spring MVC:

HttpServletRequest object, HttpServletResponse object, HttpSession object, Model/ModelMap object. Here we use two of them.

(5) configure web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>MySpringMVCAjax</display-name>
  <welcome-file-list> 
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  
  
  
  <!-- To configure springmvc Core 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:springmvc.xml</param-value>
      </init-param>    
        
  </servlet>
  
  <servlet-mapping>
      <servlet-name>springmvc</servlet-name>
      <url-pattern>/</url-pattern>
      
  </servlet-mapping>
  
  
  <!-- Release static resources -->
  <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>/static/*</url-pattern>
    </servlet-mapping>

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

    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>*.css</url-pattern>
    </servlet-mapping>
  
  
  
  
  <!-- Configure encoding filter -->
  
 <filter>
      <filter-name>SpringCharacterEncodingFilter</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> 
       
       <init-param>
      <param-name>forceEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>
  
  <filter-mapping>         
      <filter-name>SpringCharacterEncodingFilter</filter-name>
      <url-pattern>/*</url-pattern>
  </filter-mapping>  
  
</web-app>

Here we have three things.

First, configure the spring core controller. Spring MVC core controller (front-end controller or central processor) org.springframework.web.servlet.DispatcherServlet, DispatcherServlet is actually a Servlet (it inherits from the HttpServlet base class), which also needs to be declared under the web.xml configuration file of your web application. You need to map the request you want the dispatcher Servlet to handle to the corresponding URL in the web.xml file. This is the standard Java EE Servlet configuration. DispatcherServlet is a central processor of spring MVC, which is responsible for scheduling processor mapper, processor adapter and view parser. Configure initialization parameters to load spring mvc.xml, the main configuration file of spring MVC. Here we put it in src directory.

Second, release static resources. Pay attention here. What we configured under the < url pattern > tag of the core controller is /, which means that all the visited URLs are handed over to the core controller for processing, which may result in the failure to load the static resource file (js,css,img). terms of settlement:

The first one is to configure < MVC: default servlet handler / > < in the springmvc.xml file, which means to release all static resources

 

 

The second is to release static resources, as shown in our web.xml. Of course, it can also be released in the spring.xml file. The syntax is:

<resources location="/js/" mapping="/js/**" />
<resources location="/css/" mapping="/css/**" />
<resources location="/images/" mapping="/images/**" />

Here, we use web.xml to release static resources, mainly because this method is easy to understand. Later, I will update and upgrade the blog content, and then take a more advanced approach.

Third, when configuring the core controller, just set the < URL pattern > tag to *. do or. action. URLs that end in. do or. action are parsed by the front-end controller dispatcher servlet. This method can also be used, but when you visit the path, you need to add this suffix. It doesn't look very comfortable (people with a little obsessive-compulsive disorder should understand it). Of course, I don't think so. The author just takes some simple but not efficient methods.

The third is to configure spring to provide encoding filters. The encoding filter configured by web.xml uses the encoding filter provided by spring to uniformly encode in order to prevent the Chinese data from being garbled. Configured as UTF-8. Of course, other codes such as GBK can also be used. GBK coding is based on China's national conditions and has poor compatibility in the world, which is why most web pages use UTF-8 coding instead of GBK. UTF-8 benefits: compatible with ASCII, English files are stored in single byte, the file is small. In eclipse, the encoding of the project is also set to UTF-8, and the character encoding in JSP page is also set to UTF-8. The browser web page character encoding is also set to UTF-8. Anyway, it's what UTF-8 looks like. To do so much is mainly to unify the coding and solve the problem of Chinese disorder. Because in the past, when using servlet and struts 2, there was often a Chinese confusion, which made people confused. So. The coding filter provided by spring is more convenient and easy to use. So spring is a magic thing. Let's look at the Spring source code and look at the documentation developed by Spring. We can learn some essence. The coding filter provided by spring, org.springframework.web.filter.CharacterEncodingFilter class, pay attention to write the path correctly. The initialization parameter (that is, encoding) encoding is UTF-8. The character filter in spring, CharacterEncodingFilter, is for requests. forceEncoding=true means that no matter whether the client request contains encoding or not, the encoding in the filter is used to parse the request. forceEncoding defaults to false. The effect of forceEncoding is true: request.setCharacterEncoding("UTF-8"); the effect of forceEncoding is false:

 request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"). The / * configured by the < URL pattern > tag filters all requests, setting the encoding to UTF-8. Okay. This concludes web.xml. In fact, sometimes we just develop a simple demo, which looks very simple. But we need to understand how the underlying is implemented. For example, Java bottom layer, JVM(Java virtual machine) written in c/c + +, Java class library written in Java language. For example, native local methods are also written in c/c + +, and Java just calls its interface. This also explains why native methods are generally more efficient. So the question is, what's the c language written with? This can be Google or Baidu, not much here. Of course, we must also be familiar with the implementation process of a project or work. This development seems very simple, but we will explain the knowledge content involved in detail for you, and it is written by myself after careful practice word by word. Of course, I am also a rookie. Limited knowledge. But we can learn more knowledge and improve our ability to reach the peak of life. Not much (off topic, ha ha!).

(6) configure the springmvc.xml 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"  
      xmlns:mvc="http://www.springframework.org/schema/mvc"  
      xmlns:context="http://www.springframework.org/schema/context"  
      xsi:schemaLocation="  
      http://www.springframework.org/schema/beans 
      http://www.springframework.org/schema/beans/spring-beans.xsd
      http://www.springframework.org/schema/mvc 
      http://www.springframework.org/schema/mvc/spring-mvc.xsd  
      http://www.springframework.org/schema/context 
      http://www.springframework.org/schema/context/spring-context.xsd">
      
    
    
    <!-- To configure user Entity class -->
    
    <bean id="user" class="com.pojo.User" />
    
    
    <!-- To configure handler-->
    <bean name="/UserController1" class="com.controller.UserController1" /> 
    <bean name="/UserController2" class="com.controller.UserController2" /> 
    <bean name="/UserController3" class="com.controller.UserController3" />  
    
    <!-- Configure processor mapper -->
    
    <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
        
     <!-- Configure processor adapter -->   
     <bean class="org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter"/> 
         
     
     <!-- To configure json Converter with object -->
     
     <bean id="myconverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
              
     <!-- Configure view resolver -->   
     
      <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
          
         <property name="prefix" value="/"></property>
      
        <property name="suffix" value=".jsp"></property>
          
      </bean>

</beans>

springmvc.xml is the main configuration file of this development. Through observation, the top-level tag < beans > contains many bean modules. Spring beans are actually Java objects that are instantiated, assembled, and managed by spring containers. A bean is equivalent to an entity class object. Through IoC (inversion of control, also called dependency injection), we can inject beans into the container and give them to spring container management (such as bean instantiation). The purpose of this is to decouple. Because the principle of software design is high cohesion and low coupling. Spring's default bean instance is Singleton. We can use the scope property to set the scope of the bean. Scope can accept Singleton (single instance mode, only one instance can be obtained each time), prototype (prototype mode, new instances will be generated each time the bean is obtained), request (different bean instances will be generated each time the HTTP request request), session (different bean instances will be generated each time the HTTP session request), global session (each global HTTP session corresponds to one bean Example. Only valid when the portlet Context. 5 values. We often use the Singleton mode, because the cost of creating the object itself is relatively high, which consumes resources, and the Singleton itself meets our needs. Of course, we can also set different scopes according to different needs, which is not to blame. Also, notice the XSD file introduced. The XSD file referenced in the spring file is used to verify the format of the XML file. Spring loads XSD files to validate XML files by default at startup. This constrains the file. Here we introduce three XSD files, spring beans XSD, which contains the interpretation of beans. Spring-mvc.xsd contains the explanation of < MVC > and other tags, spring-context.xsd contains the explanation of context, here we only use the spring-beans.xsd constraint file.

Let's see what's configured.

1. Inject the User entity class into the container (the code of User class will be pasted below, which is not used yet). So we can assemble a User class through the < bean > tag, and we can get the User entity object by getting the bean. Set the bean ID (the unique ID of a bean) and class (the full package path package. Class of the class).

2. Configure the controller (i.e. handler) to handle client requests. Here we have three controllers configured. Let's look at the configuration of UserController1 (corresponding to the above method UserController1). A name and class are configured. Spring MVC needs to identify the url of the request by calling the processor mapper to get the name of the name, find the controller class, and then give it to the processor configurator to handle the controller. Equivalent to mapping path. Note that / 'should be added before the name, otherwise it cannot be recognized. Here we set the name = "/ UserController1" to be consistent with the class name (for convenience). Of course, we can also use other names. Don't forget /, the url submitted by the foreground should be consistent with the name here. Class is the full package class path of UserController1.

3. Configure processor mapper BeanNameUrlHandlerMapping. You do not need to specify an id, just configure the full class path, that is, class. This processor mapper looks up the bean name as the url. You need to specify the bean name (url) when configuring the Handler.

View the DispatcherServlet.properties resource file under the spring webmvc package:

# Default implementation classes for DispatcherServlet's strategy interfaces.
# Used as fallback when no matching beans are found in the DispatcherServlet context.
# Not meant to be customized by application developers.

org.springframework.web.servlet.LocaleResolver=org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver

org.springframework.web.servlet.ThemeResolver=org.springframework.web.servlet.theme.FixedThemeResolver

org.springframework.web.servlet.HandlerMapping=org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping,\
    org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping

org.springframework.web.servlet.HandlerAdapter=org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter,\
    org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter,\
    org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter

org.springframework.web.servlet.HandlerExceptionResolver=org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerExceptionResolver,\
    org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolver,\
    org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver

org.springframework.web.servlet.RequestToViewNameTranslator=org.springframework.web.servlet.view.DefaultRequestToViewNameTranslator

org.springframework.web.servlet.ViewResolver=org.springframework.web.servlet.view.InternalResourceViewResolver
 org.springframework.web.servlet.FlashMapManager=org.springframework.web.servlet.support.SessionFlashMapManager
There are two common Spring MVC processor mappers, one is org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping, which inherits
AbstractDetectingUrlHandlerMapping abstract class, which inherits AbstractUrlHandlerMapping abstract class upwards, and AbstractHandlerMapping upwards,
The AbstractHandlerMapping abstract class implements the HandlerMapping interface.

The other is org.springframework.web.servlet.handler.simpleurhandlermapping, which inherits the abstract class AbstractUrlHandlerMapping,
AbstractUrlHandlerMapping inherits AbstractHandlerMapping abstract class, and implements org.springframework.web.servlet.HandlerMapping
Interface. Observing the resource file, we find that BeanNameUrlHandlerMapping is the default processor mapper of Spring MVC, which we will use here. To use SimpleUrlHandlerMapping,
We can do it according to its grammar. It can be configured as follows:
bean id="UserController1" class="com.controller.UserController1" />

<!-- simple URL Configure processor mapper -->
<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
    <property name="mappings">
        <props>
            <prop key="/UserController1">UserController1</prop>
        </props>
    </property>
</bean>

Of course, these two processor mapper configurations can coexist, and the core controller will correctly determine which Handler to use for url processing.

Note that the processor mapper of the resource file above, defaultannotation handler mapping, has been discarded by checking the source code. It's hard to feel abandoned.

It is estimated that the heart of DefaultAnnotationHandlerMapping is broken.

4. Configure the processor adapter. No need to specify id, class is the full class path. The core Controller calls the processor mapper to find the Controller class, so who will handle the Controller. Then the processor adapter will flash. What is a processor adapter. And listen to the next chapter... (leather) By observing the above resource files. We found out. Spring MVC processor adapter, commonly used 2.

One is org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter, the other is org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter

Both classes implement the HandlerAdapter interface. The Handler handled by the SimpleControllerHandlerAdapter must implement the coreoller interface, which generally returns a ModelAndView object.

The Handler processed by httprequesthanderadapter must implement HttpRequestHandler interface, which is generally used to process string or json data. Because its abstract method does not return a value. AnnotationMethodHandlerAdapter has been abandoned. Don't talk about it. Of course, the two adapters can coexist, and different mappers can be configured to find different controller s.

The default processor adapter for Spring MVC is HttpRequestHandlerAdapter.

5. Configure the View parser. No need to specify id, class is the full class path. We use the InternalResourceViewResolver here. Configure its class path. Note that there are two properties. Prefix indicates the prefix of the returned View page, and suffix indicates the suffix of the returned View page. For example, when we want to return a page index.jsp after View parsing, prefix is equivalent to configuring its root directory (where is it), and suffix is. JSP. In this way, when we use annotations for development, we only need to return a String "index". As configured above, it means that you only need to return the JSP file name under the WebContent root directory in the Handler (for simplicity and convenience, development is more efficient). The View parser is responsible for mapping a String representing the logical View name to the actual View type View. Found through the above resource file. Note the HandlerExceptionResolver Handler exception resolver. It is responsible for mapping the captured exceptions to different views, in addition to supporting more complex exception handling code. There are three View parsers for Spring MVC:

First, use the ViewResolver interface to resolve views

The org.springframework.web.servlet.view.InternalResourceViewResolver class implements the org.springframework.web.servlet.ViewResolver interface through continuous upward inheritance. In practical application, internal resource view resolver is also the most widely used view resolver. This view parser is used in this development. This is more commonly used. The internal resource view resolver parser can be interpreted as an internal resource view resolver. InternalResourceViewResolver will resolve the returned view names to InternalResourceView objects, InternalResourceView will store the model properties returned by the Controller processor method in the corresponding request properties, and then redirect the request forword to the target URL through RequestDispatcher on the server side.

 

Method in interface: parses the View through the passed parameter and returns a View object. Note that when the Handler class implements the Conteoller interface method, it returns a ModelAndView object. ModelAndView is an underlying object of spring MVC framework, including Model and View.

 

public abstract interface ViewResolver
{
public abstract View resolveViewName(String paramString, Locale paramLocale)
throws Exception;
}

 

Second, use the RequestToViewNameTranslator interface to resolve views. DefaultRequestToViewNameTranslator is the implementation subclass of this interface.

This interface defines an abstract method

public abstract interface RequestToViewNameTranslator
{
public abstract String getViewName(HttpServletRequest paramHttpServletRequest)
throws Exception;
}

A string representing the name of a view returned according to the request.

Third, use the FlashMapManager interface to parse views. SessionFlashMapManager is the implementation subclass of this interface.

 

FlashMap manager. It can store and retrieve FlashMap objects between requests. The latter can be used to pass data between requests, usually in the context of request redirection.

This interface definition method: just look at it for yourself. I won't introduce it too much here.

public abstract interface FlashMapManager
{
public abstract FlashMap retrieveAndUpdate(HttpServletRequest paramHttpServletRequest, HttpServletResponse paramHttpServletResponse);

public abstract void saveOutputFlashMap(FlashMap paramFlashMap, HttpServletRequest paramHttpServletRequest, HttpServletResponse paramHttpServletResponse);
}

Map is used to save data when it is certain. RedirectView jumps on the page, and data saving depends on FlashMap and FlashMapManger. FlashMapManger is filled in during container initialization, and FlashMap can be obtained from Manger.

5. Configure the converter between json and object. It's not available here for the time being. It will be explained below. Skip first. In fact, the underlying layer of the built-in json object converter of Spring MVC is implemented with the Jasckson class library.

(7) configure log4j.properties log file

   

### set log levels ###
log4j.rootLogger = INFO , console , D
 
### console ###  
log4j.appender.console = org.apache.log4j.ConsoleAppender  
log4j.appender.console.Target = System.out  
log4j.appender.console.layout = org.apache.log4j.PatternLayout  
log4j.appender.console.layout.ConversionPattern = %-d{yyyy-MM-dd HH\:mm\:ss} [%p]-[%c] %m%n  
 
 
### log file ###  
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File =../logs/IvaDubboWeb-info.log
log4j.appender.D.Append = true
log4j.appender.D.Threshold = INFO 
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern = [%p] [%-d{yyyy-MM-dd HH:mm:ss}] %C.%M(%L) | %m%n


### out zhiding log file ###
log4j.logger.haha = INFO, haha
log4j.additivity.haha = false
log4j.appender.haha = org.apache.log4j.DailyRollingFileAppender
log4j.appender.haha.File =D:/logs/mylog.log
log4j.appender.haha.Append = true
log4j.appender.haha.Threshold = INFO
log4j.appender.haha.layout = org.apache.log4j.PatternLayout
log4j.appender.haha.layout.ConversionPattern = [%p] [%-d{yyyy-MM-dd HH:mm:ss}] %C.%M(%L) | %m%n

Log4j brief introduction:

Log4j is an open source project of Apache. By using log4j, we can control that the destination of log information transportation is console, file, GUI component, even a set of interface server, NT event recorder, UNIX Syslog daemons, etc.; we can also control the output format of each log; by defining the level of each log information, we can be more detailed To control the log generation process. Log4j has three main components: loggers, Appenders, and layouts. Here it can be simply understood as the log category, the place where the log is to be output and the form in which the log is to be output. The combination of these three components makes it easy to record the type and level of information and control the style and location of log output at run time.

1. Configure the root logger with the log output level of INFO. Output level of log4j: trace < debug < INFO < warn < error < fat. Higher than INFO level will also print output, lower than INFO will not output.

2. Configure the console to print the log information on the eclipse console.

3. Configure output to file. One is to export to a general file, the other is to export to the file we specified. It's simple. (I have been pondering over log4j for a long time, mainly to understand what is log printing in the end.).

Simply test the log4j above (note to import the log4j development package and unit test juninit package, and put the log4j.properties file in the src directory). Print to console:

package com.log4j;

import org.apache.log4j.Logger;
import org.junit.Test;

public class Log4jTest {

    @Test
    public void test() {

        // BasicConfigurator.configure(); //Automatically and quickly use the default Log4j Environmental Science.

        Logger logger = Logger.getLogger(Log4jTest.class);
        logger.info("log4j");
        logger.info("yes");
        logger.error("What");
        logger.debug("What about");

    }

    
}

Running effect: debug level is lower than INFO, no output.

Print the log to the specified file: just put the method in a class

@Test
    public void test1() {

        // BasicConfigurator.configure(); //Automatically and quickly use the default Log4j Environmental Science.

        Logger logger = Logger.getLogger("haha");
        logger.info("I");
        logger.info("want");
        logger.info("learn");
        logger.info("java");
        logger.info("Ha");
        logger.info("Ha");
    }

Operation effect:

 

(8) operation procedure

Start the Tomcat server and type: localhost/MySpringAjax /, in the browser address bar

Perfect operation without too much explanation.

 

4. Spring MVC processes (jQuery) Ajax requests (sending key/value data in the foreground and returning json data in the background)

(1) write jsp page

Repeat the steps and we'll take them with us. For example, the jar package has been exported, and the log4j.properties file and the springmvc.xml main configuration file are public to the project. There's not much to say here.

 

<button id="mybutton2" value="springmvc Handle ajax request" onclick="fun2()" >Send data in the format key/value ( jquery)ajax request</button>
<spand id="show2" />

 

(2) write js page

 

//Use jquery Submission key/value Data ( ajax Request)

function fun2(){
    
    $.ajax({
        
        type:"POST",
        url:"UserController2",
        data:"username=wly&password=1314520",        //key/value data
        success:function(data){
            
            $("#show2").html(data.username+" "+data.password);
            
        }            
    });

}

 

(3) write User class

package com.pojo;

public class User {

    private String username;

    private String password;
    

    private Integer age;
    
    

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

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

    @Override
    public String toString() {
        return "User [username=" + username + ", password=" + password + ", age=" + age + "]";
    }    
}

Here we add an age attribute to the User class. The foreground will send username and password. (the main purpose of adding the age attribute is to perform some operations on the User class again, which is convenient for us to demonstrate different effects.).

(4) configure the web.xml file

It has been configured. There are three things. 1. Spring MVC core controller; 2. Release static resources; 3. Configure the coding filter provided by spring MVC

(5) configure the springmvc.xml file

The above has been configured. The beans to be configured include User entity class, Controller class, processor mapper, processor adapter, view parser, json object converter (this development calls the built-in json object converter of Spring MVC for json data and object conversion). Configure the id (uniquely identifying the bean) and class (full package class path) of the json and object converter.

 

 <!-- To configure json Converter with object -->
     
     <bean id="myconverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>

 

 

 

Here we take a look at the configured Spring MVC built-in json object converter. Here we use the MappingJackson2HttpMessageConverter class. Let's first introduce two common message converters of Spring MVC.

1. org.springframework.http.converter.json.MappingJackson2HttpMessageConverter message converter class inherits the abstracthttpmessageconverter < T > abstract class, which implements the package org.springframework.http.converter.httpmessageconverter < T > interface. Let's take a look at the abstract methods of this interface.

 

package org.springframework.http.converter;

import java.io.IOException;
import java.util.List;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;

public abstract interface HttpMessageConverter<T>
{
  public abstract boolean canRead(Class<?> paramClass, MediaType paramMediaType);
  
  public abstract boolean canWrite(Class<?> paramClass, MediaType paramMediaType);
  
  public abstract List<MediaType> getSupportedMediaTypes();
  
  public abstract T read(Class<? extends T> paramClass, HttpInputMessage paramHttpInputMessage)
    throws IOException, HttpMessageNotReadableException;
  
  public abstract void write(T paramT, MediaType paramMediaType, HttpOutputMessage paramHttpOutputMessage)
    throws IOException, HttpMessageNotWritableException;
}

/* Location:           F:\eclipseWorkspace\myworkspace\MySpringMVCAjax\WebContent\WEB-INF\lib\spring-web-4.0.0.RELEASE.jar
 * Qualified Name:     org.springframework.http.converter.HttpMessageConverter
 * Java Class Version: 6 (50.0)
 * JD-Core Version:    0.7.0.1
 */

 

Generally speaking, we should implement the httpmessageconverter < T > interface when implementing the custom json and Object Converter in Spring MVC. MediaType is called content type in the message header of the network protocol. It uses two parts of identifiers to determine a type. When we use it, we really want to indicate what type of things we are passing. The MediaType class is a media type. It defines many static constants and the data format. Equivalent to ContentType. Static constant values include application/json, text/html, image/png, application/xml, etc. There are many. Go to see the source code yourself. canRead() method indicates whether the test can convert java objects to json data, and canWrite indicates whether the test can convert json data to java objects. The read () method is used to read, which means to convert json data to java objects, the write method to write, and the java objects to json data output. Mappingjackson 2httpmessageconverter is an implementation subclass of httpmessageconverter < T >. First, let's look at two important abstract methods defined by abstracthttpmessageconverter < T >. Implement the read() and write() abstract methods in the httpmessageconverter < T > interface. However, the two abstract methods defined in this class are called. Then give the driver class to implement these two methods.

 

/*     */   public final T read(Class<? extends T> clazz, HttpInputMessage inputMessage)
/*     */     throws IOException
/*     */   {
/* 158 */     return readInternal(clazz, inputMessage);
/*     */   }
/*     */   
/*     */ 
/*     */ 
/*     */ 
/*     */ 
/*     */ 
/*     */ 
/*     */   public final void write(final T t, MediaType contentType, HttpOutputMessage outputMessage)
/*     */     throws IOException, HttpMessageNotWritableException
/*     */   {
/* 170 */     final HttpHeaders headers = outputMessage.getHeaders();
/* 171 */     if (headers.getContentType() == null) {
/* 172 */       if ((contentType == null) || (contentType.isWildcardType()) || (contentType.isWildcardSubtype())) {
/* 173 */         contentType = getDefaultContentType(t);
/*     */       }
/* 175 */       if (contentType != null) {
/* 176 */         headers.setContentType(contentType);
/*     */       }
/*     */     }
/* 179 */     if (headers.getContentLength() == -1L) {
/* 180 */       Long contentLength = getContentLength(t, headers.getContentType());
/* 181 */       if (contentLength != null) {
/* 182 */         headers.setContentLength(contentLength.longValue());
/*     */       }
/*     */     }
/* 185 */     if ((outputMessage instanceof StreamingHttpOutputMessage)) {
/* 186 */       StreamingHttpOutputMessage streamingOutputMessage = (StreamingHttpOutputMessage)outputMessage;
/*     */       
/*     */ 
/* 189 */       streamingOutputMessage.setBody(new StreamingHttpOutputMessage.Body()
/*     */       {
/*     */         public void writeTo(final OutputStream outputStream) throws IOException {
/* 192 */           AbstractHttpMessageConverter.this.writeInternal(t, new HttpOutputMessage()
/*     */           {
/*     */             public OutputStream getBody() throws IOException {
/* 195 */               return outputStream;
/*     */             }
/*     */             
/*     */             public HttpHeaders getHeaders()
/*     */             {
/* 200 */               return AbstractHttpMessageConverter.1.this.val$headers;
/*     */             }
/*     */           });
/*     */         }
/*     */       });
/*     */     }
/*     */     else {
/* 207 */       writeInternal(t, outputMessage);
/* 208 */       outputMessage.getBody().flush();
/*     */     }
/*     */   }
/*     */   
/*     */ 

/*     */   protected abstract T readInternal(Class<? extends T> paramClass, HttpInputMessage paramHttpInputMessage)
/*     */     throws IOException, HttpMessageNotReadableException;
/*     */   
/*     */   protected abstract void writeInternal(T paramT, HttpOutputMessage paramHttpOutputMessage)
/*     */     throws IOException, HttpMessageNotWritableException;
/*     */ }

 

Next, MappingJackson2HttpMessageConverter appears, which implements the methods of readInternal() and writeInternal defined by the abstract class. It is found through observation. The readInternal() method calls the readValue() method of ObjectMapper(Jackson core operation class), which means to convert json strings into java objects. The read() method is actually a method of this class extension, which has the same function as readInternal. The writeInternal() method calls the writeValue() method of ObjectMapper(Jackson core operation class), which means to convert java objects into json strings.

HttpInputMessage, a public interface, extends HttpMessage to represent HTTP input message, which is composed of header and readable body. It is usually implemented by a server-side HTTP request handle or a client-side HTTP response handle. The implementation subclass ServletServerHttpRequest encapsulates the request header and request body.

The public interface HttpOutputMessage, which extends HttpMessage to represent HTTP output message, is composed of header and writable body. It is usually implemented by the client's HTTP request handle or the server's HTTP response handle. Its implementation subclass, ServletServerHttpResponse, is equivalent to encapsulating the response header and response body.

 

/*     */   protected Object readInternal(Class<?> clazz, HttpInputMessage inputMessage)
/*     */     throws IOException, HttpMessageNotReadableException
/*     */   {
/* 168 */     JavaType javaType = getJavaType(clazz, null);
/* 169 */     return readJavaType(javaType, inputMessage);
/*     */   }
/*     */   
/*     */ 
/*     */   public Object read(Type type, Class<?> contextClass, HttpInputMessage inputMessage)
/*     */     throws IOException, HttpMessageNotReadableException
/*     */   {
/* 176 */     JavaType javaType = getJavaType(type, contextClass);
/* 177 */     return readJavaType(javaType, inputMessage);
/*     */   }
/*     */   
/*     */   private Object readJavaType(JavaType javaType, HttpInputMessage inputMessage) {
/*     */     try {
/* 182 */       return this.objectMapper.readValue(inputMessage.getBody(), javaType);
/*     */     }
/*     */     catch (IOException ex) {
/* 185 */       throw new HttpMessageNotReadableException("Could not read JSON: " + ex.getMessage(), ex);
/*     */     }
/*     */   }
/*     */   
/*     */ 
/*     */   protected void writeInternal(Object object, HttpOutputMessage outputMessage)
/*     */     throws IOException, HttpMessageNotWritableException
/*     */   {
/* 193 */     JsonEncoding encoding = getJsonEncoding(outputMessage.getHeaders().getContentType());
/*     */     
/*     */ 
/*     */ 
/*     */ 
/* 198 */     JsonGenerator jsonGenerator = this.objectMapper.getJsonFactory().createJsonGenerator(outputMessage.getBody(), encoding);
/*     */     
/*     */ 
/*     */ 
/* 202 */     if (this.objectMapper.isEnabled(SerializationFeature.INDENT_OUTPUT)) {
/* 203 */       jsonGenerator.useDefaultPrettyPrinter();
/*     */     }
/*     */     try
/*     */     {
/* 207 */       if (this.jsonPrefix != null) {
/* 208 */         jsonGenerator.writeRaw(this.jsonPrefix);
/*     */       }
/* 210 */       this.objectMapper.writeValue(jsonGenerator, object);
/*     */     }
/*     */     catch (JsonProcessingException ex) {
/* 213 */       throw new HttpMessageNotWritableException("Could not write JSON: " + ex.getMessage(), ex);
/*     */     }
/*     */   }
/*     */   

2. org.springframework.http.converter.StringHttpMessageConverter class inherits abstracthttpmessageconverter < string > abstract class, which implements httpmessageconverter < T > interface. Mainly used to read and write strings. In fact, it is a message converter. By default, the converter supports all media types (* / *) and writes content type text/plain. You can override this by setting the supportedMediaTypes property. Principle: read and write through input and output streams.

Design philosophy: the philosophy of StringHttpMessageConverter is: what kind of data do you want, I will send it to you.

In fact, it's very simple. For example, the data type I want to accept is Accept: application/json;charset=UTF-8, and the data type sent is content type: application / JSON; charset = UTF-8, which should also be consistent. Equivalent to what format the string is input, it can be converted into the corresponding format. For more information, please refer to the specific source code.

 

 

 

(6) configure and write Controller class

 

package com.controller;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.web.HttpRequestHandler;

import com.pojo.User;


public class UserController2 implements HttpRequestHandler{

    public void handleRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // TODO Auto-generated method stub
        response.setCharacterEncoding("UTF-8");
        
        //Load spring.xml File initialization ApplicationContext
        ApplicationContext ac = new ClassPathXmlApplicationContext("springmvc.xml");
        //obtain User Class, as you can see IoC(Give objects to container management mechanism (factory mode)+Java Reflection mechanism)
        User user = (User) ac.getBean("user");
        //Obtain username and password,Manual encapsulation
        String username=request.getParameter("username");
        String password=request.getParameter("password");    
        user.setUsername(username);
        user.setPassword(password);    
        //Get message converter MappingJackson2HttpMessageConverter Class object, implemented HttpMessageConverter Interface
        HttpMessageConverter converter= (HttpMessageConverter) ac.getBean("myconverter");        
        //Get media type, passed in is"application/json;charset=UTF-8"Here we are directly new
        MediaType mediaType=new MediaType(MediaType.APPLICATION_JSON, null);        
        //Instantiate the response information class. ServletServerHttpResponse yes HttpOutputMessage Implementation subclass of
        //Directly here new,If you configure to springmvc The configuration file is redundant.
        HttpOutputMessage out=new ServletServerHttpResponse(response);            
        converter.write(user, mediaType, out);
    }
}

 

First, we need to get two beans, one is the configured converter, the other is the user class object. Initialize an application context ApplicationContext object of Spring by loading spring.xml, and call the method getBean("id"). We can get the bean object, which is actually done through the Java reflection mechanism. The id passed in is the id configured in our spring.xml. Be sure to keep it consistent. There are other ways to get Spring Bean. You can baidu yourself. After getting the user object, encapsulate it manually. The code is annotated and easy to understand. MediaType. Application? json is a static constant. The static constant defined in the MediaType class (there are many more, here is just one) public static final MediaType application [json = valueof ("application / json"). HttpOutputMessage encapsulates the output information. Finally, through the write () method of the message converter, the object is converted to json data for output and response to the client.

ApplicationContext is a central interface that provides configuration for applications. It is read-only when the application is running, but it can be reloaded if the implementation supports it.

ApplicationContext provides:

1. Bean factory method for accessing application components. Inherited from ListableBeanFactory.

2. The ability to load file resources in a common way. Inherited from ResourceLoader interface.

3. The ability to publish events to registered listeners. Inherited from the ApplicationEventPublisher interface.

4. The ability to solve messages and support internationalization. Inherited from the MessageSource interface.

5. Inherit from parent context. Definitions in the context of descendants will always take precedence. For example, this means that the entire Web application can use a single parent context, and each servlet has its own child context, which is independent of any other servlet's child context.

There is a problem: in fact, the user class object here finally passes the Spring container new instance (reflection). Without any annotation, how can the user class automatically encapsulate the key/value type data and how can we get the user class. There is a way of thinking (to understand the parameter binding mechanism of spring mvc, we need to study the source code again). I don't know what else we can do. Welcome to exchange.

 

(7) operation procedure

 

5. Spring MVC processes (jQuery) Ajax requests (the foreground sends json data and the background returns json data)

(1) write jsp page

<button id="mybutton3" value="springmvc Handle ajax request" onclick="fun3()" >Send data in the format json Of(jquery)ajax request</button>
<spand id="show3" /><br/>

 

(2) write js file

//Use jquery Submission json Data ( ajax Request)

function fun3(){
    
    var user={                        //accord with json Data format standard javascript object
            "username":"Who am I?",
            "password":"1314520"    
    };    
$.ajax({
        
        type:"POST",
        url:"UserController3",
        contentType:"application/json;charset=UTF-8", //Content type used when sending data to the server
        data:JSON.stringify(user),    //take javascript Object to json Character string
        
        //The data type of the expected server response. Server return json Character string. jquery Will automatically handle json Translate into js object
        dataType:"json",    //Equivalent to calling JSON.parse(data)Method. At this time, we can save it.      
        success:function(data){
            
            $("#show3").html(data.username+" "+data.password+" "+data.age);
            
        }            
    });
}

When printing information, we added an age attribute to note. Here, username is set to Chinese, mainly to test whether there will be garbled code (see if the encoding filter configured by web.xml is effective).

(3) write User class

The User entity class is the same as above. There are three properties, username,password,age. Provide getters and setters methods, toString methods.

(4) configure web.xml

Same

(5) configure the springmvc.xml file

Empathy

(6) write Controller class

package com.controller;

import java.io.IOException;

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

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.HttpRequestHandler;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.pojo.User;


public class UserController3 implements HttpRequestHandler{


    @Override
    public void handleRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // TODO Auto-generated method stub
        response.setCharacterEncoding("UTF-8");
        ////Load spring.xml File initialization ApplicationContext
        ApplicationContext ac = new ClassPathXmlApplicationContext("springmvc.xml");
        ////Get message converter MappingJackson2HttpMessageConverter Class object, implemented HttpMessageConverter Interface
        HttpMessageConverter converter=(HttpMessageConverter) ac.getBean("myconverter");        
        ////Get media type, passed in is"application/json;charset=UTF-8"Here we are directly new object
        MediaType mediaType=new MediaType(MediaType.APPLICATION_JSON, null);        
        //Request information class, encapsulating input information
        HttpInputMessage in=new ServletServerHttpRequest(request);        
        //Response information class, encapsulating output information
        HttpOutputMessage out=new ServletServerHttpResponse(response);                            
        //Send it from the front desk json Data to User Object ( read Accepted parameters: Here you can json Data to User,Benefit from HttpInputMessage The requested information has been encapsulated, including the request header and the request body)
        User user= (User) converter.read(User.class, in);
        //Age setting
        user.setAge(666);
        
        System.out.println(user);
        //hold User Object to json data output
        converter.write(user, mediaType, out);    
    }
}

The code is annotated. It's simple. The write() method of the message converter object reads the json data sent by the client, and converts the json data into a user class object. Why do you want to convert it? (it is convenient for our code to operate and maintain. For example, when we log in, we need to check the database to see whether the user exists or not and set other properties, such as age. So there is a certain demand. java language is an object-oriented programming language, which is sure to operate java objects conveniently and quickly.

(7) run the program

Perfect operation, no random code, OK, end of work. Printed out the contents of username, password, age.

6. Understand the execution process of Spring MVC

(1) the user sends the request to the Spring MVC core controller (dispatcher servlet).

(2) the front-end Controller requests HandlerMapping to find the Controller, which can be found according to the xml configuration and annotation.

(3) after the processor mapper HandlerMapping lookup is completed, it returns the Controller to the core Controller.

(4) the front-end Controller calls the processor adapter to execute the Controller.

(5) the processor adapter executes the Controller.

(6) the Controller returns the ModelAndView object to the adapter after execution.

(7) the processor adapter returns ModelAndView to the front controller. ModelAndView is an underlying object of spring MVC framework, including Model and View.

(8) the front-end controller requests to try to parse the view by using the parser to parse the real view according to the logical view name.

(9) the view parser returns the view to the front controller.

(10) the core controller renders the view. It is to fill the model data (in the ModelAndView object) into the request field

(11) the core controller responds to the user.

 

7. summary

(1) guide package. There will be errors before log4j log package. Spring framework supports log4j log output. Packages that support Apache services are also imported (com.springresource). Jackson Bao Daoquan. Spring development base package.

(2) if the static resource cannot be loaded, release the static resource file.

(3) Spring's IoC mechanism can give objects to containers for management. IoC core: inject the implementation class to the caller through configuration file or announcement.

IOC implementation principle: factory mode + java reflection mechanism. IOC benefits:

First: centralized management of resources to realize the configurable and easy management of resources.

Second, it reduces the dependence of both sides of using resources, that is, the coupling.

Third: through the configuration file, you can change the implementation class without changing any caller's code (IOC).

(4) in this development, we use the mappingjackson 2httpmessageconverter, a built-in message converter of Spring MVC (used for the conversion of java objects and json data). Its internal implementation principle still uses the Jackson development package, which is why the Jackson package is imported. Of course, we can also directly use the Jackson class library to transform java objects and json data (my previous blogs). The built-in message converter is called here for your understanding. The execution process of Spring MVC and how the underlying java objects and json data are implemented. Of course, you can also customize your message converter class in Spring MVC to implement the httpmessageconverter < T > interface.

(5) the strength of this development is that it does not use any notes of Spring. It is based on pure XML configuration and adopts native mode. It is convenient for you to understand the underlying implementation principle.

(6) when learning, you can refer to the development documents of Spring and Spring MVC. You can refer to the Spring API documentation for classes you don't understand.

Posted by Cantaloupe on Sat, 02 Nov 2019 22:26:59 -0700