Spring MVC Configuration Detailed

Source: Internet
Author: User

Now the mainstream web MVC framework, in addition to struts this main force, followed by spring MVC, so this is a programmer need to master the mainstream framework, the framework is more choice, to deal with the changing needs and business, the implementation of the program is more natural. However, to flexibly use spring MVC to deal with most web development, it is necessary to master its configuration and principles.

The spring MVC environment is built: (Spring 2.5.6 + Hibernate 3.2.0)

1. Jar Package Introduction

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, Driver jar packages for 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, corresponding databases

SPRINGMVC is a dispatcherservlet-based MVC framework that each request is first visited by Dispatcherservlet, Dispatcherservlet is responsible for forwarding each request to the corresponding Handler,handler processing and then returning the corresponding view and model, the returned view and model can not be specified, That is, you can return only the model or only the view or none of the returns.

Dispatcherservlet is inherited from the HttpServlet, since SPRINGMVC is based on Dispatcherservlet, then we first configure the Dispatcherservlet, So that it can 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> <!--can customize the location and name of the Servlet.xml configuration file by default to the Web-inf directory with the name [<servlet-name>]-servlet.xml, such as spring-Servlet.xml<init-param> <param-name>contextConfigLocation</param-name> <param-value>/web-inf/sp ring-servlet.xml</param-value>&nbsp; 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's configuration files are located. Default configuration in 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 <servlet-name> tag in the above Web. XML is Spring (<servlet-name>spring</servlet-name >), plus the "-servlet" suffix to form the Spring-servlet.xml file name, if 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 h Ttp://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOPhttp://www.springframework.org/schema/aop/spring-aop-3.0.xsdhttp//Www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx-3.0.xsdhttp//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 annotations--<context:annotation-config/> <!--set the jar of the class that uses the annotations--and <context:com Ponent-scan base- Package= "Controller" ></context:component-scan> <!--to complete the request and annotation Pojo-<beanclass= "Org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/> <!--the path resolution of the steering page. Prefix: prefix, suffix: suffix---<beanclass= "Org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix= "/jsp/" p:suffix= ". JSP"/></ Beans>

Dispatcherservlet will use some special beans to process request requests and generate corresponding view returns.

With regard to the return of the view, the controller is only responsible for returning a value, and then exactly what view is returned, is controlled by the view parser, the common view resolver in the JSP is Internalresourceviewresovler, it will require a prefix and a suffix

In the view parser above, if the controller returns BLOG/INDEX, the view after parsing through the view parser is/jsp/blog/index.jsp.

Mainly talking about controller.

A class that uses @controller to tag is a controller.

 PackageController;Importjavax.servlet.http.HttpServletRequest;ImportOrg.springframework.stereotype.Controller;Importorg.springframework.web.bind.annotation.RequestMapping;ImportOrg.springframework.web.bind.annotation.RequestParam;Importentity. User; @Controller//struts-like action Public classTestController {@RequestMapping ("Test/login.do")//request URL address mapping, similar to struts action-mapping     PublicString Testlogin (@RequestParam (value= "username") string Username, string password, httpservletrequest request) {//@RequestParam refers to the parameters that must be included in the request URL address mapping (unless attribute Required=false)//@RequestParam can be abbreviated as: @RequestParam ("username")        if(!" Admin ". Equals (username) | | !" Admin. Equals (password)) {            return"LoginError";//Jump page Path (default is forward), this path does not need to contain the prefix and suffix configured in the Spring-servlet configuration file        }        return"Loginsuccess"; } @RequestMapping ("/test/login2.do")     PublicModelandview testLogin2 (string Username, string password,intAge ) {        //request and response do not have to be present in the method, if not used can be removed//The name of the parameter is matched to the page control's name, and the parameter type is automatically converted                if(!" Admin ". Equals (username) | | !" Admin ". Equals (password) | | Age < 5) {            return NewModelandview ("LoginError");//Manual instantiation of the Modelandview completes the Jump page (forward), the effect is equivalent to the above method return string        }        return NewModelandview (NewRedirectview (".. /index.jsp "));//Redirect to page//Redirection also has a simple way of writing//return new Modelandview ("redirect:.. /index.jsp ");} @RequestMapping ("/test/login3.do")     Publicmodelandview testLogin3 (user user) {//also supports parameters as form objects, actionform,user like struts do not require any configuration and can be written directlyString username =User.getusername (); String Password=User.getpassword (); intAge =User.getage (); if(!" Admin ". Equals (username) | | !" Admin ". Equals (password) | | Age < 5) {            return NewModelandview ("LoginError"); }        return NewModelandview ("Loginsuccess"); } @Resource (Name= "Loginservice")//gets the ID of the bean in Applicationcontext.xml loginservice, and injects    PrivateLoginservice Loginservice;//equivalent to the spring traditional injection method of write get and set method, this advantage is neat and neat, eliminating the need for code@RequestMapping ("/test/login4.do")     PublicString testLogin4 (user user) {if(loginservice.login (user) = =false) {            return"LoginError"; }        return"Loginsuccess"; }}

