A detailed example of Spring MVC annotated @controller @RequestMapping @Resource

Source: Internet
Author: User
<span id="Label3"></p><p><p>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.</p></p><p><p>The spring MVC environment is built: (spring 2.5.6 + Hibernate 3.2.0)</p></p><p><p>1. Jar Package Introduction</p></p><p><p>Spring 2.5.6:spring.jar, spring-webmvc.jar, commons-logging.jar, Cglib-nodep-2.1_3.jar</p></p><p><p>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</p></p><p><p></p></p><p><p>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.</p></p><p><p>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.</p></p><span class="cnblogs_code_copy"><span class="cnblogs_code_copy"></span></span><pre><!--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/spring-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 > <!--specifies the directory where the spring Bean's configuration file Resides. Default configuration in Web-inf directory--><context-param> <param-name>contextConfigLocation</param-name> < Param-value>classpath:config/applicationcontext.xml</param-value></context-param></pre><span class="cnblogs_code_copy"><span class="cnblogs_code_copy"></span></span><p><p></p></p><p><p>Spring-servlet.xml Configuration</p></p><p><p>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.</p></p><span class="cnblogs_code_copy"><span class="cnblogs_code_copy"></span></span><pre><?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:conte xt= "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/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 annotations--<context:annotation-config/> <!--set the jar of the class that uses the Annotations--<context:coMponent-scan base-package= "controller" ></context:component-scan> <!--to Complete the request and annotation Pojo Mapping--<bean CLA ss= "org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/> <!--the Path resolution to the steering PAGE. Prefix: prefix, suffix: Suffix---<bean class= "org.springframework.web.servlet.view.InternalResourceViewResolver" p: prefix= "/jsp/" p:suffix= ". jsp"/></beans></pre><span class="cnblogs_code_copy"><span class="cnblogs_code_copy"></span></span><p><p></p></p><p><p>Dispatcherservlet will use some special beans to process request requests and generate corresponding view Returns.</p></p><p><p>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</p></p><p><p>In the view parser above, if the controller returns blog/index, the view after parsing through the view parser is/jsp/blog/index.jsp.</p></p><p><p></p></p><p><p></p></p><p><p>Mainly talking about Controller.</p></p><p><p>A class that uses @controller to tag is a controller.</p></p><span class="cnblogs_code_copy"><span class="cnblogs_code_copy"></span></span><pre>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//struts-like actionpublic class TestController {@RequestMapping ("test/login.do")//request URL address mapping, similar to strut s action-mapping public string Testlogin (@RequestParam (value= "username") string username, string password, HttpServletRequest request) {//@RequestParam means the parameters that must be included in the requested 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 include 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.) { Request and response do not have to be in the present 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 new Modelandview ("loginError");//manual instantiation Modelandview Complete the jump page (forward), the effect is equivalent to the above method return string} return new Modelandview (new Redirectview (". /index.jsp ")); Redirect to Page//redirect There is also a simple notation//return new Modelandview ("redirect:. /index.jsp "); } @RequestMapping ("/test/login3.do") public modelandview testLogin3 (user user) {//also supports parameter as form object, Act similar to struts Ionform,user does not require any configuration, write directly can be 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"); }<span style="color: #ff0000;"><span style="color: #ff0000;">@Resource (name = "loginservice")//get applicationcontext.xml The Bean's ID is loginservice, and inject</span></span>Private Loginservice loginservice; Equivalent to the spring traditional injection way of writing get and set methods, this advantage is neat and neat, eliminating the need for code @RequestMapping ("/test/login4.do") public String testLogin4 (User u Ser) {if (loginservice.login (user) = = False) {return "loginError"; } return "loginsuccess"; }}</pre><span class="cnblogs_code_copy"><span class="cnblogs_code_copy"></span></span><p><p></p></p><p><p>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:</p></p><span class="cnblogs_code_copy"><span class="cnblogs_code_copy"></span></span><pre>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 only one *. The do request is associated to the Controllerpublic class TestController2 {@RequestMapping public string testlogin (string username, string password, int Age) {//if No parameters are added, the method will be executed by default when The/test2/login.do is Requested. 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 p Assword) {//based on the value of the params parameter method to distinguish different calling methods//you can specify the type of page request mode, default is 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.) {if (!) Admin ". equals (username) | | !" Admin ". equals (password) | | Age < 5) {return "loginError"; } return "loginsuccess"; }}</pre><span class="cnblogs_code_copy"><span class="cnblogs_code_copy"></span></span><p><p></p></p><p><p>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:</p></p><span class="cnblogs_code_copy"><span class="cnblogs_code_copy"></span></span><pre><pre>Package Controller;import Org.springframework.stereotype.controller;import org.springframework.web.bind.annotation.RequestMapping, @Controller @requestmapping ("/test3/*") // Parent request Urlpublic Class TestController3 { @RequestMapping ("login.do") //child request url, stitching is equivalent to/test3/ Login.do public string Testlogin (string username, string password, int.) { if (!) Admin ". equals (username) | | !" Admin ". equals (password) | | Age < 5) { return "loginError"; } return "loginsuccess"; }}</pre></pre><span class="cnblogs_code_copy"><span class="cnblogs_code_copy"></span></span><p><p></p></p><p><p>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</p></p><pre><pre>@RequestMapping (value= "/comment/{blogid}", method=requestmethod.post) public void comment (comment comment,@ pathvariable int blogId, HttpSession session, httpservletresponse Response) throws IOException { }</pre></pre><p><p></p></p><p><p>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.</p></p><p><p>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.</p></p><p><p>A detailed example of Spring MVC annotated @controller @RequestMapping @Resource</p></p></span>

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.