One 、 summary

Spring Web MVC It's based on Java Realized. Web MVC Design pattern request driven type lightweight Web frame , That is to use MVC The idea of architecture pattern , take web Layer to decouple responsibilities , Request driven refers to the use of requests - Response model .

1、 What is? MVC?

Model - View - controller (MVC) Is a design pattern based on the design of interface applications . It is mainly through the separation model 、 The role of view and controller in the application decouples business logic from the interface . Usually , The model is responsible for encapsulating the application data in the view layer . The view just shows the data , Does not contain any business logic . The controller is responsible for receiving requests from users , And call the background service to process the business logic . After processing , The background business layer may return some data to be displayed in the view layer . The controller collects these data and prepares the model for presentation at the view level .MVC The core idea of the pattern is to separate the business logic from the interface , Allow them to change independently without affecting each other .

stay Spring MVC in , The model is usually made up of POJO Object composition , It's handled in the business layer , Persistent in the persistence layer , The view usually uses JSP Standard label library (JSTL) Compiling JSP Templates , The controller part is made up of dispatcher servlet be responsible for .

2、Spring MVC framework

SpringMVC It's a request driven Web frame , Use front end controller mode to design , According to the mapping rules distributed to the corresponding page controller for processing . The request processing flow is shown in the figure below :

The specific steps are as follows :

1、 The client sends a HTTP request ,Web The application server received the request , If the match DispatcherServlet Request mapping path for (web.xml It is specified in ),Wen The container will forward the request to DispatcherServlet Handle .

2、DispatcherServlet After receiving this request , Will be based on the requested information and HandlerMapping To find the processor handling the request (Handler).

3、 obtain Handler after , adopt HandlerAdapter Yes Handler encapsulate , And then call... With a unified adapter interface Handler.

4、 After processing the business logic, the processor returns a ModelAndView to DispatcherServlet,ModelAndView Contains view logical name and model data information .

5、DispatcherServlet through ViewResolver Complete the parsing from logical view name to real view object .

6、 When you get the real view object view after ,DispatcherServlet Just use this View Object pair ModelAndView Rendering model data in .

7、 The final response message received by the client may be a normal HTML page , It could be one XML Or is it JSON strand .

Two 、 Basic configuration ( Non comment )

1、 New project , Import build SpringMVC What is needed for the project jar package

2、 Configure front end controller

stay web.xml Configure the front end controller :

<?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">
<display-name>day_0301_springMVC</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<!-- Front controller -->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- contextConfigLocation To configure springmvc The loaded configuration file ( Configure the processor mapper 、 Adapter, etc )
If you don't configure contextConfigLocation, The default load is /WEB-INF/servlet name -servlet.xml
-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<!--
The first one is :*.action, Visit to .action Ending by DispatcherServlet To analyze
The second kind :/, All addresses visited are by DispatcherServlet To analyze , For static file parsing, you need to configure not to allow DispatcherServlet To analyze
-->
<url-pattern>*.action</url-pattern>
</servlet-mapping>
</web-app>

3、 Configure the processor mapper

stay classpath Under the springmvc.xml Configuration of processor mapper

<!-- Processor mapper , take bean Of name As URL Search for , Need to be configured Handler When you specify beanName( Namely URL)-->
<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"></bean>

4、 Configure the processor adapter

<!-- Processor adapter , All processor adapters implement HandlerAdapter Interface -->
<bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter">
</bean>

5、 Configure the view parser

<!-- Configure the view parser 
analysis jsp View , By default jstl label
CLASSPATH There's going to be jstl jar package
-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"></bean>

6、 To write Handler

Need to achieve Controller Interface , Only by SimpleControllerHandlerAdapter The adapter performs .

First create POJO object :

public class Items
{
private String name;
private int price;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public int getPrice()
{
return price;
}
public void setPrice(int price)
{
this.price = price;
}
}

establish Handler:

public class TestController implements Controller
{
@Override
public ModelAndView handleRequest(HttpServletRequest request,HttpServletResponse response) throws Exception
{
List<Items> itemsList=new ArrayList<Items>();
Items items1=new Items();
items1.setName(" Lenovo notebook ");
items1.setPrice(2500);
Items items2=new Items();
items2.setName(" Samsung notebook ");
items2.setPrice(5000);
itemsList.add(items1);
itemsList.add(items2);
ModelAndView modelAndView=new ModelAndView();
modelAndView.addObject("itemsList", itemsList);
modelAndView.setViewName("/WEB-INF/jsp/items/itemsList.jsp");
return modelAndView;
}
}

