The configuration method and detailed _jsp programming of Spring MVC framework

Source: Internet
Author: User
Tags aop

Now the mainstream web MVC framework, in addition to the main force struts, followed by spring MVC, so this is a programmer needs to master the mainstream framework, the framework to choose more, to deal with the changing needs and business, the implementation of a more natural solution. But the flexibility to use spring MVC to deal with most web development requires mastering its configuration and rationale.

One, spring MVC Environment Build: (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, 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, the corresponding database driver Jar pack

2. Web.xml Configuration (part)

<!--Spring MVC configuration--> <!--======================================--> <servlet> <servlet-name> Spring</servlet-name> <servlet-class>org.springframework.web.servlet.dispatcherservlet</ Servlet-class> <!--You can customize the location and name of the Servlet.xml configuration file by default to the Web-inf directory, and the name is [<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> default </init-param>--> <load-on-star tup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>spring</
Servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <!--spring configuration--> <!--======================================--> <listener> <listener-class> 
  
 
Org.springframework.web.context.contextloaderlistener</listener-class> </listener><!--Specifies the directory where the spring bean's configuration file resides. Default configuration in the Web-inf directory--> <context-param> <param-name>contextConfigLocation</param-name> < Param-value>classpath:config/applicationcontext.xml</param-value> </context-param>

3. Spring-servlet.xml Configuration

The name Spring-servlet is because the Web.xml <servlet-name> tag in the above value is spring (<servlet-name>spring</servlet-name >), coupled with 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=" 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 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 package where the annotations are used--> <context:component-scan BASe-package= "Controller" ></context:component-scan> <!--complete the mapping of request and annotation Pojo--> <bean class= "org.spring Framework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter "/> <!--the path resolution to the page. Prefix: prefix, suffix: suffix--> <bean class= "Org.springframework.web.servlet.view.InternalResourceViewResolver" P: prefix= "/jsp/" p:suffix= ". jsp"/> </beans>

4. Applicationcontext.xml Configuration

<?xml version= "1.0" encoding= "UTF-8"?> <beans xmlns= "Http://www.springframework.org/schema/beans" Xmlns:xs I= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP" xmlns:tx= " Http://www.springframework.org/schema/tx "xsi:schemalocation=" Http://www.springframework.org/schema/beans http ://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/aop http:// Www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/tx http:// Www.springframework.org/schema/tx/spring-tx-2.5.xsd "> <!--hibernate.cfg.xml configuration data source--> <bean id=" ses Sionfactory "class=" Org.springframework.orm.hibernate3.LocalSessionFactoryBean "> <property name=" Configlocation "> <value>classpath:config/hibernate.cfg.xml</value> </property> </be An> <!--associate transactions with hibernate--> <bean id= "tRansactionmanager "class=" Org.springframework.orm.hibernate3.HibernateTransactionManager "> <property name=" Sessionfactory "> <ref local=" sessionfactory "/> </property> </bean> <!--transactions (note Solution)--> <tx:annotation-driven transaction-manager= "TransactionManager" proxy-target-class= "true"/> <!-- Test service--> <bean id= "Loginservice" class= service. Loginservice "></bean> <!--test DAO--> <bean id=" Hibernatedao "DAO. Hibernatedao "> <property name=" sessionfactory "ref=" sessionfactory "></property> </bean> < /beans>

Second, detailed

Spring MVC is similar in principle to struts (all based on the MVC architecture) and has a servlet that controls page requests, and then jumps the page after processing. Look at the following code (note):

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//Similar to Struts action public class TestController {@RequestMapping ("test/login.do")//Request URL address mapping, a similar to struts Ction-mapping public String Testlogin (@RequestParam (value= "username") string username, string password, HttpServletRequest request) {//@RequestParam refers to the parameters that must be contained in the requested URL address map (unless the property required=false)//@RequestParam can be abbreviated as: @Requ Estparam ("username") if (!) Admin ". Equals (username) | | !" Admin ". Equals (password)) {return" loginerror ";//Jump page path (default is forwarding), this path does not need to include the prefix and suffix configured in Spring-servlet configuration file} re 
  Turn "loginsuccess"; 
    @RequestMapping ("/test/login2.do") Public Modelandview testLogin2 (string Username, string password, int age) { Request and response do not have to be in the current method, if not in the words can be removed 
    Parameter names are matched to the page control's name, and the parameter types are automatically converted to the IF (!) Admin ". Equals (username) | | !" Admin ". Equals (password) | | Age < 5) {return new Modelandview ("Loginerror");//manually instantiate Modelandview complete jump page (forward), the effect is equivalent to the above method returns the string} RET Urn New Modelandview (new Redirectview ("...). /index.jsp ")); Redirect to page//redirect There is also a simple writing//return new Modelandview ("redirect: ... 
  /index.jsp "); The @RequestMapping ("/test/login3.do") public modelandview testLogin3 (user user) {//is also supporting the parameter as a Form object, similar to the act of struts 
    Ionform,user does not require any configuration, direct write 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 to New Modelandview ("loginsuccess"); @Resource (name = "Loginservice")//Get the ID of the bean in Applicationcontext.xml as Loginservice and inject private Loginservice logi Nservice; is equivalent to the spring traditional injection method of write get and set methods,The advantage is simplicity and neatness, eliminating the need for code @RequestMapping ("/test/login4.do") public String testLogin4 (user user) {if Loginservic 
    E.login (user) = False) {return "Loginerror"; 
  Return to "loginsuccess"; } 
}

The above 4 method examples, is a controller contains different request URL, also can use a URL to access, through the URL parameter to differentiate access to different methods, the code is as follows:

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 that only one *.do request is associated to the Controller public class TestController2 {@Reque Stmapping public string Testlogin (string username, string password, int age) {//If no arguments are added, the default is when the/test2/login.do is requested Executes the method if (!) Admin ". Equals (username) | | !" Admin ". Equals (password) | | 
    Age < 5} {return "Loginerror"; 
  Return to "loginsuccess";  @RequestMapping (params = "method=1", method=requestmethod.post) public string testLogin2 (string username, string Password) {//depending on the value of the parameter method of params to distinguish between different invocation methods//You can specify the type of page request, default to GET request if (!) Admin ". Equals (username) | | !" 
    Admin ". Equals (password)) {return" Loginerror "; 
  Return to "loginsuccess"; } @RequestMapping (params = "method=2") pUblic string testLogin3 (string username, string password, int age) {if (!) Admin ". Equals (username) | | !" Admin ". Equals (password) | | 
    Age < 5} {return "Loginerror"; 
  Return to "loginsuccess"; } 
}

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

Package controller; 
 
Import Org.springframework.stereotype.Controller; 
Import org.springframework.web.bind.annotation.RequestMapping; 
 
@Controller
@RequestMapping ("/test3/*")//Parent Request URL Public 
class TestController3 { 
 
  @RequestMapping ("login.do")//Child request URL, which is equivalent to/test3/login.do public 
  String Testlogin (string Username, string password, int Age) { 
    if (!) Admin ". Equals (username) | | !" Admin ". Equals (password) | | Age < 5) {return 
      "Loginerror"; 
    } 
    return "loginsuccess"; 
  } 

Third, concluding remarks

Mastering these spring MVC is a good foundation for almost any development, a technology that can be used more flexibly when mastered, such as multiple view technologies such as JSP, Velocity, Tiles, IText, and POI. The Spring MVC Framework does not know the views used, so you will not be forced to use only JSP technology.

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.