Spring MVC environment construction

Keywords: xml Spring Java JSP

Spring MVC execution principle
When the page sends the request, the controller finds the corresponding mapping (method) according to the request. After the function is executed, the controller jumps to the corresponding page and presents the processing result after the view parser processing according to the returned result.

Environmental construction steps
1. Import related jar package
Baidu cloud takes it by itself Build the jar package needed by spring MVC

2. Configuring dispatchServlet in web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
    xmlns="http://java.sun.com/xml/ns/javaee" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

    <!-- To configure DispatcherServlet -->
    <servlet>
        <servlet-name>springDispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc.xml</param-value>          
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springDispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>

3. Write spring mvc.xml file and configure view parser

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://www.springframework.org/schema/beans" 
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd 
                        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd 
                        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd ">

    <!-- Automatic scanning -->
    <context:component-scan base-package="com.xiao.leave"></context:component-scan>

    <!-- Configure view resolver -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/view/"></property>
        <property name="suffix" value=".jsp"/>
    </bean>


</beans>

4. Write controller and related pages

import java.util.Arrays;
import java.util.Date;
import java.util.Map;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

import com.xiao.leave.entities.Students;

@SessionAttributes(value={"stu"},types={String.class})
@Controller
@RequestMapping("/login")
public class LonginAction {
    private static final String SUCCESS = "success";



    @RequestMapping("/testSessionAttribute")
    public String testSessionAttribute(Map<String, Object> map){
        Students stu = new Students("xiao", 24, "123456");
        map.put("stu", stu);
        map.put("addr", "Beijing");

        return SUCCESS;
    }

    @RequestMapping("/testModelAndView")
    public ModelAndView testModelAndView(){
        String viewName = SUCCESS;
        ModelAndView modelandview = new ModelAndView(viewName);
        modelandview.addObject("time",new Date());

        return modelandview;
    }

    @RequestMapping("/testMap")
    public String testMap(Map<String, Object> map){
        map.put("names", Arrays.asList("tom", "mike", "lily"));
        System.out.println(map.getClass().getName());

        return SUCCESS;
    }

    @RequestMapping("/testPojo")
    public String testPojo(Students stu){
        System.out.println("Student:" + stu);

        return SUCCESS;
    }

    @RequestMapping("testRequestParam")
    public String testRequestParam(@RequestParam(value="username") String un, 
                                    @RequestParam(value="age",required=false,defaultValue="0") int age){
        /**
         * RequestParam Mapping request parameters
         * value:Parameter name of the request parameter
         */
        System.out.println("testRequestParam: username = " + un + ", age = " + age);

        return SUCCESS;
    }

    @RequestMapping("/testPathVariable/{id}")
    public String testPathVariable(@PathVariable("id")Integer id){
        //PathVariable can map placeholders in the url to the parameters of the target method
        System.out.println("testPathVariable  ==" + id);

        return SUCCESS;
    }

    @RequestMapping("testAntPath/*/aa")
    public String testAntPath(){
        // * Match any character,? Match one character, * * match multiple paths

        System.out.println("testAntPath");

        return SUCCESS;
    }

    @RequestMapping(value="/testparaAndMethod", params={"username","age!=10"}, method=RequestMethod.POST)
    public String testparaAndMethod(){
        /**
         * value Map representing the request path
         * params Represents the parameter passed in;! =Indicates that there is a parameter, but it is not equal to a value,
         * method Indicate request mode
         */

        System.out.println("testparaAndMethod");

        return SUCCESS;
    }

    @RequestMapping("/helloworld")
    public String helloworld(){
        System.out.println("helloworld");

        return SUCCESS;
    }

}

success.jsp

<body>
    <h2>Congratulations! Login successfully</h2>

    <h4>names: ${requestScope.names} </h4>

    <h4>time: ${requestScope.time} </h4>

    <h4>request stu: ${requestScope.stu} </h4>

    <h4>session stu: ${sessionScope.stu} </h4>

    <h4>request addr: ${requestScope.addr} </h4>

    <h4>session addr: ${sessionScope.addr} </h4>


  </body>

login.jsp

  <body>

    <a href="login/testSessionAttribute">testSessionAttribute</a><br/>

    <a href="login/testModelAndView">testModelAndView</a><br/>

    <a href="login/testMap">testMap</a><br/>

    <form action="login/testPojo">
        Full name:<input type="text" name="sname"><br/>
        Age:<input type="text" name="sage"><br/>
        Mobile phone:<input type="text" name="stel"><br/>
        Province:<input type="text" name="saddr.province"><br/>
        City:<input type="text" name="saddr.city"><br/>

        <input type="submit" value="Submission">
    </form>

    <a href="login/testRequestParam?username=xiao&age=24">testRequestParam</a><br>

    <a href="login/testPathVariable/1">testPathVariable</a><br/>

    <a href="login/testAntPath/hello/aa">testAntPath</a><br/>

    <form action="login/testparaAndMethod?username=xiao&age=11" method="post">
        <input type="submit" value="Sign in"/>
    </form>

    <a href="login/helloworld">hello world</a><br/>
  </body>
</html>

Click the link in login.jsp to successfully jump to the success.jsp page, which means that the environment is built successfully! (testPojo needs to write a pojo and add the get set toString method)

The above is my understanding after reading the relevant courses. If there is something wrong, please correct it

Posted by andybrooke on Wed, 01 Apr 2020 20:24:39 -0700