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 -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
         <version>${spring.version}</version>
    </dependency>

 

 


b. Configuration (xml labeling):AppConfig class
        @Configurable
        @EnableWebMvc
        @ComponentScan({"day"})

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
 */

@Configuration
@EnableWebMvc
@ComponentScan({"day"})
public class AppConfig {
    /**
     * jsp Parser
     * The purpose of this Bean is to tell Spring MVC where the JSP file you write is located
     * @return
     */
    @Bean 
    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
        resolver.setViewClass(JstlView.class);
        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
SpringMVC: 
    (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 {

    @Override
    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
        ctx.register(AppConfig.class);
        //-- 3. Spring Container nozzle servletContext Application Context Object
        ctx.setServletContext(servletContext);
        //-- 4. Add to Servlet(Add at least one Servlet,SpringMVC Entry to Framework Implementation Servlet)
        ServletRegistration.Dynamic servlet = 
                servletContext.addServlet("dispatcher",new DispatcherServlet(ctx));
        servlet.addMapping("/");
        servlet.setLoadOnStartup(1);
    }
//-- 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;

@Controller
public class HelloController {
    @RequestMapping("/hello")
    public void hello() {
        System.out.println("hello");
    }
    
    @RequestMapping("/hi")
    public void hi() {
        System.out.println("hi");
    }
    
    @RequestMapping("/index")  //-- Represents a mapping path
    public String index(HttpServletRequest request,    HttpServletResponse response) {   //-- Method Name
        String name = request.getParameter("name");
        System.out.println(name);
        try {
            PrintWriter out = response.getWriter();
            out.write("adsfasdfasdf"+name);
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        
        return "index";//-- Name of page
    }
    /**
     * Return string
     * @return
     */
    @RequestMapping("/data")
    @ResponseBody
    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 
     */
    @RequestMapping("/test")
    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;
        
        //Bottom:
//        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:
        http://localhost:8080/hello/name/zhangsan/password/123456
    
Implementation: hello/zhangsan/123456
    @RequestMapping("/hello/{name}/{password}")
    public String getUser(
        @pathVariable("name") String name,
        @pathVariable("password") String password){}
 
    

Get and Post requests:

Method 1:
      @RequestMapping(value="",method=RequestMethod.GET)

    @RequestMapping(value="",method=RequestMethod.Post)
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