Spring MVC based on Maven

Keywords: Java Spring JSP Tomcat

Spring MVC

He's based on MVC design patterns and Spring's further encapsulation of Servlet s
  MVC: Model  View  Controller

How do I use Spring MVC?(Spring and Spring MVC integration)
Import SpringMVC.jar with a. pom.xml


<!-- Spring 5 and SpringMVC -->



b. Configuration (xml labeling):AppConfig class

package day;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.JstlView;
import org.springframework.web.servlet.view.UrlBasedViewResolver;

 * Annotation-based Configuration Class (JavaConfig Configuration)
 * @author Zhang Ze

public class AppConfig {
     * jsp Parser
     * The purpose of this Bean is to tell Spring MVC where the JSP file you write is located
     * @return
    public UrlBasedViewResolver setupViewResolver() {
        UrlBasedViewResolver resolver = new UrlBasedViewResolver();
        resolver.setPrefix("/WEB-INF/");//-- Location protected from direct access
        resolver.setSuffix(".jsp"); //-- jsp File suffix, you omit the suffix when you write the page
        return resolver;
    In other words: we need to configure that Servlet first and instantiate it when the server starts
    (1)tomcat At startup, the SpringMVC framework wrote the listener ContextListener(ServletContextListener)
    (2)Instantiate this core Servlet in ServletContextListener
    (3)This Serlet intercepts all requests
    (4)After intercepting the request, forward the path to the corresponding Controller after obtaining the request
    (5)Controller Processing the corresponding request
Idea: All beans need to be managed in Spring containers to implement Interface-oriented programming
Tomcat Will there be a Spring container after startup?
When Tomcat starts, we instantiate a Spring container.Then put it in the ServletContext
    (1)When Tomcat starts, instantiate a Spring container into the ServletContext object
    (2)And instantiate that core Servlet in the ServletContext
    (3)And the Servlet intercepts all requests



WebInitializer class: The onStartup method of this class is called to initialize work when the web container starts up: Spring container and Spring MVC framework


package day;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

 * Tomcat Classes that detect whether there is a WebApplicationInitializer interface at startup
 * If this class is detected, it is instantiated and its onStartup method is called
 * @author Zhang Ze
public class WebInitializer implements WebApplicationInitializer {

    public void onStartup(ServletContext servletContext) 
            throws ServletException {
        System.out.println("startup invoker the method");
        //--  1. structure Spring container
        AnnotationConfigWebApplicationContext ctx = 
                new AnnotationConfigWebApplicationContext();
        //-- 2. Spring Container Load Configuration
        //-- 3. Spring Container nozzle servletContext Application Context Object
        //-- 4. Add to Servlet(Add at least one Servlet,SpringMVC Entry to Framework Implementation Servlet)
        ServletRegistration.Dynamic servlet = 
                servletContext.addServlet("dispatcher",new DispatcherServlet(ctx));
//-- You want to use it Spring,Just have it Spring Container example,
//-- You want to use it SpringMVC You have to configure DispatcherServlet Take an example,
//-- And put these two things in ServletContext In the object, why?
//-- Because they're both heavyweight



* Call Class


package day;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;

import day.entity.User;

public class HelloController {
    public void hello() {
    public void hi() {
    @RequestMapping("/index")  //-- Represents a mapping path
    public String index(HttpServletRequest request,    HttpServletResponse response) {   //-- Method Name
        String name = request.getParameter("name");
        try {
            PrintWriter out = response.getWriter();
        } catch (IOException e) {
        return "index";//-- Name of page
     * Return string
     * @return
    public String aaa() {
        List<User> users = new ArrayList<User>();
        users.add(new User("zz",15));
        users.add(new User("zz",15));
        users.add(new User("zz",15));
        //-- 2. use alibaba have to fastJson tool
        String jsonStr = JSON.toJSONString(users);
        return jsonStr;
        //return "[{'name':zz,'age':15}]";
     * Return to page and pass data to page
     * @return 
    public ModelAndView bbb(HttpServletRequest request,HttpServletResponse response) {
        ModelAndView mv = new ModelAndView("test");
        //-- do something query data
        mv.addObject("message", "Pagoda will stop river monster");
        return mv;
//        request.setAttribute("message", "hello");
//        try {
//            request.getRequestDispatcher("/WEB-INF/test.jsp").forward(request, response);
//        } catch (ServletException e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        } catch (IOException e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        }



Other small points of knowledge:

Previous access connection: URL: http://localhost:8080/hello?Name=xxx&word=122
RestFul Form Interface:
Implementation: hello/zhangsan/123456
    public String getUser(
        @pathVariable("name") String name,
        @pathVariable("password") String password){}

Get and Post requests:

Method 1:

Method 2:
Get request: @GetMapping(") equals: @RequestMapping (value="), method=RequestMethod.GET)
Post request: @PostMapping ("")

Posted by ptraffick on Thu, 07 Nov 2019 09:44:28 -0800