Spring framework learning (7) Getting started with spring mvc

The content comes from: Getting started with spring mvc

 

1. The relationship between spring mvc and spring

Spring MVC is a layer in the seven-tier architecture provided by the spring framework. It is a part of the spring framework and is an MVC tool used by spring to process client requests, replacing the presentation layer framework struts1/2. When using, spring mvc and spring framework are independent of each other. Spring mvc is a separate presentation layer framework that is separated from the spring framework.

2. How to add spring mvc to the web project?

The way to add the spring framework to the web project is different from the way to add springmvc

 

 

If you use the spring framework and springmvc framework at the same time in the project, you need to register two classes in web.xml to load the two frameworks respectively

When registering spring web.xml ContextLoaderListener listener

Register the spring mvc framework in order to use this framework to process client request registration while setting the request format that needs to be processed for this framework *.do *.action *.etoak...

struts1 ActionServlet <servlet> <Servlet-mapping><url-pattern> *.do

struts2 StrutsPrepareAndExecuteFilter <filter><filter-mapping><url-pattern> *.action

Register spring framework ContextLoaderLIstener <listener> <listener-mapper>

 

The listener cannot set the request format it needs to handle for the spring framework

To register spring mvc, you need to set the processing request format for it, you need to use another class instead of the listener

DispatcherServlet extends HttpServlet <servlet> <servlet-mapping>

 

Three, the basic process of spring-mvc request processing

How spring-mvc handles requests: non-annotated version (2.0 and earlier), annotated version (after 2.5)

a The client submits the hello.do request, submits the request to web.xml (web container), and is intercepted by the DIspatcherServlet registered in the web container; DispatcherServlet forwards all the requests it intercepts to the request parser registered in the ioc container

b spring-mvc provides two request parsers for request parsing: The character/byte 
character parser provides a HandlerMapping interface, which can be used to parse the request using any of the implementation classes it provides. In this interface, two default request parsers are provided: SimpleUrlHandlerMapping /DefaultAnnoationHandlerMapping which one to use depends on whether the current ioc environment is an annotation environment or not 
. structure. 
Request parsers parse requests differently, but the structure of the parsing is the same: 
get the string "/hello" representing the request

c According to the parsed string, find the request handler for processing the request in the ioc container 
[struts1=Action struts2=ActionSupport] 
The request handler provided by spring-mvc needs to implement the Controller interface

1 Create a class that implements the Controller interface as the request processor of spring-mvc to process the request 
2 Configure it as a bean in the ioc container

@Controller 
class marked with this annotation will become the object instantiated by the  ioc container, which
is equivalent to manually configuring a bean in the ioc container

A class that provides a function that other annotations (@Compeont @Service @Repository) do not have 
will automatically implement the Controller interface and become the request processor of spring-mvc.

Create a class annotated with @Controller annotation - request handler - handle /hello request

Fourth, spring mvc form item encapsulation

Provide a third-party javaBean to encapsulate the form items in the request. Add the javaBean that encapsulates the form item to the first parameter of the method that handles the request.

Special case: When there is only one form item in the submit request, and the type of the form item is the basic data type or String type; the encapsulation of the form item can be performed directly using the first parameter of the processing request method. And can no longer provide a javaBean.

5. Chinese garbled characters

Cause: The encoding used by the client (utf-8) and the server (iso-8859-1) is inconsistent

Solution :

1 Soft coding

Modify the encoding format in the request and response

Constraints: When is the use of soft coding invalid?

1 get 2 upload, download

When using soft coding to solve Chinese garbled characters, it must be ensured that the location of the modified coding is before the form items are encapsulated!

2 Hardcoded

Assemble a new string with the new encoding

spring-mvc: use soft coding to rewrite the central controller DispatcherServlet

6. servlet-API interaction

HttpServletRequest HttpServletResponse HttpSession ServletContext..

 

 

servlet-API scope (request session application) provides a way similar to struts2, the scope is encapsulated in the map object

Map map=ActionContext.getContext().get("request/session/application")

 

 

ModelMap implements Map

 

 

@SessionAttributes(String[] attrs)

This annotation is used to annotate a class (request handler)

When using this annotation, you need to provide it with an array of String type

The array points to the data key added to the ModelMap

Copy this data and transfer it to the session scope.

 

Seven, sample program:

page:

