"Springmvc" Springmvc introduction and the first HelloWorld

Source: Internet
Author: User

Lin Bingwen Evankaka Original works. Reprint please specify the source Http://blog.csdn.net/evankaka

I. SPRINGMVC Overview and Fundamentals

Spring Web MVC is a lightweight web framework that implements the request-driven type of the Web MVC design pattern based on Java, that is, the idea of using the MVC architecture pattern, decoupling the WEB layer from responsibility, and based on the request-driven approach is to use the request-response model, The purpose of the framework is to help us simplify our development, and Spring Web MVC also simplifies our daily web development.

There is also a component-based, event-driven web framework that is not covered here, such as tapestry, JSF, and so on.

Spring Web MVC is also an implementation of service-to-worker mode, but is optimized. The front controller is an DispatcherServlet; application controller that actually splits the processor mapper (Handler Mapping) for processor management and view Resolver for view management; The page Controller/action/processor is the Controller interface (contains ModelAndView handleRequest(request, response) only (can also be any Pojo class), support localization (Locale) parsing, topic (Theme) parsing, and file upload, etc., providing very flexible data validation, formatting, and data binding mechanisms, and providing a powerful contract-more contractual programming support than the configuration (customary precedence principle).

The Spring Web MVC Framework provides a model-view-controller architecture and components that you can use to develop flexible, loosely-coupled web applications. The MVC pattern causes different aspects of the decoupled application (input logic, business logic, and UI logic), while providing loose coupling between these elements.

    • The model encapsulates the data of the application and the Pojo that are typically made up of them.

    • The view is responsible for rendering the model data and generally the HTML output it generates, which the client's browser can interpret.

    • The controller is responsible for processing the user's request, establishing the appropriate model, and passing it on to the view rendering.

1.1, Dispatcherservlet

Spring's web Model-View-Controller (MVC) framework is designed around the dispatcherservlet that handles all HTTP requests and responses. The Dispatcherservlet request processing flow for the Spring Web MVC framework is described in the following example:



The following is an event sequence that corresponds to an incoming HTTP request to Dispatcherservlet:

    1. After receiving the HTTP request, Dispatcherservlet consults the handlermapping to invoke the appropriate controller.

    2. The Controller accepts the request and invokes the appropriate service method based on the use of the Get or post method. The service method sets the model data based on the defined business logic and returns the view name to Dispatcherservlet.

    3. Dispatcherservlet will need help for the viewresolver from pickup to the view defined by the request.

    4. Once the view is finalized, Dispatcherservlet passes the model data as the view that is ultimately rendered on the browser.

All of the above parts, namely handlermapping, controller and view resolver webapplicationcontext sections are pure applicationcontext necessary for some additional functional extensions of the Web application.

1.2, the required configuration

You need to map the required dispatcherservlet processing by using a URL mapping request in the Web. xml file. The following is an example of an example of declaring and mapping Helloweb Dispatcherservlet:

<?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_3_0.xsd" xsi: schemalocation= "Http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id= "Webapp_ ID "version=" 3.0 "><!--SPRINGMVC Front-end controller--><servlet><servlet-name>hello</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>< load-on-startup>1</load-on-startup></servlet><!--Spring MVC configuration file ends--><!--intercept settings-->< servlet-mapping><servlet-name>hello</servlet-name><!--intercept all requests by SPRINGMVC--><url-pattern >/</url-pattern></servlet-mapping></web-app>

The Web. xml file will be saved in the Webcontent/web-inf directory of your website application. in the Helloweb initialization of Dispatcherservlet, the framework will attempt to get from a named [Servlet-name]-servlet.xml located in the application Webcontent/web-inf The catalog file loads the application context. In this case our file will be helloweb-servlet.xml.

The next,<servlet-mapping> tag indicates that the URL will be dispatcherservlet processed. It's all used here. The JSP end HTTP request will be processed by Dispatcherservlet's helloweb. If you do not want to use the default file name of [Servlet-name]-servlet.xml and default location of Webcontent/web-inf. the name and location of the file defined in the Web. xml file is as follows:

<?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_3_0.xsd" xsi: schemalocation= "Http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id= "Webapp_ ID "version=" 3.0 "><!--SPRINGMVC Front-end controller--><servlet><servlet-name>hello</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><!-- Set the controller XML file of your own definition--><init-param><param-name>contextconfiglocation</param-name>< param-value>/web-inf/hello-servlet.xml</param-value></init-param><load-on-startup>1</ load-on-startup></servlet><!--Spring MVC configuration file ends--><!--intercept settings--><servlet-mapping>< servlet-name>hello</servlet-name><!--intercept all requests by SPRINGMVC--><url-pattern>/</url-pattern ></servlet-mapping>&Lt;/web-app> 

Now, let's examine the desired configuration of the Helloweb-servlet.xml file, placed in the Webcontent/web-inf directory of the WEB application:

Here are the key points about the Hello-servlet.xml file:

<beans xmlns= "Http://www.springframework.org/schema/beans" xmlns:context= "http://www.springframework.org/ Schema/context "xmlns:xsi=" http://www.w3.org/2001/XMLSchema-instance "xmlns:p=" http://www.springframework.org/ schema/p "xsi:schemalocation=" Http://www.springframework.org/schema/mvc HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/MV C/spring-mvc-3.0.xsd Http://www.springframework.org/schema/beans Http://www.springframework.org/schem A/beans/spring-beans-3.0.xsd Http://www.springframework.org/schema/context HTTP://WWW.SPRINGFRAMEWORK.O Rg/schema/context/spring-context-3.0.xsd "><!--convert classes marked with @controller annotations to Bean--><context:component-scan Base-package= "COM.MUCFC"/><!--start the annotation feature of spring MVC, complete the mapping of requests and annotations Pojo--><bean class= " Org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter "/><!--The resolution of the name of the model view, That is, add the prefix--><bean class= "Org.springframework.web.servlet.view.InternalResourceViewResolver" to the Model view name P:prefix= "/web-inf/views/" p:suffix= ". JSP"/></beans> 

    • [The Servlet-name]-servlet.xml file will be used to create the defined bean, overwriting the definition of the bean with the same name in the global scope.

    • <context:component-scan...> tags will use the annotation scanning feature that launches spring MVC, allowing for use like @Controller and using @requestmapping annotations.

    • Use Internalresourceviewresolver to have a rule defined to resolve the view name. According to the rules defined above, the logical view named Hello is delegated to a view implementation located in/web-inf/jsp/hello.jsp.

1.3. Define the controller

The Dispatcherservlet delegate request is sent to the controller to perform its function specific to it. Note @controller represents a specific class that provides the role of a controller. Note @requestmapping is used to map URLs to any class or to a specific processing method.

Package Com.mucfc;import Org.springframework.stereotype.Controller;  Import Org.springframework.ui.ModelMap;  Import org.springframework.web.bind.annotation.RequestMapping;  Import Org.springframework.web.bind.annotation.RequestMethod;  @Controller public  class Helloworldcontroller {      @RequestMapping (value= "/hello") public      String Printwelcome (Modelmap model) {          Model.addattribute ("message", "Spring 3 MVC Hello World");          return "Hello";      }  }

The annotation @controller class is defined as a spring MVC controller. Here, using the @requestmapping for the first time indicates that all the processing methods on the controller are relative to the/hello path. The next callout uses @requestmapping (method = Requestmethod.get) to declare the Printhello () method as the default service method for the controller to handle HTTP GET requests. You can define another method to handle post requests for the same URL.

Can be written in another form above, you can use @requestmapping to add additional attributes such as the following control:

Package Com.mucfc;import Org.springframework.stereotype.Controller;  Import Org.springframework.ui.ModelMap;  Import org.springframework.web.bind.annotation.RequestMapping;  Import Org.springframework.web.bind.annotation.RequestMethod;  @Controller public  class Helloworldcontroller {      @RequestMapping (value= "/hello", Method=requestmethod.get, params= "userid") Public      String printwelcome (modelmap model,string userid) {          model.addattribute ("message", " Spring 3 MVC Hello World ");          return "Hello";      }  }

The Value property indicates the URL to which the processing method is mapped and the method property defines the methods of the service to handle HTTP GET requests. There are a few important points to note about the controllers defined above:

    • The service methods within the required business logic will be defined. You can call this method in another method as required.

    • Based on the defined business logic, a model is created in this method. You can set the properties of different models and these properties will be accessed by the view presented by the final result. This example creates a model with its own property, "message".

    • The defined service method can return a string that contains the name to be used to render the model view. This example returns "Hello" as the logical view name.

1.4. Create a JSP view

Spring MVC supports multiple types of views with different presentation techniques. These include: Jsp,html,pdf,excel,xml,velocity,xslt,json,atom and RSS feeds, jasperreports, etc., but most commonly used jstl JSP templates. So, let's write a/web-inf/hello/hello.jsp simple Hello view:

Here, ${message} is a property that we have built inside the controller. You can display multiple properties in the view.
<%@ page language= "java" contenttype= "text/html; charset=gb2312 "    pageencoding=" gb2312 "%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >


Second, the first SPRINGMVC procedure

Project free Download

1. Create a new WEB project in Ecliose, first import the required packages into the \webcontent\web-inf\lib


2. Configure 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_3_0.xsd" xsi: schemalocation= "Http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id= "Webapp_ ID "version=" 3.0 "><!--SPRINGMVC Front-end controller--><servlet><servlet-name>hello</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><!-- Set the controller XML file of your own definition--><init-param><param-name>contextconfiglocation</param-name>< param-value>/web-inf/hello-servlet.xml</param-value></init-param><load-on-startup>1</ load-on-startup></servlet><!--Spring MVC configuration file ends--><!--intercept settings--><servlet-mapping>< servlet-name>hello</servlet-name><!--intercept all requests by SPRINGMVC--><url-pattern>/</url-pattern ></servlet-mapping>&Lt;/web-app> 

3, Configuration hello-servlet.xml:

<beans xmlns= "Http://www.springframework.org/schema/beans" xmlns:context= "http://www.springframework.org/ Schema/context "xmlns:xsi=" http://www.w3.org/2001/XMLSchema-instance "xmlns:p=" http://www.springframework.org/ schema/p "xsi:schemalocation=" Http://www.springframework.org/schema/mvc HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/MV C/spring-mvc-3.0.xsd Http://www.springframework.org/schema/beans Http://www.springframework.org/schem A/beans/spring-beans-3.0.xsd Http://www.springframework.org/schema/context HTTP://WWW.SPRINGFRAMEWORK.O Rg/schema/context/spring-context-3.0.xsd "><!--convert classes marked with @controller annotations to Bean--><context:component-scan Base-package= "COM.MUCFC"/><!--start the annotation feature of spring MVC, complete the mapping of requests and annotations Pojo--><bean class= " Org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter "/><!--The resolution of the name of the model view, That is, add the prefix--><bean class= "Org.springframework.web.servlet.view.InternalResourceViewResolver" to the Model view name P:prefix= "/web-inf/views/" p:suffix= ". JSP"/></beans> 

4. Configure the Controller:

Package Com.mucfc;import Org.springframework.stereotype.Controller;  Import Org.springframework.ui.ModelMap;  Import org.springframework.web.bind.annotation.RequestMapping;  Import Org.springframework.web.bind.annotation.RequestMethod;  @Controller public  class Helloworldcontroller {      @RequestMapping (value= "/hello", Method=requestmethod.get, params= "userid") Public      String printwelcome (modelmap model,string userid) {          model.addattribute ("message", " Spring 3 MVC Hello World ");          return "Hello";      }  }

5, Web-inf Create a new Views folder, and then create a new hello.jsp

<%@ page language= "java" contenttype= "text/html; charset=gb2312 "    pageencoding=" gb2312 "%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >

6, the entire project directory is as follows:

7, direct operation, input Http://localhost:8080/SpringMVCLearningChapter1/hello in the browser

The results are as follows:

Project free Download


Lin Bingwen Evankaka Original works. Reprint please specify the source Http://blog.csdn.net/evankaka




"Springmvc" Springmvc introduction and the first HelloWorld

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.