7、 Authoring views jsp

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title> Query product list </title>
</head>
<body>
<form action="${pageContext.request.contentLength}/item/queryItem.action" method="post">
Query criteria :
<table width="100%" border="1">
<tr>
<td><input type="submit" value=" Inquire about "/></td>
</tr>
</table>
List of goods :
<table width="100%" border="1">
<tr>
<td> Name of commodity </td>
<td> commodity price </td>
<td> operation </td>
</tr>
<c:forEach items="${itemsList}" var="item">
<tr>
<td>${item.name }</td>
<td>${item.price }</td>
<td><a href="${pageContext.request.contextPath}/item/editItem.action?name=${item.name}"> modify </a></td>
</tr>
</c:forEach>
</table>
</form>
</body>
</html>

8、 To configure Handler

<bean name="/queryItems.action" class="com.demo.ssm.controller.TestController"></bean>

Here we are ,springmvc.xml The configuration is complete , The specific configuration file is as follows :

<?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"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
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-4.1.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd"> <bean name="/queryItems.action" class="com.demo.ssm.controller.TestController"></bean> <!-- Processor adapter , All processor adapters implement HandlerAdapter Interface -->
<bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter">
</bean> <!-- Processor mapper , take bean Of name As URL Search for , Need to be configured Handler When you specify beanName( Namely URL)-->
<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"></bean> <!-- Configure the view parser
analysis jsp View , By default jstl label
CLASSPATH There's going to be jstl jar package
-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"></bean>
</beans>

9、 Deployment mode

Address visited :http://localhost:8080/day_0301_springMVC/queryItems.action

The results are shown in the following figure :

3、 ... and 、 Annotation based mapper and Adapter Configuration

In the mapper and Adapter Configuration Based on annotation , annotation Handler It is written as follows :

@Controller
public class TestController2
{
@RequestMapping("/queryItemsTest")
public ModelAndView queryItems()
{
List<Items> itemsList=new ArrayList<Items>();
Items items1=new Items();
items1.setName(" Lenovo notebook ");
items1.setPrice(2500);
Items items2=new Items();
items2.setName("apple");
items2.setPrice(5000);
itemsList.add(items1);
itemsList.add(items2);
ModelAndView modelAndView=new ModelAndView();
modelAndView.addObject("itemsList", itemsList);
modelAndView.setViewName("/WEB-INF/jsp/items/itemsList.jsp");
return modelAndView;
}
}

springmv.xml The configuration is as follows :

<?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"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
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-4.1.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd">
<bean class="com.demo.ssm.controller.TestController2"></bean>
<!-- Annotation mapper -->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>
<!-- Annotation adapter -->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/>
<!-- Use the following mvc:annotation-driven Instead of the above annotation mapper and annotation adapter -->
<mvc:annotation-driven></mvc:annotation-driven>
<!-- <context:component-scan base-package="com.demo.ssm.controller"></context:component-scan> -->
<!-- Configure the view parser -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"></bean>
</beans>

After deployment , Access address :http://localhost:8080/day_0301_springMVC/queryItemsTest.action, The operation result is the same as above .

Four 、 Engineering source code

Click on Project source code download link

