preface
Spring MVC configuration details
Besides Struts, the mainstream Web MVC framework is followed by Spring MVC. Therefore, this is also the mainstream framework that a programmer needs to master. With more choices of frameworks, there will be more feasible solutions to cope with changing demands and businesses. However, in order to flexibly apply Spring MVC to most Web development, it is necessary to master its configuration and principle.
I. Spring MVC environment construction :(Spring 2.5.6 + Hibernate 3.2.0)
1. Import the JAR package
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. Jar, commons-collections-3.1, dom4J-1.6.1. jar, Javassist-3 Jar, slf4J-APi-1.6.1. jar, slF4j-NOp-1.6.4. jar, corresponding database driver JAR package SpringMVC is an MVC framework based on DispatcherServlet. Each Request is first visited by the DispatcherServlet, which is responsible for forwarding each Request to the corresponding Handler. After processing, the Handler returns the corresponding View and Model. The View and Model returned can be left unspecified, that is, Model only, View only, or neither. The DispatcherServlet inherits from HttpServlet, and since SpringMVC is based on DispatcherServlet, let's first configure the DispatcherServlet to manage what we want it to manage. The 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> <! [<servlet-name>]-servlet.xml; [<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> 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> <! -- Specify the directory where the Spring Bean configuration file resides. Default configuration in web-INF directory --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:config/applicationContext.xml</param-value> </context-param>Copy the code
Spring – servlet. XML configuration
The name spring-servlet. XML is derived from the name of the web.xml tag with the value of spring (spring) and the suffix “-servlet”. The corresponding file name is springMVC-servlet.xml.
<? The 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/contex T/spring - the context - 3.0 XSD < / a > "> <! -- Enable spring MVC annotations --> <context:annotation-config /> <! <context:component-scan base-package="controller"></context:component-scan> <! - complete the request and annotate the POJO mapping - > < bean class = "org. Springframework. Web. Servlet. MVC. The annotation. AnnotationMethodHandlerAdapter" / > <! Resolve the path to the page. Prefix: suffix: Suffix - > < bean class = "org. Springframework. Web. Servlet. The InternalResourceViewResolver" p: prefix = "/ JSP/p:" suffix = ". The JSP" /> </beans>Copy the code
The DispatcherServlet makes use of special beans to process Request requests and generate corresponding view returns.
Return of view Controller is responsible for return to a value, what then returns the view, is controlled by the view of the parser, in view of the parser is commonly used in JSP is InternalResourceViewResovler, it will require a prefix and a suffix
In the view parser above, if the Controller returns blog/index, then the view parsed by the view parser is/JSP /blog/index.jsp.
I’m going to talk about Controller.
A class marked with @Controller is a 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 public class TestController {@requestMapping ("test/login.do"); Struts action mapping public String testLogin(@requestParam (value="username")String username, String password, HttpServletRequest Request) {// @requestParam specifies the parameters that must be included in the url mapping (unless the attribute required=false). @RequestParam("username") if (!" admin".equals(username) || !" admin".equals(password)) { return "loginError"; } return "loginSuccess";} return "loginSuccess";} return "loginSuccess";} return "loginSuccess"; } @RequestMapping("/test/login2.do") public ModelAndView testLogin2(String username, String password, // The name of the parameter matches the name of the page control, and the parameter type is automatically converted if (!" admin".equals(username) || !" admin".equals(password) || age < 5) { return new ModelAndView("loginError"); } return new ModelAndView(new RedirectView(".. /index.jsp")); // Return new ModelAndView("redirect:.. /index.jsp"); } @requestmapping ("/test/login3.do") public ModelAndView testLogin3(User User) {RequestMapping("/test/login3.do") public ModelAndView testLogin3(User User) { 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") // Get applicationContext. XML bean id loginService, Private LoginService LoginService; // It is equivalent to the traditional spring injection method to write get and set methods. @requestMapping ("/test/login4.do") public String testLogin4(User User) {if (loginservice.login (User) == false) { return "loginError"; } return "loginSuccess"; }}Copy the code
The above 4 method examples contain different request URLS in one Controller, and one URL can also be used for access. Different access methods can be distinguished by URL parameters, with the code 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 the only *. Do request associated with the Controller public class TestController2 { @requestMapping public String testLogin(String username, String password, int age) {@requestMapping public String testLogin(String username, String password, int age) { If (!" is executed by default. 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) {// Use params method to specify the type of page request. Default is 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"; }}Copy the code
RequestMapping can be a parent Request URL, and RequestMapping can be a child Request URL. The parent Request URL will eventually be pieced together to match the page Request URL. RequestMapping can also be written like this:
package controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @controller@requestMapping ("/test3/*") // Parent Request URL Public class TestController3 {@requestMapping ("login.do") // /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"; }}Copy the code
Common annotations in SpringMVC include @pathVariable, @requestParam, @pathVariable tags on method parameters, which can be used to pass values 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 {
}
Copy the code
In this example, the blogId is marked by @pathvariable as the request PathVariable. If /blog/comment/1.do is requested, the blogId value is 1. RequestParam is also used to pass a value to a parameter, but it takes a value from the request.getParameter(” parameter name “) method.
In the Controller method, if you need the WEB elements HttpServletRequest, HttpServletResponse, and HttpSession, you just need to give the method a corresponding parameter, and SpringMVC will automatically pass it a value when it accesses it. However, it is important to note that an error will be reported if the Session is passed in to the system for the first time because the Session has not yet been generated.
The last
I have compiled a Spring MVC information document, Spring series of family cask, Java systematic information (including Java core knowledge points, interview topics and 20 years of the latest Internet real questions, e-books, etc.) friends who need to pay attention to the public number can be obtained.