A small example of spring (2) -- parsing the previous small example

         Continued from the previous article: http://709002341.iteye.com/admin/blogs/2280103

         First of all, it should be understood that a web project, web.xml is the entry.

         Then let's analyze the web.xml that appeared in the previous blog:

         

<?xml version="1.0" encoding="UTF-8"?>  
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"  
    version="2.5">  
    <!-- Distinguish the project name to prevent the default duplicate name-->    
    <context-param>    
        <param-name>webAppRootKey</param-name>    
        <param-value>maven.cainiao.root</param-value>    
    </context-param>    
    
    <!-- Spring's log4j listener -->    
    <listener>    
        <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>    
    </listener>    
    
    <!-- charset filter-->    
    <filter>    
        <filter-name>CharacterEncodingFilter</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>CharacterEncodingFilter</filter-name>    
        <url-pattern>/*</url-pattern>    
    </filter-mapping>    
    
    <!-- Spring view dispatcher-->    
    <servlet>    
        <servlet-name>dispatcher_cainiao</servlet-name>    
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>    
        <init-param>    
            <param-name>contextConfigLocation</param-name>    
            <param-value>/WEB-INF/dispatcher_cainiao.xml</param-value>    
        </init-param>    
        <load-on-startup>1</load-on-startup>    
    </servlet>
    <servlet-mapping>    
        <servlet-name>dispatcher_cainiao</servlet-name>    
        <url-pattern>/</url-pattern>    
    </servlet-mapping>    
</web-app>

        The first is the context-param parameter. Before saying context-param, there should be a concept:

         The loading process of web.xml is context-param -> listener -> fileter -> servlet.

         The context-param attribute is the first to be loaded in the xml file, but it is the only one, and it must be used in conjunction with other java classes. The context-param is almost equivalent to the built-in map of a web project. The key and value are both Strings. The loading of the context-param is just a value for the map, which is equivalent to a configuration parameter, so that the subsequent listeners or filters can use the context-param . configured parameters.

           For example, my web server is jboss, configure parameters in context-param

<context-param>
		<param-name>webAppRootKey</param-name>
		<param-value>maven.cainiao.root</param-value>
	</context-param>

 

     After that, when jboss loads this project, the alias of this project is maven.cainiao.root . At this time, if there is another project in jboss with this name, then jboss will report an error.

      For another example, if you want to set log monitoring, you need to configure the log4jConfigLocation parameter in the context-param , and the log listener Log4jConfigListener will automatically monitor the file under the value corresponding to the log4jConfigLocation parameter when loading; for another example, the ContextLoaderListener listener is responsible for The xml file under the contextConfigLocation parameter path is loaded.

     Of course, you can also do the listener or filter yourself, and then configure the filtered parameters through context-param in web.xml (through ServletConfig.getInitParameter (key) ) .

      Then there is org.springframework.web.util.Log4jConfigListener, which is a spring log4j listener. It's okay to actually not use this listener, but there are several advantages to using it:

     First of all, if you don't use it, then the log configuration file log4j.properties must be written in the classpath, and if you use it, you can easily manage the location of log4j.properties.

     Secondly, there is a method in this monitor that scans the log4j configuration file every 60 seconds, so that you can modify the log4j configuration file without restarting the service.

     Then, the character filter CharacterEncodingFilter, you can see that the url-pattern in the filter-mapping is /*, which is responsible for forcibly converting all requests under /* (that is, all paths) to UTF-8 encoding, In this way, if you also use utf-8 when writing pages

Encoding can prevent the generation of garbled characters.

  Finally, it is the servlet that we deal with the most. First look at servlet-mapping, there is a url-pattern, which matches what is entered in the url, for example, in the above web.xml is /, then all the urls of http://localhost:8080/test/* will be Parsed by this servlet named dispatcher_cainiao. The servlet-name under the servlet-mapping corresponds to the servlet-name under the servlet, and the specific servlet is found according to the name ( servlet-mapping is the entrance of the servlet, which feels more like an interface, responsible for the entry url of the servlet and the corresponding specific servlet implementation class ) ; And this servlet-class is the specific servlet implementation class. Of course, we can write our own implementation class, so that the url will be requested to our own servlet (this is rarely written now), and we can also hand it over to spring for hosting, such as the implementation class writing org.springframework.web. servlet.DispatcherServlet, which is a process controller in the spring framework, is responsible for distributing urls. init-param indicates that its configuration parameters will be initialized. For example, in the above configuration, the configuration file path used by this dispatcher is: /WEB-INF/dispatcher_cainiao.xml, and load-on-startup indicates that it will start when the web is easy to start. Self-loading (this is very important, without this your url will not find the servlet that can be distributed).

  Let's look at the xml configuration file used by the distributor:

<?xml version="1.0" encoding="UTF-8"?>  
<beans xmlns="http://www.springframework.org/schema/beans"   
       xmlns:aop="http://www.springframework.org/schema/aop"   
       xmlns:context="http://www.springframework.org/schema/context"  
       xmlns:mvc="http://www.springframework.org/schema/mvc"   
       xmlns:tx="http://www.springframework.org/schema/tx"   
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
       xsi:schemaLocation="http://www.springframework.org/schema/aop   
        http://www.springframework.org/schema/aop/spring-aop-3.0.xsd   
        http://www.springframework.org/schema/beans   
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd   
        http://www.springframework.org/schema/context   
        http://www.springframework.org/schema/context/spring-context-3.0.xsd   
        http://www.springframework.org/schema/mvc   
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd   
        http://www.springframework.org/schema/tx   
        http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">  
  	
    <mvc:annotation-driven />  
    <!-- <mvc:default-servlet-handler/> -->
    <context:component-scan base-package="controller" />  
  	
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
        <property name="prefix" value="/views/" />  
        <property name="suffix" value=".jsp" />
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
    </bean>  
</beans>  

     First of all, mvc:annotation-driven is a shorthand mode, which means that the two beans DefaultAnnotationHandlerMapping and AnnotationMethodHandlerAdapter are automatically loaded, which is necessary for spring MVC to distribute requests to @Controllers. context:component-scan is an automatic scanning mechanism in spring, which is responsible for scanning all spring annotations contained in all the following classes in the package.

Then, register a bean: InternalResourceViewResolver, the view resolution class, which resolves the return in the servlet to the suffix file corresponding to the suffix in the parameter folder corresponding to the prefix.

       It needs to be used with the control class:

package controller;


import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.cainiaojava.beans.User;


/**  
* DispatcherController:
* @author xuejupo  [email protected]
*
* create in 2016-3-1 3:35:13 PM  
*    
*/
@Controller
@RequestMapping("demo")
public class DispatcherController {
	@RequestMapping(method=RequestMethod.GET)    
    public String printWelcome(ModelMap model) {  
		User user = new User();
		user.setInfo("Haha, I'm the only user!");
		user.setUserName("I am the boss!");
		user.setPasswd("Don't tell you!");
		model.addAttribute("str0121", "I'll go, it's a success!!!");
		model.addAttribute("info","The current user information is:");
		model.addAttribute("user", user);
        System.out.println("index.jsp");
        return "index";
    }  
}

 @Controller indicates that this is a controller, @RequestMapping("demo") indicates that he receives a url with a suffix of demo (such as http://localhost:8080/test/demo), and @RequestMapping(method=RequestMethod.GET) indicates a request If the method is get, enter this method. ModelMap is a built-in ui control class of spring, which can pass the value to the front end. return "index", and the value of the suffix parameter mentioned above, combine to form index.jsp, so this servlet will return the request to the page index.jsp.

 

    in conclusion:

     First load web.xml, first load context-param in web.xml, they have no practical significance, just a context. Then load the listener. The above web.xml configures the log listener, so load the Log4jConfigListener file (to configure the log listener, you should configure the log4jConfigLocation parameter in the context-param. I'm lazy, I haven't configured the log yet...), and then , load the character filter CharacterEncodingFilter, and then load the servlet from top to bottom (there is only one servlet in this article, there is no sequence problem), load the DispatcherServlet dispatcher, and then load the dispatcher's configuration file dispatcher_cainiao.xml. In dispatcher_cainiao.xml, because mvc:annotation-driven is written, two beans DefaultAnnotationHandlerMapping and AnnotationMethodHandlerAdapter are loaded, then the package controller is scanned , the annotations contained in all files under the package controller are processed, and then the view resolution class InternalResourceViewResolver is configured, and then the web The project is started.

       When we request http://localhost:8080/test/demo, we first find the project according to http://localhost:8080/test, and then according to /demo, look for the corresponding url-pattern in servlet-mapping item, find a dispatcher_cainiao, then find the file DispatcherController according to the annotation @RequestMapping("demo"), then enter the corresponding method to process, and finally return according to the return value index and the InternalResourceViewResolver view management in the configuration file, find the jsp file /views/ index.jsp, the last is to render the jsp file.

      ps:

       First of all, the only entry of the web project is web.xml (I don't know if there are other entries, I am a rookie, if there are other entries, I hope God will correct me by leaving a message), other xml files are registered in the web.xml file, Or it is loaded in a servlet or a listener, and the listener is also registered in web.xml, so all configuration files can be reached from web.xml through a certain path. To learn the spring framework, you must know what his general process is. So if you are a beginner in spring, it is recommended to find a blank sheet of paper and draw a good picture of what his process is going to be, which is very helpful.

      Please indicate the source of the reprint: http://709002341.iteye.com/admin/blogs/2281180 , you are also welcome to communicate with me here.

 

 

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327040107&siteId=291194637