For SpringMVC overview

Springmvc is a module of the Spring framework, and spring and Springmvc do not need to be integrated by an intermediate integration layer.

Springmvc is an MVC based Web framework

The three tasks of the presentation layer are:

URL mapping to controller

HTTP request parameter binding

Generation and output of HTTP responses

MVC Design pattern

MVC design pattern is a general software programming idea.

According to the MVC design pattern, any software can be divided into three parts:

(1) Controller to control program flow

(2) Encapsulating data processing data Model (Model)

(3) View responsible for displaying data

Implementation principle of SpringMvc

(1). Users send requests to the front-end controller (DispatcherServlet);

Tips: The role of DispatcherServlet: receive requests, call other components to process requests, response results, equivalent to the repeater, central processing unit, is the center of the whole process control

(2). The front-end controller (DispatcherServlet) invokes the HandlerMapping after receiving the request.

The HandlerMapping finds the specific Controller(which can be found according to the XML configuration, annotated line) and returns the Controller to the DispatcherServlet;

(3). The front-end controller (DispatcherServlet) calls the processor adapter (HandlerAdapter). The handler adapter is adapted to invoke a specific Controller; (Controller–> Service –> Dao –> database)

Controller executes and returns to ModelAndView,

Tip: Model(Model data, which is the result of the Controller’s processing, Map) View(logical View name, which is the name of the JSP page that displays the result)

The HandlerAdapter (HandlerAdapter) returns the results of the controller execution (ModelAndView) to the front-end controller (DispatcherServlet);

(4). The front-end controller (DispatcherServlet) will execute the result (ModelAndView) to the view parser (ViewReslover).

The ViewReslover returns the specific JSP page after parsing based on the View(logical View name)

(5). The front-end controller (DispatcherServlet) renders the View according to the Model (that is, the Model data is filled into the View);

The front-end controller (DispatcherServlet) sends the data-populated web page response to the user

For SpringMVC implementation

Step 1: Create the Maven project SpringMVC

Step 2: Add dependencies to the POM file

<dependencies>
    <!-- 单元测试 -->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.10</version>
        <scope>test</scope>
    </dependency>
    <!-- SpringMVC的jar包 -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>4.1.3.RELEASE</version>
    </dependency>
    <!-- servlet 和 jsp的jar包 -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>servlet-api</artifactId>
        <version>2.5</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jsp-api</artifactId>
        <version>2.0</version>
        <scope>provided</scope>
    </dependency>
    <!-- java对象转换json的工具类
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.5.1</version>
    </dependency>
    -->
</dependencies>

Copy the code

Step 3: Configure the front-end controller in web.xml

<? The 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_2_5.xsd" id="WebApp_ID" Version = "2.5" > <! Configure springMVC front-end controller, Give all requests to SpringMVC to handle --> <servlet> <servlet-name> SpringMVC </servlet-name> <servletclass>org.springframework.web.servlet.DispatcherServlet</servletclass> <! By default, the springMVC configuration file is in the web-INF directory. The default name of the configuration file is springmVC-servlet.xml. If it is in another directory, specify the following configuration:  --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc-config.xml</param-value> </init-param> </servlet> <! -- The slash (/) means to intercept all requests (except JSP), All requests go through springMVC front-end controller --> <servlet-mapping> <servlet-name> SpringMVC </servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>Copy the code

Step 4: Create and configure SpringMVC-config.xml

<? The 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/mvc http://www.springframework.org/schema/mvc/spring-mvc4.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/springbeans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context4.0.xsd "> <! --> < MVC :default-servlet-handler/> <! -- 2. Configure annotation drivers to recognize annotations (such as @Controller) --> < MVC :annotation-driven></ MVC :annotation-driven><! -- 3. Configure the packets to be scanned: Spring automatically scans classes in the Base-package. If the class has @Controller, @Service, @Component annotations, etc., Classes will be automatically registered as beans --> <context:component-scan base-package="com.tedu.controller"> </context:component-scan> <! Prefix: configure path prefix suffix: configure file suffix --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/pages/"/> <property name="suffix" value=".jsp"/>Copy the code

Step 5: Create HelloController

RestController = controller + responsebody:

RestController returns a JSON object

Controller Mandatory string: modelANDView

Controller + ResponseBody returns a JSON object

package com.tedu.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; /* @controller, if the package in which the current class belongs is configured with Spring package scanning, classes with this annotation will be registered as beans in the Spring container, and instances will be created by the Spring container. */ @controller public class HelloController {/* @requestMapping configures the access path for the current method * When the browser to http://localhost:8080/day20-springmvc/hello * if no configuration on the Controller class access path, in the way that all * in Controller in the current project access paths are different conflict! */ @RequestMapping("/hello") public String testHello() { System.out.println( "HelloController.testHello()" ); System.out.println( "hello springmvc..." ); // jump to/web-inf /pages/home.jsp return "home"; }}Copy the code

Step 6: Create and implement home.jsp

In the web-INF /pages/ directory, create the home.jsp page.

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <! DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <h1>day20-springmvc... home.jsp... </h1> </body> </html>Copy the code

Step 7: Test by sending a request

Open your browser and enter the URL: http://localhost :8080/day16-springmv/hello.

Redirection and forwarding

The difference between a redirect and a forward

1. Redirect the browser to display a new address in the address bar, and the forwarding address bar remains unchanged

2. Redirection can be redirected to other websites, and forwarding can only be forwarded to the method in this website.

Redirect to Redirect

Application to the original page is no longer available.

@controller public class UserController {// redirect, The original login address @ RequestMapping ("/login ") public String the login () {return "redirect:https://passport.jd.com/new/login.aspx"; }}Copy the code

http://localhost:8080/login

After the forwarding, the browser address bar changes to the forwarded address.

View the Status code in Network in Chrome’s debug window

Forward Forward

The browser address bar remains the same. So parameters requested before forwarding can still be read after forwarding.

@requestMapping ("/ requestinByName ") @responseBody public String requestInByNamepwd (String username,String password)  { return "login"; } // When logging in again, @requestMapping ("/loginByCode") public String loginByCode(String username,String password,String code) { Return "forward:/loginByName"; // Check whether the verification code is correct. }Copy the code

Restful style

The @pathVariable is used to map template variables in the request URL to parameters of the function handling method

RUSTFul form, this will be the trend of the future. It’s much simpler and safer. Strengthen the URL GET access mode.

@RestController public class OrderCotroller { @RequestMapping("/order/{startTime}/{endTime}") public String searchByDate(@PathVariable String startTime, @PathVariable String endTime) { return "restful startTime="+startTime+",endtime="+endtime; }}Copy the code

The last

I have arranged a: Spring family barrel series, Java systematic information, (including Java core knowledge, interview topics and the latest Internet real questions in 20 years, e-books, etc.) friends who need to pay attention to the public number can be obtained.