Introduction to SpringMvc and related interview questions

Posted by The Cat on Thu, 20 Jan 2022 14:52:16 +0100

1. Spring MVC overview

Spring MVC is a WEB layer and control layer framework, which is mainly used to interact with clients and call business logic. Spring MVC is a major component of the spring family. Spring MVC can achieve seamless integration. Features: easy to use and good performance

2. Advantages of spring MVC over Servlet

a. The development and configuration of servlets is relatively troublesome, especially when there are many servlets XML files will be very bloated
b. Each servlet can only handle one function. If multiple functions are needed, multiple servlets need to be developed. There are a large number of servlets in the project, which seems bloated.
c. The process of obtaining request parameters for type conversion and encapsulating data into bean s is cumbersome.
d. Other inconveniences in development, such as garbled code, data format processing, form retrieval

spring MVC details

  1. Components of spring MVC
    a. Front end controller (dispatcher servlet)
    It is essentially a servlet, which is equivalent to a transit station. All accesses will go to this servlet, and then go to the corresponding handler for processing according to the configuration, so as to obtain data and views
    b. Handler mapping
    In essence, it is a mapping relationship, which stores the access path and the corresponding Handler as a mapping relationship, which can be consulted by the front-end controller when necessary.
    c. Handler adapter
    It is essentially an adapter. You can find the corresponding handler to run according to the requirements. After the front-end controller finds the processor mapper and finds the corresponding handler information, the request response and the corresponding handler information are handed over to the processor adapter for processing. After the processor adapter finds the real handler for execution, it returns the result, that is, model and view, to the front-end controller.
    d. View resolver
    It is essentially a mapping relationship, which can map the view name to the real view address. The front-end controller calls the processor to the model and view after adaptation, and transmits the view information to the view parser to get the real view.
    e. view
    In essence, it is to embed the model data returned from the handler processor into the jsp page obtained after view parsing and respond to the client

Generate the core configuration file of SpringMvc

<!--Configure front-end controller-->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--Manually configure the location of the core file-->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:/springmvc.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>*.action</url-pattern>
    </servlet-mapping>
<!--Configure the mapping relationship between the path in the processor mapper and the processor-->
    <bean name="/hello.action" class="cn.tedu.web.Hello"></bean>
    <!--Configure view parser-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
//Create a class to implement the controller interface
public class Hello implements Controller {
    @Override
    public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
        //Create modelAndView
        ModelAndView modelAndView = new ModelAndView();
        //Encapsulate data
        modelAndView.addObject("msg1","hello world");
        modelAndView.addObject("msg2","hello springMVC");
        //Package view
        modelAndView.setViewName("hello");
        //Return modelAndView
        return modelAndView;
    }
}

Spring MVC annotation configuration

SpringMVC It supports annotation configuration, which is more flexible and easy to use than configuration files. It is the mainstream configuration method at present
<context:component-scan base-package="cn.tedu"></context:component-scan>
    <mvc:annotation-driven></mvc:annotation-driven>
    <!--Configure the mapping relationship between the view name and the real page in the view parser-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
<!--Configure front-end controller-->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--Manually configure the location of the core file-->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>*.action</url-pattern>
    </servlet-mapping>
@RequestMapping("/my01")
@Controller
public class Controller01 {
    @RequestMapping("/test01.action")
    public String test01(Model model){
        model.addAttribute("msg","one word one dream");
        return "test01";
    }
}

How spring MVC annotations work

  1. When the server starts, it loads the web XML file, and then load spring MVC. XML by introducing the core configuration file xml
  2. When parsing to package scanning, scan the specified package and resolve the class with @ Conteoller annotation to the processor
  3. If MVC: annotation driven is configured, spring MVC annotations will be parsed
  4. Resolve @ requestMapping (value = "/ test01.action") and save the mapping relationship between the specified address and the current method
  5. When the client sends a request for access, spring MVC looks for the mapping relationship of changing the address, executes the method when it is found, and throws 404 when it is not found

Spring MVC get request parameters