<a href="hello.do">helloworld</a>
<form action="login.do" method="post">
登录名:<input type="text" name="loginname"/><br/>
密码: <input type="password" name="password"/><br/>
     <input type="submit" value="登录"/>
</form>

web.xml: 
load spring central controller and intercept .do requests

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" 
    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_3_0.xsd">

  <!-- 
    Register a central controller responsible for loading springmvc when the web container starts: DispatcherServlet,
Here we use the soft coding method to rewrite the doService() method in the DispatcherServlet provided by spring mvc, so the value of <servlet-class> is the class we wrote.
    DispatcherServlet role:
    1 Load springmvc framework instead of ContextLoaderListener
        [The configuration files used by spring and springmvc are both ioc containers]
    2 Set the request format that spring mvc allows to process to prevent garbled characters
   -->
  <servlet>
    <servlet-name>etoak</servlet-name>
    <servlet-class>com.etoak.util.MyDispatcherServlet</servlet-class>
    <!-- 
        If you do not write <init-param>contextConfigLocation default value:
            /WEB-INF/etoak-servlet.xml
     -->
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext.xml</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
    <servlet-name>etoak</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>
  <display-name></display-name> 
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

applicationContext.xml

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    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-3.2.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.2.xsd">

    <!-- 
        Request parser:
        There are two kinds of parsers responsible for parsing requests in spring-mvc:
            character request parser
                HandlerMapping interface
            spring-mvc provides two default request parsers for parsing character requests:
                SimpleUrlHandlerMapping
                    Default in non-annotated environments
                DefaultAnnotationHandlerMapping
                    The default in the annotation environment
            bytes request parser [upload request parser]
                MultipartResolver interface
        The way of parsing the request is different, but the parsing result is the same:
        Get the string /hello representing the request
     -->    
    <context:component-scan base-package="com"/>
</beans>

HelloController.java 
handles the request

/**
 * Business logic layer
 *  servlet    XxServlet  com.etoak.servlet
 *  struts1/2   XxAction   com.etoak.action
 *  spring-mvc  XxController  com.etoak.controller
 */

@Controller
@SessionAttributes({"user"})
public class HelloController {

    /** "/hello"
     * The mapping relationship between requests and processing is formed?
     *  @RequestMapping(path)
     * This annotation is used to annotate a method in the request handler;
     * Use this method to handle the request pointed to by path
     */
    @RequestMapping("/hello")
    public String hello(){
        System.out.println( "Process the hello.do request submitted by the client" );
         /**
         * Return a response view for the client
         * The way to return the response view: handle the return value of the request method (String)
         * The form of the return view: redirect redirect | forward forward
         */
        return "redirect:success.jsp";
        // return "forward:/success.jsp";
    }

    @RequestMapping("/login")
    public String login(User user){

        // Indicates that a user object of the User type is used to encapsulate the form items in the current request 
        /* hard-coded to prevent garbled characters:
        String loginname = user.getLoginname();
        try {
            loginname = new String( loginname.getBytes("iso-8859-1"), "utf-8");
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace ();
        }
        */
        System.out.println("loginname-->"+user.getLoginname());
        System.out.println("password-->"+user.getPassword());
        return "forward:success.jsp";
    }

    @RequestMapping("/selectUserById")
    public String selectUserById(Integer id , ModelMap map){

        System.out.println("id-->"+id);

        User user = new User("sheldon","111" );
         /** Stored in the request scope
         * Add user to ModelMap object
         * The data added to the ModelMap is stored in the request scope by default
         */
        map.put("user", user);
        // request.setAttribute("user",user);

        return "forward:success.jsp";
    }
}

MyDispatcherServlet.java 
soft coding control coding format:

public  class MyDispatcherServlet extends DispatcherServlet {
     // Soft coding: Rewrite the doService method in DispatcherServlet to control the request coding format 
    @Override
     protected  void doService(HttpServletRequest request,
            HttpServletResponse response)
            throws Exception {
        // TODO Auto-generated method stub

        request.setCharacterEncoding("utf-8");

        super.doService(request, response);
    }
}

User.java

public class User {

    private String loginname;
    private String password;
    public User(String loginname, String password) {
        super();
        this.loginname = loginname;
        this.password = password;
    }
    public String getLoginname() {
        return loginname;
    }
    public void setLoginname(String loginname) {
        this.loginname = loginname;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325172546&siteId=291194637