In addition to Struts, the main force of mainstream Web MVC frameworks are second to Spring MVC. Therefore, this is also the mainstream framework that a programmer needs to master. With more frameworks, there are naturally more solutions to implement when dealing with changing needs and businesses. However, if you want to flexibly use Spring MVC to deal with most web development, you must master its configuration and principles.
1. Spring MVC environment construction: (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.jar, commons-collections-3.1, dom4j-1.6.1.jar, javassist-3.12.0.GA.jar, jta-1.1.jar, slf4j-api-1.6.1.jar, slf4j-nop-1.6.4.jar, driver jar package for corresponding databases
SpringMVC is an MVC framework based on DispatcherServlet. The first thing that each request accesses is the DispatcherServlet. The DispatcherServlet is responsible for forwarding each Request request to the corresponding Handler. After the Handler processes it, it returns the corresponding view (View) and model (Model). The returned view and model can be not specified, that is, you can only return the Model or only return the View or not.
DispatcherServlet is inherited from HttpServlet. Since SpringMVC is based on DispatcherServlet, let's first configure the DispatcherServlet so that it can manage the content 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> <!-- You can customize the location and name of the servlet.xml configuration file. The default is in the WEB-INF directory, and 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> 默认</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配置--><!-- ====================================== --><listener> <listenerclass> org.springframework.web.context.ContextLoaderListener </listener-class></listener> <!-- Specifies the directory where the Spring Bean's configuration file is located. The default configuration is in the 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 is because the value matched by the <servlet-name> tag in web.xml above is spring (<servlet-name>spring</servlet-name>), and the file name of spring-servlet. If it is 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 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>"> <!-- Enable spring mvc annotation--> <context:annotation-config /> <!-- Set the jar package where the class using the annotation is located--> <context:component-scan base-package="controller"></context:component-scan> <!-- Complete the mapping of request and annotation POJOs--> <bean /> <!-- Path resolution of the turning page. prefix: prefix, suffix: suffix --> <bean p:prefix="/jsp/" p:suffix=".jsp" /></beans>
DispatcherServlet will use some special beans to handle Request requests and generate corresponding view returns.
Regarding the return of a view, the Controller is only responsible for passing back a value, and then what view is returned. It is controlled by the view parser. The commonly used view parser in jsp is InternalResourceViewResovler, which will require a prefix and a suffix.
In the above view parser, if the Controller returns blog/index, then the view parsed through the view parser is /jsp/blog/index.jsp.
Mainly talking about Controller.
A class that uses @Controller for marking is the 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 //Actionpublic class TestController similar to Struts's Action-mapping { @RequestMapping("test/login.do") //Request url address mapping, similar to Struts' action-mapping public String testLogin(@RequestParam(value="username")String username, String password, HttpServletRequest request) { // @RequestParam refers to the parameters that must be contained in the request URL address map (unless the attribute required=false) // @RequestParam can be abbreviated as: @RequestParam("username") if (!"admin".equals(username) || !"admin".equals(password)) { return "loginError"; // Jump the page path (default is forwarding), which does not need to contain the prefix and suffix configured in the spring-servlet configuration file} return "loginSuccess"; } @RequestMapping("/test/login2.do") public ModelAndView testLogin2(String username, String password, int age){ // Request and response do not have to appear in the method. If you cannot use it, you can remove it // The name of the parameter matches the name of the page control, and the parameter type will be automatically converted if (!"admin".equals(username) || !"admin".equals(password) || age < 5) { return new ModelAndView("loginError"); // Manually instantiate ModelAndView to complete the page (forward), the effect is equivalent to the above method to return the string} return new ModelAndView(new RedirectView("../index.jsp")); // Redirect page by redirecting// There is also a simple way to write redirection// return new ModelAndView("redirect:../index.jsp"); } @RequestMapping("/test/login3.do") public ModelAndView testLogin3(User user) { // The parameters are also supported as form objects, similar to Struts' ActionForm. User does not require any configuration, 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") // Get the id of the bean in applicationContext.xml that is loginService, and inject private LoginService loginService; //Equivalent to the traditional spring injection method to write get and set methods. This benefit is concise and neat, eliminating unnecessary code @RequestMapping("/test/login4.do") public String testLogin4(User user) { if (loginService.login(user) == false) { return "loginError"; } return "loginSuccess"; }}The above four method examples are a Controller that contains different request urls. You can also use a url access to distinguish different methods of access through the url parameters. 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 the only *.do request to be associated with the Controllerpublic class TestController2 { @RequestMapping public String testLogin(String username, String password, int age) { // If no parameters are added, the method is executed by default when requesting /test2/login.do 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) { // Different calling methods are distinguished based on the value of params parameter method// You can specify the type of page request method, which is default to 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 can be regarded as the parent Request request url on Class, while RequestMapping can be regarded as the child Request request url on the method. The parent and child request url will eventually be spliced together to match the page request url. Therefore, 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 request urlpublic class TestController3 { @RequestMapping("login.do") // Child request request url, which 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"; }}Common annotations in SpringMVC include @PathVariable, @RequestParam, @PathVariable tagged on the parameters of the method. The parameters marked using it 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 marked as a request path variable by @PathVariable. If the request is /blog/comment/1.do, it means that the value of blogId is 1. Similarly, @RequestParam is also used to pass values to parameters, but it takes the value from the parameter of the request from the beginning, which is equivalent to the request.getParameter("parameter") method.
In the Controller method, if the WEB elements HttpServletRequest, HttpServletResponse and HttpSession are required, you only need to give the method a corresponding parameter, then SpringMVC will automatically pass the value to it during access. However, it should be noted that if the session is called when the first time you access the system, an error will be reported, because the session has not been generated at this time.
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.