@Controller
public class MyController01 {
    /**
     * Get request parameters: date data processing
     *  By registering the custom type editor, spring MVC supports the processing of custom format request parameters
     *  Here, spring MVC already provides an editor class for Date type, so you can use it directly without writing it yourself
     * http://localhost:8080/SpringMVCDay01_04_Params_war_exploded/my01test09.jsp
     */
    @InitBinder
    public void myInitBinder(ServletRequestDataBinder dataBinder){
        dataBinder.registerCustomEditor(Date.class,new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"),true));

    }

    @RequestMapping("/test09.action")
    public void test09(String name, int age, Date birthday) {
        System.out.println(name);
        System.out.println(age);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String format1 = format.format(birthday);
        System.out.println(format1);

    }

    /**
     * Get request parameters: Chinese garbled code solution
     *     If the server configuration code is utf-8 and the project adopts utf-8, the default request parameters are free of garbled codes
     *     tomcat8 The default code is UTF-8 (can be changed)
     *     tomcat7 And older versions, the default code is iso8859-1 (can be changed)
     *     If the server code is inconsistent with the project code, garbled code will be generated
     *     For POST submission, you can use request SetCharacterEncoding ("UTF-8") to resolve garbled code
     *     However, this line of code is invalid for GET. The request parameters submitted by GET are garbled and can only be solved by manual encoding and decoding
     *     Manual encoding and decoding is also effective for POST submission
     *     springmvc The filter characterencoding filter is provided to help us solve the garbled code
     *     But this filter is essentially request Setcharacterencoding() is also valid only for POST
     *     ,Even if GET is configured, submit the garbled code manually
     *
     */
    @RequestMapping("/test08.action")
    public void test08(HttpServletRequest request) throws UnsupportedEncodingException {
        //POST submission
        //request.setCharacterEncoding("utf-8");
        //String uname = request.getParameter("uname");
        //System.out.println(uname);
        //GET commit
        //String uname = request.getParameter("uname");
        //byte [] data = uname.getBytes("iso8859-1");
        //uname = new String(data,"utf-8");
        //System.out.println(uname);
    }

    //    Get request parameters: processing of multiple request parameters with the same name
    // http://localhost:8080/SpringMVCDay01_04_Params_war_exploded/my01/test07.action?name=tt&love=bb&love=pp&love=zz
    @RequestMapping("/test07.action")
    public void test07(String name,String [] love) {
        //Encapsulated in an array
        System.out.println(name);
        System.out.println(Arrays.asList(love));
    }

    //Get request parameters: automatically encapsulate request parameters to bean processing of complex types
    // http://localhost:8080/SpringMVCDay01_04_Params_war_exploded/my01/test06.action?id=35&name=jj&age=18&addr=cd&dog.name=wd&dog.age=1&dog.cat.name=xx&dog.cat.age=3
    @RequestMapping("/test06.action")
    public void test06(User user) {
        System.out.println(user);
    }

    //Get request parameters: automatically encapsulate request parameters to bean processing of complex types
    // http://localhost:8080/SpringMVCDay01_04_Params_war_exploded/my01/test05.action?id=35&name=jj&age=18&addr=cd&dog.name=wd&dog.age=1
    @RequestMapping("/test05.action")
    public void test05(User user) {
        System.out.println(user);
    }

    //Get request parameters: automatically encapsulate request parameters into bean s
    // http://localhost:8080/SpringMVCDay01_04_Params_war_exploded/my01/test04.action?id=35&name=jj&age=18&addr=cd
    @RequestMapping("/test04.action")
    public void test04(User user) {
        System.out.println(user);

    }

    //Get request parameters: specify parameter assignment through @ RequestParam to solve the assignment problem when the request parameter name and method parameters are inconsistent
    // http://localhost:8080/SpringMVCDay01_04_Params_war_exploded/my01/test03.action?name=yasuo&uage=19
    @RequestMapping("/test03.action")
    public void test03(@RequestParam("name") String username, @RequestParam("uage") int age) {
        System.out.println(username + "~~~~" + age);
    }

    //Get request parameters: get directly
    // http://localhost:8080/SpringMVCDay01_04_Params_war_exploded/my01/test02.action?username=yasuo&age=19
    @RequestMapping("/test02.action")
    public void test02(String username, int age) {
        System.out.println(username + "~~~~" + age);
    }


    //Get request parameters: traditional method
    // http://localhost:8080/SpringMVCDay01_04_Params_war_exploded/my01/test01.action?username=yasuo&age=19
    @RequestMapping("/test01.action")
    public void test01(HttpServletRequest request) {
        String username = request.getParameter("username");
        int age = Integer.parseInt(request.getParameter("age"));
        System.out.println(username + "~~~~" + age);

    }

Topics: Spring Spring MVC