The above 4 method example, is a controller contains a different request URL, you can also take a URL to access, through the URL parameter to distinguish access to different methods, the code is as follows:

 PackageController;ImportOrg.springframework.stereotype.Controller;Importorg.springframework.web.bind.annotation.RequestMapping;ImportOrg.springframework.web.bind.annotation.RequestMethod, @Controller @requestmapping ("/test2/login.do")//specifies that a unique *.do request is associated to the controller Public classTestController2 {@RequestMapping PublicString Testlogin (string username, string password,intAge ) {        //If no parameters are added, the method is executed by default when/test2/login.do is requested.                if(!" Admin ". Equals (username) | | !" Admin ". Equals (password) | | Age < 5) {            return"LoginError"; }        return"Loginsuccess"; } @RequestMapping (Params= "Method=1", method=requestmethod.post) Publicstring TestLogin2 (string username, string password) {//distinguish different calling methods based on the value of the params parameter method//You can specify the type of page request mode, by default, GET request                if(!" Admin ". Equals (username) | | !" Admin. Equals (password)) {            return"LoginError"; }        return"Loginsuccess"; } @RequestMapping (Params= "method=2")     PublicString TestLogin3 (string username, string password,intAge ) {        if(!" Admin ". Equals (username) | | !" Admin ". Equals (password) | | Age < 5) {            return"LoginError"; }        return"Loginsuccess"; }}

In fact, requestmapping on the class, can be seen as the parent request URL, and requestmapping on the method can be considered as a child request URL, the parent-child request URL will eventually be spelled together with the page request URL to match, So requestmapping can also write this:

 PackageController;ImportOrg.springframework.stereotype.Controller;Importorg.springframework.web.bind.annotation.RequestMapping, @Controller @requestmapping ("/test3/*")//Parent Request URL Public classTestController3 {@RequestMapping ("Login.do")//Child request URL, after stitching equivalent to/test3/login.do     PublicString Testlogin (string username, string password,intAge ) {        if(!" Admin ". Equals (username) | | !" Admin ". Equals (password) | | Age < 5) {            return"LoginError"; }        return"Loginsuccess"; }}

The annotations used in SPRINGMVC are also @pathvariable, @RequestParam, @PathVariable tag on the parameters of the method, using the parameters that it marks can be used to pass the value of the request path, see the following example

@RequestMapping (value= "/comment/{blogid}", method=requestmethod.post)publicvoid  intthrows  ioexception {    }

In this example, blogID is marked as a request path variable by @pathvariable, and the value of blogID is 1 if the request is/blog/comment/1.do. The same @requestparam is used to pass values to the parameter, but it is the value from the parameter of the request from the beginning, which is equivalent to the Request.getparameter ("parameter name") method.

In the controller's method, if you need web elements httpservletrequest,httpservletresponse and httpsession, you just need to give the method a corresponding parameter, Then the SPRINGMVC will automatically pass the value when it is accessed, but it is important to note that the session will be called when the session is accessed for the first time, because the session has not yet been generated.

Spring MVC Configuration Detailed

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.