spring MVC setup and configuration details

  • 2020-05-27 05:31:20
  • OfStack

Now the mainstream Web MVC framework is in addition to Struts as the main force, Spring MVC is the second, so this is also the mainstream framework that a programmer needs to master. With more choices of frameworks, when dealing with the changing needs and business, there will naturally be more feasible solutions. However, if you want to flexibly use Spring MVC to cope with most Web development, you must master its configuration and principles.

1. Spring MVC environment :(Spring 2.5.6 + Hibernate 3.2.0)

1. Introduction of jar package

Spring 2.5.6: spring.jar, spring-webmvc.jar, commons-logging.jar, cglib-nodep-2.1 _3.jar

Hibernate 3.6.8: hibernate3.jar, hibernate-jpa-2.0-api-1.0.1.Final.jar, antlr-2.7.6.1.jar, commons-collections-3.1, dom4j-1.6.1.jar, javassist-3.12.0.GA.jar, jta-1.1.1.jar, slf4j-api-1.6.1.es jar, slf4j-nop-1.6.4.jar, jar package for the corresponding database driver

SpringMVC is an MVC framework based on DispatcherServlet. The first access of every request is DispatcherServlet, and DispatcherServlet is responsible for forwarding every request of Request to the corresponding Handler. After processing, Handler returns the corresponding view (View) and model (Model), and the returned view and model can be not specified, that is, only Model or View or none.

DispatcherServlet is inherited from HttpServlet, and since SpringMVC is based on DispatcherServlet, let's configure 1 DispatcherServlet to manage what we want it to manage. HttpServlet is declared in the web.xml file.


<!-- Spring MVC configuration  -->
<!-- ====================================== -->
<servlet>
  <servlet-name>spring</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <!--  You can customize it servlet.xml The location and name of the configuration file, by default WEB-INF Under the directory, the name is [<servlet-name>]-servlet.xml , such as spring-servlet.xml
  <init-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/spring-servlet.xml</param-value>&nbsp;  The default 
  </init-param>
  -->
  <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
  <servlet-name>spring</servlet-name>
  <url-pattern>*.do</url-pattern>
</servlet-mapping>
 

<!-- Spring configuration  -->
<!-- ====================================== -->
<listener>
  <listenerclass>
   org.springframework.web.context.ContextLoaderListener
  </listener-class>
</listener>
 

<!--  The specified Spring Bean The directory where the configuration files are located. The default configuration is WEB-INF directory  -->
<context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>classpath:config/applicationContext.xml</param-value>
</context-param>

spring - servlet. xml configuration

The name spring-servlet comes from web.xml above < servlet-name > The value of the tag is spring ( < servlet-name > spring < /servlet-name > ), plus "-servlet" suffix to form spring-servlet. xml file name, if changed to springMVC, the corresponding file name is springMVC-servlet. xml.


<?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:p="http://www.springframework.org/schema/p"   
    xmlns:context="http://www.springframework.org/schema/context"   
  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd  
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd  
    http://www.springframework.org/schema/context <a href="http://www.springframework.org/schema/context/spring-context-3.0.xsd">http://www.springframework.org/schema/context/spring-context-3.0.xsd</a>">

  <!--  To enable the spring mvc  annotations  -->
  <context:annotation-config />

  <!--  Sets the location of the class that USES the annotation jar package  -->
  <context:component-scan base-package="controller"></context:component-scan>

  <!--  Complete the request and comments POJO The mapping of  -->
  <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
  
  <!--  Path resolution to the redirect page. prefix : prefix,  suffix : suffix  -->
  <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/jsp/" p:suffix=".jsp" />
</beans>

DispatcherServlet USES some special bean to process the Request request and generate the corresponding view return.

As for the return of the view, Controller is only responsible for returning one value, and then what view is returned, which is controlled by the view parser. The common view parser in jsp is InternalResourceViewResovler, which requires a prefix and a suffix

In the view above the parser, if Controller returns blog/index, then through the view of the parser parsed view is/jsp blog/index jsp.

Mostly Controller.

One class that USES @Controller is marked with Controller


package controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import entity.User;

@Controller // similar Struts the Action
public class TestController {

  @RequestMapping("test/login.do") //  request url Address mapping, similar Struts the action-mapping
  public String testLogin(@RequestParam(value="username")String username, String password, HttpServletRequest request) {
    // @RequestParam Refers to the request url The parameters that must be included in the address map ( Unless the attribute required=false)
    // @RequestParam It can be abbreviated as: @RequestParam("username")

    if (!"admin".equals(username) || !"admin".equals(password)) {
      return "loginError"; //  The jump page path (forward by default), which need not be included spring-servlet The prefixes and suffixes configured in the configuration file 
    }
    return "loginSuccess";
  }

