1 Introduction
What is MVC framework
The full name of MVC is Model View Controller, which is the abbreviation of model-view-controller. It is a software design model. It organizes code using a separation method of business logic, data, and interface display, and gathers business logic into a component. While improving and personalizing the interface and user interaction, there is no need to rewrite business logic. MVC has been uniquely developed to map traditional input, processing and output functions in a logical graphical user interface structure.
Model-View-Controller (MVC) is a well-known design pattern based on design interface applications. It mainly decouples business logic from the interface by separating the role of models, views and controllers in applications. Typically, the model is responsible for encapsulating application data in the view layer. The view only displays this data and does not contain any business logic. The controller is responsible for receiving requests from users and calling background services (manager or dao) to handle business logic. After processing, the background business layer may return some data to be displayed in the view layer. The controller collects this data and prepares the model to be displayed in the view layer. The core idea of the MVC model is to separate business logic from the interface, allowing them to change individually without affecting each other.
In SpringMVC applications, the model is usually composed of POJO objects, which are processed in the business layer and persisted in the persistence layer. Views are usually JSP templates written in JSP Standard Tag Library (JSTL). The controller part is managed by the dispatcherservlet, and we will learn more about it in this tutorial.
Some developers believe that the business layer and DAO layer classes are part of the MVC model components. I have different opinions on this. I don't think that the business layer and the DAO layer classes are part of the MVC framework. Usually a web application is a three-layer architecture, namely data-service-representation. MVC is actually part of the presentation layer.
Dispatcher Servlet (Spring Controller)
In the simplest Spring MVC application, the controller is the only Servlet you need to configure in the Java web deployment description file (i.e. the web.xml file). Spring MVC controller - commonly known as Dispatcher Servlet, implements the front-end controller design pattern. And each web request must pass through it so that it can manage the entire request lifecycle.
When a web request is sent to a Spring MVC application, the dispatcher servlet first receives the request. It then organizes components configured in the Spring web application context (such as the actual request processing controller and view resolver) or using annotation configuration, all of which require processing the request.
Define a controller class in Spring 3.0, which must be marked with the @Controller annotation. When a controller with @Controller annotation receives a request, it will look for a suitable handler method to handle the request. This requires the controller to map each request to the handler method through one or more handler mappings. In order to do this, methods of a controller class need to be decorated with @RequestMapping annotation to make them handler methods.
After the handler method has processed the request, it delegates control to a view with the same view name as the handler method's return value. To provide a flexible method, the return value of a handler method does not represent the implementation of a view but a logical view, i.e., there is no file extension. You can map these logical views to the correct implementation and write these implementations to the context file so that you can easily change the view layer code without even modifying the code that requests the handler class.
It is the responsibility of the view resolver to match the correct file for a logical name. Once the controller class has parsed a view name to a view implementation. It renders the corresponding object according to the design implemented by the view.
2 Import jar package
At least there should be these.
3 Configuration Files
3.1 web.xml
<?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 http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>SpringMVC_HelloWorld</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> <!-- servlet for spring mvc --> <!-- After initialization, DispatcherServlet will directly look for springmvc-servlet.xml file under /WEB-INF/. The parameter definition of the servlet-name tag should correspond to the XML file --> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener></web-app>
3.2 springmvc-servlet.xml
The name of this file is determined by the <servlet-name></servlet-name> of the DispatcherServlet configured in web.xml. The path is in context/WEB-INF/, which mainly configures the corresponding relationship between the logical view name and the physical view returned by the controller.
<?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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <!-- Automatically scanned package --> <context:component-scan base-package="com.lin.helloworld.controller" /> <bean id="viewResolver" > <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> <!-- Controller Returns a logical view name after pre-suffix processing to return to the physical view --> <property name="prefix" value="/WEB-INF/jsp/" /> <property name="suffix" value=".jsp" /> </bean></beans>
4 Write a domain class
Used to encapsulate some submission data
package com.lin.helloworld.domain;public class HelloWorld {private String data;public HelloWorld() {super();}public HelloWorld(String data) {super();this.data = data;}public String getData() {return data;}public void setData(String data) {this.data = data;}@Override public String toString() {return "HelloWorld [data=" + data + "]";}} 5 Write controller
This is the controller in MVC. What is different from struts2 is that it is a method-level intercept, and struts2 is a class-level intercept.
package com.lin.helloworld.controller;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.ModelAttribute;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.servlet.ModelAndView;import com.lin.helloworld.domain.HelloWorld;@Controllerpublic class HelloWorldController {//Here /hello is equivalent to an action in struts2//Return a string to the view @RequestMapping("/hello") public ModelAndView saysHello() {//The first parameter of the modelAndView constructor is equivalent to a result in Struts2 nameModelAndView modelAndView = new ModelAndView("helloworld", "msg", "HelloWorld!!!");return modelAndView;}//Return an object to the view//@ModelAttribute("obj") is equivalent to a field in the action class of Struts2, //The data used for form submission is put into an object//The difference between here and struts2://struts2 handles form submission:<input name="obj.data"//The submitted data is encapsulated in the data of the obj object//Springmvc is:<input name="data"//The submitted data is encapsulated in the data of the obj object, //The premise is to use @ModelAttribute annotation @RequestMapping("/helloObj") public ModelAndView saysHelloWorld(@ModelAttribute("obj") HelloWorld obj) {System.out.println(obj.toString());ModelAndView modelAndView = new ModelAndView("helloworld", "obj", obj);return modelAndView;}}6 views
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head> <base href="<%=basePath%>" rel="external nofollow" > <title>My JSP 'helloworld.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css" rel="external nofollow" > --> </head> <body> HelloWorld! This is a spring mvc framework example.<br> ${msg} <hr/> <form action="helloObj" method="post"> <!-- The form submission here is different from struts2. Name="data" will automatically correspond to the filed of the object --> <input type="text" name="data" size="30"/><br/> <input type="submit" value="Submit"/> </form> <hr/> ${obj.data} </body></html>7 Directory Structure
Summarize
The above is all about the SpringMVC entry example in this article, I hope it will be helpful to everyone. Interested friends can continue to refer to this site:
Java programming implementation of springMVC simple login example
SpringMVC programming uses the Controller interface to implement controller instance code
Detailed explanation of whether the SpringMVC interceptor implements monitoring session expires
If there are any shortcomings, please leave a message to point it out. Thank you friends for your support for this site.