[Notes] SpringMVC---SpringMVC and simple environment construction

SpringMvc request process

write picture description here
[note:]
1. The client request request is initiated, and the request is sent to the DispatcherServlet. The DispatcherServlet is actually a controller Controller. It will go to the "xxx-servlet.xml" configuration file to find a corresponding "beanname" of the configured HandlerMapping , and then use it to find the request url which should be handed over to the "Controller" for processing.
2. In the specific "Controller", it completes the interaction with "Service", "JavaBean", etc., gets a certain value, and then returns a "ModelAndView" view.
3. For the returned view, find its corresponding specific returned view and the return form of its view through the configured ViewResolver.
4. Finally, return to the specific view "View" and display it on the client browser.

DispatcherServlet: package org.springframework.web.servlet;
HandlerMapping: org.springframework.web.servlet
[note:] 1. (note that it is under servlet) 2. "AbstractHandlerMapping" which implements the "HandlerMapping" interface, and "AbstractDetectingUrlHandlerMapping" Inherited "AbstractHandlerMapping", and then there are three important inheritances for "AbstractDetectingUrlHandlerMapping" "DefaultAnnotationHandlerMapping": more used to realize the mapping relationship through spring annotation, "BeanNameUrlHandlerMapping": traditionally configure HandlerMapping through "beanname" to achieve mapping relationship, "AbstractControllerUrlHandlerMapping"






Environment construction

  1. 新建javaWeb项目,导入Springjar包和apache下的commons-loggin的jar包:
    commons-logging.jar
    spring-aop-4.1.1.RELEASE.jar
    spring-aspects-4.1.1.RELEASE.jar
    spring-beans-4.1.1.RELEASE.jar
    spring-context-4.1.1.RELEASE.jar
    spring-context-support-4.1.1.RELEASE.jar
    spring-core-4.1.1.RELEASE.jar
    spring-expression-4.1.1.RELEASE.jar
    spring-instrument-4.1.1.RELEASE.jar
    spring-instrument-tomcat-4.1.1.RELEASE.jar
    spring-jdbc-4.1.1.RELEASE.jar
    spring-jms-4.1.1.RELEASE.jar
    spring-messaging-4.1.1.RELEASE.jar
    spring-orm-4.1.1.RELEASE.jar
    spring-oxm-4.1.1.RELEASE.jar
    spring-test-4.1.1.RELEASE.jar
    spring-tx-4.1.1.RELEASE.jar
    spring-web-4.1.1.RELEASE.jar
    spring-webmvc-4.1.1.RELEASE.jar
    spring-webmvc-portlet-4.1.1.RELEASE.jar
    spring-websocket-4.1.1.RELEASE.jar
  2. Configure "DispatcherServlet" 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_3_1.xsd"
         version="3.1">
    <servlet>
        <servlet-name>hello</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!-- 设置在项目启动的时候就让它跟随启动 -->
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
    <!-- 所有的页面只要访问url,都会被servlet捕获,捕获之后就会进入到springmvc的处理 -->
        <servlet-name>hello</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

[note:]
The "servlet-name" is set to "hello" here, so to create a corresponding "hello-servlet.xml", the file name here must be the same as the "servlet-name" set in the configuration.
4. Create the corresponding spring configuration file "hello-servlet.xml"

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <bean name="/welcome" class="com.xing.controller.WelcomeController"></bean>
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>
</beans>

[note:]
1. Complete the mapping relationship by setting "beanname".
2. Configure the corresponding view resolver "org.springframework.web.servlet.view.InternalResourceViewResolver".
InternalResourceViewResolver: There are two properties in the class, prefix: prefix, suffix: suffix. That is to say, when the corresponding controller returns a ModelAndView, he will find a specific view of "name returned by ModelAndView" + ".jsp" in the already configured "/WEB-INF/jsp/" path .
6. Create the Controller corresponding to the "class" configured in the above steps ( the created Controller needs to inherit "AbstractController" )

package com.xing.controller;

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

/**
 * Created with IntelliJ IDEA
 * Created By 【星】
 * Date: 2016/8/9
 * Time: 18:05
 */
public class WelcomeController extends AbstractController {
    @Override
    protected ModelAndView handleRequestInternal(javax.servlet.http.HttpServletRequest httpServletRequest, javax.servlet.http.HttpServletResponse httpServletResponse) throws Exception {
        System.out.println("welcome");

        //return 返回的是我们具体要对应的视图
        return new ModelAndView("welcome");
    }
}
  1. Create the corresponding view file under "/WEB-INF/jsp" (the name of the view file created here is determined according to the result returned by the Controller)
<%--
  Created by IntelliJ IDEA.
  User: 【星】
  Date: 2016/8/9
  Time: 18:13
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h1>Welcome</h1>
</body>
</html>

Start "tomcat" to access the address: " http://localhost:8080/xing-spring-stu01/welcome ", if "Welcome" appears in the browser, it means success.

[note:] The whole process:
url request: " http://localhost:8080/xing-spring-stu01/welcome " was intercepted by "DispatcherServlet";
--> found HandlerMapping with beanname "/welcome";
--> found it The corresponding "WelcomeController.java" class, --> found the "handleRequestInternal" method in this class;
--> After processing in this method, the "welcome" view is returned, which is to resolve this view through "InternalResourceViewResolver"
–> According to the parser settings, find the corresponding welcome.jsp

Annotation-based configuration

1. Open Annotation: Open in the corresponding xxx-servlet.xml configuration file:

    <!--打开annotation-->
    <context:component-scan base-package="com.xing.controller" />
    <mvc:annotation-driven />

2. Create the corresponding "HelloController.java"

package com.xing.controller;

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

/**
 * Created with IntelliJ IDEA
 * Created By 【星】
 * Date: 2016/8/10
 * Time: 15:22
 */
@Controller
public class HelloController {
    @RequestMapping({"/hello","/hello1"})
    public String hello(){
        System.out.println("Hello");
        return "hello" ;
    }
}

3. Create "hello.jsp"
@RequestMapping: Support multiple mapping paths to point to the same controller.
Access: " http://localhost:8080/xing-spring-stu01/hello " or " http://localhost:8080/xing-spring-stu01/hello1 ".

Pass value to Controller

Example: Using @RequestParam in a method

    @RequestMapping({"/sayHello1"})
    public String sayHello1(@RequestParam("name") String name){
        System.out.println("name=="+name);
        return "hello" ;
    }

Test: http://localhost:8080/xing-spring-stu01/sayHello1?name=ok
Background: "ok" is successfully obtained,
but after using @RequestParam, if no value is passed in the request at this time, a request error will be thrown exception. Because @RequestParam is used, it will think that the parameters we pass are also part of the request url.
To solve the above problem, we can directly remove @RequestParam and pass parameters directly. If parameter confirmation is essential, you can use @RequestParam
When requesting, use the parameters of the function directly

    @RequestMapping({"/sayHello2"})
    public String sayHello2(String name){
        System.out.println("name=="+name);
        return "hello" ;
    }

Pass values ​​from Controller to View

1. Use the Map collection in the method of the Controller

    @RequestMapping({"/sayHello3"})
    public String sayHello3(String name,Map<String,String> context){
        System.out.println("name=="+name);
        context.put("name",name) ;
        return "hello" ;
    }

2. Model is used in the Controller method, and the addAttribute() method it provides is used to pass the value

    @RequestMapping({"/sayHello4"})
    public String sayHello4(String name,Model model){
        System.out.println("name=="+name);
        model.addAttribute("name",name) ;
        return "hello" ;
    }

model.addAttribute(Object) ; it can also pass an object

Guess you like

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