SpringMVC Series of basic configuration of more related articles

  1. springmvc A series of The configuration of ( Including the official website doc)

    1.springmvc Official website reference address : https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html 2 ...

  2. ( turn )springMVC+mybatis+ehcache Detailed configuration

    One . Mybatis+Ehcache To configure In order to improve the MyBatis Performance of , Sometimes we need to add cache support , At present, there is no more cache than ehcache Cached ,ehcache Powerful performance , And all kinds of applications provide solutions ...

  3. 【SpringMVC】SpringMVC series 11 And Restful Of CRUD

      11.Restful Of CRUD 11.1. demand 11.2.POST Turn into PUT.DELETE Of fileter 11.3. Query all 11.4. add to 11.5. Delete      elegant REST The style of the capital ...

  4. 【SpringMVC】SpringMVC series 10 View and view parser of

    10. Views and view parsers 10.1. summary      After execution of the request processing method , Finally return to a ModelAndView processing method ,Spring MVC They will also be assembled internally into a ModelAndView object , ...

  5. ANDROID Porting Series two 、 Configure a new product

    ANDROID Porting Series two . Configure a new product Detailed instructions The following steps describe how to configure new mobile devices and products makefile function android. 1.          Catalog //vendor/ Create a public ...

  6. Spring Web MVC Page caching support in —— Follow me SpringMVC series

    Spring Web MVC Page caching support in —— Follow me SpringMVC series

  7. JavaEE Development of SpringMVC In the routing configuration and parameter transfer details

    Before we used Swift Of Perfect Framework to develop the server program , Talk about the Perfect Routing configuration in . And in the SpringMVC The routing configuration in is similar to that in . When it comes to routing , It's really just the URL Mapping to Java The concrete class ...

  8. Spring-MVC Development steps ( Entry configuration )

    Spring-MVC Development steps ( Entry configuration ) Step1. Guide pack spring-webmvc Step2. add to spring The configuration file Step3. To configure DispatcherServlet stay web.xml in : ...

  9. Robotframework-Appium series : Installation configuration

    1.   Robotframework-android series : Installation configuration 1.1. Installation environment 64 position win10 Family Chinese 1.1. Installation instructions online robotframework-appium There are a lot of installation information , ...

Random recommendation

  1. Browser execution js

    Scriptish chrome Bring their own greasemonkey http://www.firefox.net.cn/forum/viewtopic.php?f=5&t=45715

  2. 24 Design patterns -- Iterative mode 【Iterator Pattern】

    On Friday afternoon , I'm looking at the technology website , The sixth sense is that someone is behind you , Turn around and take a look. , I C, The boss is standing behind , Get up in a hurry ,“ Manager Wang , You come to me ?” I said, . “ Oh , Looking at technology . I'd like to talk to you about something , You come to my office .” The eldest son said . To ...

  3. MyBatis Query two fields , return Map, A field as key, A field as value The implementation of the

    1. Problem description In the use of MyBatis, We often encounter this situation :SELECT Two fields , I need to return a Map, The first of these fields is key, The second field serves as value.MyBatis Of MapKey Although it's very practical , But not ...

  4. mac platform adb、tcpdump catcher android Mobile network packets

    In the development of mobile phones app When we want to be able to see app The network makes a request , We need to tcpdump Toolkit capture . Realization tcpdump Emptiness , The following steps require : ad locum , stay android Huawei mobile phones P6 For samples ...

  5. of struts in DispatchAction Summary of usage of

        I just saw it today DispatchAction I think it's interesting , So just write something , Through its name, I think we can understand its function , For distribution Action, The main advantage is that some functions are similar Action In a Ac ...

  6. Python Beginners —— Windows, windows Tkinter

    This article is learning from brother Mo fan's video , Attach the learning website :https://morvanzhou.github.io/tutorials/python-basic/ What is? tkinter window 1.1 What is? ...

  7. ssh Integration six manages our profile

    1. our ssh The building has been built , It used to be pure xml The way , And our profile , It's a framework, a configuration file . In this case , There will be a lot of content in the configuration file , In this way, it will be very troublesome to modify later , because         this , We're trying to put these ...

  8. Mysql 5.7 Weak password restrictions , And create users with no password

    One . Introduce 1.haproxy Mysql Need a password free login mysql user . 2.Mysql 5.7 Version installed by default  validate_password  plug-in unit , effect : The complexity of the required password . 3. Create user ...

  9. java web solve Form Form garbled problem

    JSP and Servlet Six ways to deal with Chinese garbled code One . Garbled form submission : During form submission , Often submit some Chinese , Naturally, we can't avoid the situation of garbled Chinese , There are two ways to submit a form :get and post submission . ...

  10. 【bzoj2259】[Oibh] New computers Heap optimization Dijkstra

    Title Description Tim Playing with his design “ Computer ”, He thinks the principle of this computer is very unique , So many problems can be solved with it .  however , There's a problem he can't solve , It's the input problem of this computer . The input of the new computer is also very unique , Let's say the input sequence has ...