Introduction to spring MVC

Source: Internet
Author: User

Model-View-controller (MVC) is a software architecture model in software engineering. The software system is divided into three basic parts: Model and view) and controller (Controller ). by stratified development, the software structure is clearer, which improves development efficiency and maintainability and scalability. the MVC framework provided by spring is an implementation of the MVC mode in J2EE Web development. This article describes the use of spring MVC through examples.

Let's take a look at how an HTTP request is processed in spring's MVC framework: (the image is from spring in action)

1. dispatcherservlet is the core of spring MVC. In essence, it is an HTTP servlet that implements the J2EE standard. xml configuration <servlet-mapping> to implement request listening.

<servlet><servlet-name>springTestServlet</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><load-on-startup>2</load-on-startup></servlet><servlet-mapping><servlet-name>springTestServlet</servlet-name><url-pattern>*.do</url-pattern></servlet-mapping>

** All requests ending with. Do are processed by springtestservlet.
2, 3. When the request is received, dispatcherservlet determines according to the configuration of handlermapping (the configuration file of handlermapping is determined by the value of <servlet-Name> by default, here we will read the springTestServlet-servlet.xml to get the configuration information of handlermapping), call the corresponding controller to process the request.

<bean id="simpleUrlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"><property name="mappings"><props><prop key="/login.do">loginController</prop></props></property></bean><bean id="loginController" class="com.test.spring.mvc.contoller.LoginController"><property name="sessionForm"><value>true</value></property><property name="commandName"><value>loginCommand</value></property><property name="commandClass"><value>com.test.spring.mvc.commands.LoginCommand</value></property><property name="authenticationService"><ref bean="authenticationService"/></property><property name="formView"><value>login</value></property><property name="successView"><value>loginDetail</value></property></bean>

** Use login. the request at the end of DO is processed by logincontroller. <property name = "formview"> the logical view name that the controller needs to display when receiving an http get request. In this example, login is displayed. JSP, <property name = "successview"> Configure the logical view name to be displayed when an http post request is received. In this example, It is login. the logic view named logindetail must be displayed when JSP is submitted.

4. After the controller processes the business, a modelandview object is returned.

return new ModelAndView(getSuccessView(),"loginDetail",loginDetail);

5, 6, dispatcherservlet according to the viewresolver configuration (in this example, the configuration in the springTestServlet-servlet.xml file) to the logical view to really display the view, such as JSP.

<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"><property name="viewClass"><value>org.springframework.web.servlet.view.JstlView</value></property><property name="prefix"><value>/jsp/</value></property><property name="suffix"><value>.jsp</value></property></bean>

** The function is to resolve the modleandview returned by the Controller to a specific resource (JSP file). In the preceding example, return New modelandview (getsuccessview (); Follow the viewresolver configuration above, it will be parsed into/JSP/logindetail. JSP. the rule is prefix + the second parameter of modelandview + suffix.

The complete sample code is as follows:

1web. xml:

<?xml version="1.0" encoding="UTF-8"?><web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"><display-name>prjSpring3</display-name><servlet><servlet-name>springTestServlet</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><load-on-startup>2</load-on-startup></servlet><servlet-mapping><servlet-name>springTestServlet</servlet-name><url-pattern>*.do</url-pattern></servlet-mapping><listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener><listener><listener-class>org.springframework.web.context.request.RequestContextListener</listener-class></listener><context-param><param-name>contextConfigLocation</param-name><param-value>/WEB-INF/springTest-services.xml</param-value></context-param><jsp-config><taglib><taglib-uri>/spring</taglib-uri><taglib-location>/WEB-INF/spring.tld</taglib-location></taglib></jsp-config></web-app>

2, the content of the springTestServlet-servlet.xml is as follows:

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"><bean id="simpleUrlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"><property name="mappings"><props><prop key="/login.do">loginController</prop></props></property></bean><bean id="loginController" class="com.test.spring.mvc.contoller.LoginController"><property name="sessionForm"><value>true</value></property><property name="commandName"><value>loginCommand</value></property><property name="commandClass"><value>com.test.spring.mvc.commands.LoginCommand</value></property><property name="authenticationService"><ref bean="authenticationService"/></property><property name="formView"><value>login</value></property><property name="successView"><value>loginDetail</value></property></bean><bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"><property name="viewClass"><value>org.springframework.web.servlet.view.JstlView</value></property><property name="prefix"><value>/jsp/</value></property><property name="suffix"><value>.jsp</value></property></bean></beans>

3, springTest-services.xml content:

<Bean id = "authenticationservice" class = "com. Test. Spring. MVC. Services. authenticationservice"/>

4. Java code:

public class LoginController extends SimpleFormController {org.springframework.web.servlet.DispatcherServlet t;protected ModelAndView onSubmit(Object command) throws Exception{LoginCommand loginCommand = (LoginCommand) command;authenticationService.authenticate(loginCommand);LoginDetail loginDetail = authenticationService.getLoginDetail(loginCommand.getUserId());return new ModelAndView(getSuccessView(),"loginDetail",loginDetail);}private AuthenticationService authenticationService;public AuthenticationService getAuthenticationService() {return authenticationService;}public void setAuthenticationService(AuthenticationService authenticationService) {this.authenticationService = authenticationService;}....public class LoginCommand {private String userId;private String password;....public class LoginDetail {private String userName;public class AuthenticationService {public void authenticate(LoginCommand command) throws Exception{if(command.getUserId()!= null && command.getUserId().equalsIgnoreCase("test") && command.getPassword()!= null && command.getPassword().equalsIgnoreCase("test")){}else{throw new Exception("User id is not authenticated"); }}public LoginDetail getLoginDetail(String userId){return new LoginDetail(userId);}}

5. jsp file: Put it in the JSP folder of web-INF

login.jsp:

In the address bar of the browser, enter http: // localhost: 8080/XXX/login. Do to enter the login. jsp page.

Some expansion points of the Configuration:

1. Specify the file name for the configuration of handlermapping and controller.

<servlet>      <servlet-name>springTestServlet</servlet-name>      <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>      <init-param>          <param-name>contextConfigLocation</param-name>          <param-value>classpath*:/xxx.xml</param-value>      </init-param>      <load-on-startup>1</load-on-startup>  </servlet>  

2. Added support for MVC Annotations:

<?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: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-3.0.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsdhttp://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"><context:annotation-config /><context:component-scan base-package="com.test.spring.mvc.contoller" /><mvc:annotation-driven />@Controllerpublic class AnnotationController {    @RequestMapping("annotation.do")    protected void test(HttpServletRequest request,            HttpServletResponse response) throws Exception{                response.getWriter().println("test Spring MVC annotation");    }

3, The annotation and simpleformcontroller must be configured in the servlet configuration file (in this example, the springTestServlet-servlet.xml) corresponding to dispatcherservlet at the same time:

<Bean class = "org. springframework. web. servlet. MVC. simplecontrollerhandleradapter "/> otherwise, the following exception occurs: javax. servlet. servletexception: No adapter for Handler [COM. test. spring. MVC. contoller. logincontroller @ 6ac615]: Does your handler implement a supported interface like controller? Org. springframework. web. servlet. dispatcherservlet. gethandleradapter (dispatcherservlet. java: 982) Org. springframework. web. servlet. dispatcherservlet. dodispatch (dispatcherservlet. java: 770) Org. springframework. web. servlet. dispatcherservlet. doservice (dispatcherservlet. java: 716) Org. springframework. web. servlet. frameworkservlet. processrequest (frameworkservlet. java: 647) Org. springframework. web. servlet. frameworkservlet. doget (frameworkservlet. java: 552) javax. servlet. HTTP. httpservlet. service (httpservlet. java: 621) javax. servlet. HTTP. httpservlet. service (httpservlet. java: 722)

In the context configuration file of a web application, load by using the following method. contextloaderlistener is a listener that implements servletcontextlistener,
It can access <context-param> and obtain the path of the configuration file. After loading the file, it initializes a webapplicationcontext and places it as the attribute in the servletcontext,
All places that can access servletcontext can access webapplicationcontext.

<listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener><context-param><param-name>contextConfigLocation</param-name><param-value>/WEB-INF/springTest-services.xml,classpath:conf/jndiDSAppcontext.xml</param-value></context-param>

Share a nice link to spring MVC http://www.iteye.com/topic/1119598

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.