  @RequestMapping("/test/login2.do")
  public ModelAndView testLogin2(String username, String password, int age){
    // request and response You don't have to be in the method, you can get rid of it if you don't 
    //  The name of the parameter is associated with the page control name Match, and the parameter types are automatically converted 
    
    if (!"admin".equals(username) || !"admin".equals(password) || age < 5) {
      return new ModelAndView("loginError"); //  Manual instantiation ModelAndView To complete the jump page (forward), the effect is the same as the above method to return a string 
    }
    return new ModelAndView(new RedirectView("../index.jsp")); //  Redirect to the page 
    //  Redirection and 1 It's a simple way to write it 
    // return new ModelAndView("redirect:../index.jsp");
  }

  @RequestMapping("/test/login3.do")
  public ModelAndView testLogin3(User user) {
    //  Also supports parameters as form objects, similar to Struts the ActionForm . User No configuration required, just write 
    String username = user.getUsername();
    String password = user.getPassword();
    int age = user.getAge();
    
    if (!"admin".equals(username) || !"admin".equals(password) || age < 5) {
      return new ModelAndView("loginError");
    }
    return new ModelAndView("loginSuccess");
  }

  @Resource(name = "loginService") //  To obtain applicationContext.xml In the bean the id for loginService And inject 
  private LoginService loginService; // Is equivalent to spring Traditional injection writing get and set Method, which has the advantage of being clean and clean, eliminating unnecessary code 

  @RequestMapping("/test/login4.do")
  public String testLogin4(User user) {
    if (loginService.login(user) == false) {
      return "loginError";
    }
    return "loginSuccess";
  }
}

For the above four method examples, one Controller contains different requests for url, and one url can also be used to access different methods through the parameters of url. The code is as follows:


package controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("/test2/login.do") //  Specify only 11 a *.do The request is associated with this Controller
public class TestController2 {
  
  @RequestMapping
  public String testLogin(String username, String password, int age) {
    //  If no parameters are added, the request is made /test2/login.do , the method is executed by default 
    
    if (!"admin".equals(username) || !"admin".equals(password) || age < 5) {
      return "loginError";
    }
    return "loginSuccess";
  }

  @RequestMapping(params = "method=1", method=RequestMethod.POST)
  public String testLogin2(String username, String password) {
    //  On the basis of params The parameters of the method To distinguish between calling methods 
    //  You can specify the type of page request mode, by default get request 
    
    if (!"admin".equals(username) || !"admin".equals(password)) {
      return "loginError";
    }
    return "loginSuccess";
  }
  
  @RequestMapping(params = "method=2")
  public String testLogin3(String username, String password, int age) {
    if (!"admin".equals(username) || !"admin".equals(password) || age < 5) {
      return "loginError";
    }
    return "loginSuccess";
  }
}

In fact, RequestMapping on Class can be regarded as the parent Request requesting url, while RequestMapping on the method can be regarded as the child Request requesting url. The parent and child request url will eventually match the page request url, so RequestMapping can also be written like this:


 package controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/test3/*") //  The father request request url
public class TestController3 {

  @RequestMapping("login.do") //  The child request request url Is equivalent to /test3/login.do
  public String testLogin(String username, String password, int age) {
    if (!"admin".equals(username) || !"admin".equals(password) || age < 5) {
      return "loginError";
    }
    return "loginSuccess";
  }
}

Other annotations commonly used in SpringMVC are @PathVariable, @RequestParam, and @PathVariable, which are marked on the parameters of a method. The parameters marked with this tag can be passed using the request path. See the following example


@RequestMapping(value="/comment/{blogId}", method=RequestMethod.POST)
public void comment(Comment comment,@PathVariable int blogId, HttpSession session, HttpServletResponse response) throws IOException {
  
}

In this example, blogId is @ PathVariable marked as request path variable, if the request is/blog/comment / 1. do says blogId a value of 1. When I was the same @ RequestParam is also used to parameter by value, but it is from the beginning of request parameter values, equivalent to request. getParameter (" parameter name ") method.

In Controller method, if you need HttpServletRequest WEB element, HttpServletResponse and HttpSession, only need to give a corresponding parameters, then at the time of visit SpringMVC will automatically to its value, but it's important to note that when introduced into Session if when is the first access to the system call session complains, because this time session has not been generated.


Related articles: