The first Spring MVC program and the first Spring MVC Program

Source: Internet
Author: User

The first Spring MVC program and the first Spring MVC Program

Recently, the company began to use Spring MVC to replace Struts2, and learned how to use Spring MVC. This is the first Spring mvc program, using xml and annotations respectively.

1. Build in xml format

1. To use SpringMVC, configure interceptor and filter in web. xml first.

<? Xml version = "1.0" encoding = "UTF-8"?> <Web-app xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns = "http://java.sun.com/xml/ns/javaee" xmlns: web = "http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi: schemaLocation = "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id = "WebApp_ID" version = "2.5"> <servlet> <! -- The name hello must correspond to the following Spring configuration file --> <servlet-name> hello </servlet-name> <servlet-class> org. springframework. web. servlet. dispatcherServlet </servlet-class> <! -- Set the startup priority --> <load-on-startup> 1 </load-on-startup> </servlet> <servlet-mapping> <servlet-name> hello </servlet -name> <url-pattern>/</url-pattern> </servlet-mapping> <! -- Filter is used to set the encoding --> <filter-name> CharacterFilter </filter-name> <filter-class> org. springframework. web. filter. characterEncodingFilter </filter-class> <init-param> <param-name> enconding </param-name> <param-value> UTF-8 </param-value> </init- param> </filter> <filter-mapping> <filter-name> CharacterFilter </filter-name> <url-pattern>/</url-pattern> </filter-mapping> </web-app>

The servlet name "hello" is not random. It must correspond to the following servlet. The Filter is the encoding Filter.

2. Define springmvc configuration file WEB-INF under hello-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: context = "http://www.springframework.org/schema/context" xmlns: mvc = "http://www.springframework.org/schema/mvc" xsi: schemaLocation = "http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd http://www.springframework.org/schema/beans http: // Www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd "> <! -- Define a/welcome. When a request arrives at/welcome, the interceptor intercepts the request and calls the corresponding controller, perform business processing --> <bean id = "/welcome" class = "com. springmvc. web. welcomeController "> </bean> <! -- Define a view to process the returned view prefix and suffix respectively to define the view corresponding to the page prefix path and suffix path view returned welcome corresponding to the path is/WEB-INF/page/welcome. jsp --> <bean class = "org. springframework. web. servlet. view. internalResourceViewResolver "> <property name =" prefix "value ="/WEB-INF/page/"> </property> <property name =" suffix "value = ". jsp "> </property> </bean> </beans>

3. Custom Controller, inherited from AbstractController

Package com. springmvc. web; import javax. servlet. http. httpServletRequest; import javax. servlet. http. httpServletResponse; import org. springframework. web. servlet. modelAndView; import org. springframework. web. servlet. mvc. abstractController; // defines a controller that inherits AbstractControllerpublic class WelcomeController extends AbstractController {@ Override protected ModelAndView handleRequestInternal (HttpServletRequest arg0, HttpServletResponse arg1) throws Exception {System. out. println ("========="); return new ModelAndView ("welcome ");}}

4. Finally, create welcome. jsp under/WEB-INF/page/, and then access http: // 127.0.0.1: 8080/Spring_Hello/welcome in the browser.

 

2. Compile the first SpringMVC program using annotation (this is the most commonly used method in our daily development)

1. Configure servlet and filter in web. xml, which is the same as the xml method.

2. Specify the annotation scan package and enable the annotation mode in the hello-servlet.xml.

Add two sentences before the interceptor of the original xml

<! -- Configure annotation scan package --> <context: component-scan base-package = "com. springmvc. web"> </context: component-scan> <! -- Enable the annotation mode --> <mvc: annotation-driven/>

3. Configure InternalResourceViewResolver View Control and add prefix and suffix attributes.

4, write HelloController control class (this time do not need to register in the hello-servlet.xml, do not need to inherit from the controller Spring)

package com.springmvc.web;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;@Controllerpublic class HelloController {        @RequestMapping({"/hello","/"})    public String Hello(){        return "Hello";    }        @RequestMapping("/welcome.html")    public String Welcome(){        return "welcome";    }}

Call http: // 127.0.0.1: 8080/Spring_Hello/hello to jump to the hello. jsp page (of course, the hello. jsp file must be created first)

You can call http: // 127.0.0.1: 8080/Spring_Hello/welcome.html to access welcome.jsp.(not the same as the welcomethat was just called, and the suffix of ".html" is not available only)


What is the workflow of spring mvc?

The general process of Spring Web MVC processing Http requests:
Once an Http request arrives, DispatcherSevlet is responsible for distributing the request. DispatcherServlet can be considered as a front-end Controller provided by Spring. All requests are distributed in a unified manner.
Before DispatcherServlet distributes requests to the Spring Controller, it is necessary to use the HandlerMapping provided by Spring to locate the specific Controller. HandlerMapping is an object that can map customer requests to the Controller. In Struts, this ing is done through a struts-config.xml file. Spring provides several implementations for the Controller Interface, such as BeanNameUrlHandlerMapping used by Spring by default. Also, SimpleUrlHandlerMapping and CommonsPathMapHandlerMapping.
Spring Controller processes requests from DispatcherServlet. Spring Controller is similar to struts Action and can accept HttpServletRequest and HttpServletResponse. Spring provides several implementation classes for the Controller Interface, which are located in the org. springframework. web. servlet. mvc package. Since the Controller needs to process the preceding request for concurrent users, when implementing the Controller Interface, it must ensure thread security and be reusable. The Controller processes customer requests, which is consistent with the role played by Struts Action.
Once the Controller processes the customer request, the ModelAndView object is returned to the DispatcherServlet front-end Controller. ModelAndView includes Model and View ). From a macro perspective, DispatcherServlet is the Controller of the entire Web application; from a micro perspective, Controller is the Controller in the Process of processing a single Http request, and ModelAndView is the model and view returned in the Http request process. The View returned by the front-end controller can be the logical name of the View or an object that implements the View Interface. The View object can render the customer response results. The model in ModelAndView can be used for rendering the View. Map Objects can store models.
If the View returned by ModelAndView is only the logical name, you need to use the ViewResoler provided by Spring to search for the View object in the Web application and render the response result to the customer.
DispatcherServlet returns the results rendered by the View object to a client.

What is spring mvc?

Spring3 MVC is a very good MVC Framework. Since its release in version 3.0, more and more teams have chosen Spring3 MVC. Spring3 MVC has a simple structure. The simple structure is beautiful, and it is powerful and flexible, and its performance is excellent.

Spring3 MVC advantages:

1. Spring3 MVC is less difficult to learn than Struts2, and Struts2 does not provide many additional functions. Well, of course this is not the deciding factor.

2. Spring3 MVC can easily write programs with excellent performance. Struts2 must be careful to write programs with excellent performance (referring to the MVC part)

3. Spring3 MVC's flexibility is beyond your imagination. Spring's scalability is well known, and Spring3 MVC certainly will not lag behind, and will not feel any restrictions due to the use of the MVC framework.
 

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.