Skip to main content

spring mvc 框架搭建及详解


  现在主流的Web MVC框架除了Struts这个主力 外,其次就是Spring MVC了,因此这也是作为一名程序员需要掌握的主流框架,框架选择多了,应对多变的需求和业务时,可实行的方案自然就多了。不过要想灵活运用Spring MVC来应对大多数的Web开发,就必须要掌握它的配置及原理。
  一、Spring MVC环境搭建:(Spring 2.5.6 + Hibernate 3.2.0)
  1. jar包引入
  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、相应数据库的驱动jar包
  2. web.xml配置(部分)
[html] view plaincopy
  1.   
  2.   
  3. <servlet>  
  4.     <servlet-name>spring</servlet-name>  
  5.     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
  6.       
  •   
  • <listener>  
  •     <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
  • </listener>  
  •     
  •   
  •   
  • <context-param>  
  •     <param-name>contextConfigLocation</param-name>  
  •     <param-value>classpath:config/applicationContext.xml</param-value>  
  • </context-param>  
  •   3. spring-servlet.xml配置
      spring-servlet这个名字是因为上面web.xml中标签配的值为spring(spring),再加上“-servlet”后缀而形成的spring-servlet.xml文件名,如果改为springMVC,对应的文件名则为springMVC-servlet.xml。
    [html] view plaincopy
    1. xml version="1.0" encoding="UTF-8"?>  
    2. <beans xmlns="http://www.springframework.org/schema/beans"       
    3.        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"       
    4.         xmlns:context="http://www.springframework.org/schema/context"       
    5.    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd     
    6.        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd     
    7.        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd     
    8.        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>">  
    9.   
    10.       
    11.     <context:annotation-config />  
    12.   
    13.       
    14.     <context:component-scan base-package="controller"></context:component-scan>  
    15.   
    16.       
    17.     <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />  
    18.   
    19.       
    20.     <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/jsp/" p:suffix=".jsp" />  
    21. </beans>  
      4. applicationContext.xml配置
    [html] view plaincopy
    1. xml version="1.0" encoding="UTF-8"?>  
    2. <beans xmlns="http://www.springframework.org/schema/beans"  
    3.         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    4.         xmlns:aop="http://www.springframework.org/schema/aop"  
    5.         xmlns:tx="http://www.springframework.org/schema/tx"  
    6.         xsi:schemaLocation="  
    7.             http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd  
    8.             http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd  
    9.             http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">  
    10.   
    11.       
    12.     <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">  
    13.         <property name="configLocation">  
    14.             <value>classpath:config/hibernate.cfg.xml</value>  
    15.         </property>  
    16.     </bean>  
    17.       
    18.       
    19.     <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">  
    20.         <property name="sessionFactory">  
    21.             <ref local="sessionFactory"/>  
    22.         </property>  
    23.     </bean>  
    24.       
    25.       
    26.     <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/>  
    27.   
    28.      
    29.    <bean id="loginService" class="service.LoginService"></bean>  
    30.   
    31.       
    32.     <bean id="hibernateDao" class="dao.HibernateDao">  
    33.         <property name="sessionFactory" ref="sessionFactory"></property>  
    34.     </bean>  
    35. </beans>  

      二、详解
      Spring MVC与Struts从原理上很相似(都是基于MVC架构),都有一个控制页面请求的Servlet,处理完后跳转页面。看如下代码(注解):
    [java] view plaincopy
    1. package controller;  
    2.   
    3. import javax.servlet.http.HttpServletRequest;  
    4.   
    5. import org.springframework.stereotype.Controller;  
    6. import org.springframework.web.bind.annotation.RequestMapping;  
    7. import org.springframework.web.bind.annotation.RequestParam;  
    8.   
    9. import entity.User;  
    10.   
    11. @Controller  //类似Struts的Action  
    12. public class TestController {  
    13.   
    14.     @RequestMapping("test/login.do")  // 请求url地址映射,类似Struts的action-mapping  
    15.     public String testLogin(@RequestParam(value="username")String username, String password, HttpServletRequest request) {  
    16.         // @RequestParam是指请求url地址映射中必须含有的参数(除非属性required=false)  
    17.         // @RequestParam可简写为:@RequestParam("username")  
    18.   
    19.         if (!"admin".equals(username) || !"admin".equals(password)) {  
    20.             return "loginError"// 跳转页面路径(默认为转发),该路径不需要包含spring-servlet配置文件中配置的前缀和后缀  
    21.         }  
    22.         return "loginSuccess";  
    23.     }  
    24.   
    25.     @RequestMapping("/test/login2.do")  
    26.     public ModelAndView testLogin2(String username, String password, int age){  
    27.         // request和response不必非要出现在方法中,如果用不上的话可以去掉  
    28.         // 参数的名称是与页面控件的name相匹配,参数类型会自动被转换  
    29.           
    30.         if (!"admin".equals(username) || !"admin".equals(password) || age < 5) {  
    31.             return new ModelAndView("loginError"); // 手动实例化ModelAndView完成跳转页面(转发),效果等同于上面的方法返回字符串  
    32.         }  
    33.         return new ModelAndView(new RedirectView("../index.jsp"));  // 采用重定向方式跳转页面  
    34.         // 重定向还有一种简单写法  
    35.         // return new ModelAndView("redirect:../index.jsp");  
    36.     }  
    37.   
    38.     @RequestMapping("/test/login3.do")  
    39.     public ModelAndView testLogin3(User user) {  
    40.         // 同样支持参数为表单对象,类似于Struts的ActionForm,User不需要任何配置,直接写即可  
    41.         String username = user.getUsername();  
    42.         String password = user.getPassword();  
    43.         int age = user.getAge();  
    44.           
    45.         if (!"admin".equals(username) || !"admin".equals(password) || age < 5) {  
    46.             return new ModelAndView("loginError");  
    47.         }  
    48.         return new ModelAndView("loginSuccess");  
    49.     }  
    50.   
    51.     @Resource(name = "loginService")  // 获取applicationContext.xml中bean的id为loginService的,并注入  
    52.     private LoginService loginService;  //等价于spring传统注入方式写get和set方法,这样的好处是简洁工整,省去了不必要得代码  
    53.   
    54.     @RequestMapping("/test/login4.do")  
    55.     public String testLogin4(User user) {  
    56.         if (loginService.login(user) == false) {  
    57.             return "loginError";  
    58.         }  
    59.         return "loginSuccess";  
    60.     }  
    61. }  
      以上4个方法示例,是一个Controller里含有不同的请求url,也可以采用一个url访问,通过url参数来区分访问不同的方法,代码如下:
    [java] view plaincopy
    1. package controller;  
    2.   
    3. import org.springframework.stereotype.Controller;  
    4. import org.springframework.web.bind.annotation.RequestMapping;  
    5. import org.springframework.web.bind.annotation.RequestMethod;  
    6.   
    7. @Controller  
    8. @RequestMapping("/test2/login.do")  // 指定唯一一个*.do请求关联到该Controller  
    9. public class TestController2 {  
    10.       
    11.     @RequestMapping  
    12.     public String testLogin(String username, String password, int age) {  
    13.         // 如果不加任何参数,则在请求/test2/login.do时,便默认执行该方法  
    14.           
    15.         if (!"admin".equals(username) || !"admin".equals(password) || age < 5) {  
    16.             return "loginError";  
    17.         }  
    18.         return "loginSuccess";  
    19.     }  
    20.   
    21.     @RequestMapping(params = "method=1", method=RequestMethod.POST)  
    22.     public String testLogin2(String username, String password) {  
    23.         // 依据params的参数method的值来区分不同的调用方法  
    24.         // 可以指定页面请求方式的类型,默认为get请求  
    25.           
    26.         if (!"admin".equals(username) || !"admin".equals(password)) {  
    27.             return "loginError";  
    28.         }  
    29.         return "loginSuccess";  
    30.     }  
    31.       
    32.     @RequestMapping(params = "method=2")  
    33.     public String testLogin3(String username, String password, int age) {  
    34.         if (!"admin".equals(username) || !"admin".equals(password) || age < 5) {  
    35.             return "loginError";  
    36.         }  
    37.         return "loginSuccess";  
    38.     }  
    39. }  
      其实RequestMapping在Class上,可看做是父Request请求url,而RequestMapping在方法上的可看做是子Request请求url,父子请求url最终会拼起来与页面请求url进行匹配,因此RequestMapping也可以这么写:
    [java] view plaincopy
    1. package controller;  
    2.   
    3. import org.springframework.stereotype.Controller;  
    4. import org.springframework.web.bind.annotation.RequestMapping;  
    5.   
    6. @Controller  
    7. @RequestMapping("/test3/*")  // 父request请求url  
    8. public class TestController3 {  
    9.   
    10.     @RequestMapping("login.do")  // 子request请求url,拼接后等价于/test3/login.do  
    11.     public String testLogin(String username, String password, int age) {  
    12.         if (!"admin".equals(username) || !"admin".equals(password) || age < 5) {  
    13.             return "loginError";  
    14.         }  
    15.         return "loginSuccess";  
    16.     }  
    17. }  

      三、结束语
      掌握以上这些Spring MVC就已经有了很好的基础了,几乎可应对与任何开发,在熟练掌握这些后,便可更深层次的灵活运用的技术,如多种视图技术,例如 Jsp、Velocity、Tiles、iText 和 POI。Spring MVC框架并不知道使用的视图,所以不会强迫您只使用 JSP 技术。

    转自:http://blog.csdn.net/wangpeng047/article/details/6983027

    Comments

    Popular posts from this blog

    Regression Testing

    From  http://www.softwaretestinghelp.com/regression-testing-tools-and-methods/ The selective retesting of a  software  system that has been modified to ensure that any  bugs  have been fixed and that no other previously working functions have failed as a result of the reparations and that newly added features have not created problems with previous versions of the  software . Also referred to as  verification testing , regression testing is initiated after a  programmer  has attempted to fix a recognized problem or has added  source code  to a program that may have inadvertently introduced errors. It is a  quality  control measure to ensure that the newly modified code still complies with its specified requirements and that unmodified code has not been affected by the maintenance activity. What is Regression Software Testing? Regression means retesting the unchanged parts of the application. Test cases are re-execu...

    Spring MVC 3.2 Preview: Introducing Servlet 3, Async Support

    Continuing the Spring 3.0 "simplification series" started by Keith and Chris , I would like to provide a quick overview of simplifications in scheduling and task execution enabled by Spring 3.0. I will be walking through a basic sample application that you can checkout from the spring-samples Subversion repository. It has been designed to be as simple as possible while showcasing both annotation-driven and XML-based approaches to scheduling tasks in Spring 3.0. Let's begin with the annotation-driven approach. You can run it directly via the main() method in AnnotationDemo. If you take a look, you'll see that it's nothing more than a bootstrap for a Spring ApplicationContext: public static void main(String[] args) {      new ClassPathXmlApplicationContext( "config.xml" , AnnotationDemo. class ); } The reason nothing else is necessary is that the ApplicationContext contains an "active" component, which we will...

    How to install JSVC on Linux WidenHome Log | WidenHome Log

    How to install JSVC on Linux WidenHome Log | WidenHome Log In our team, we have a lot of Java standalone applications which should be run as daemon on Unix/Linux system, and we found JSVC is the best choice for us to wrap Java programs to daemons. This article records the steps on how to install JSVC executable on Linux, which is our stage/prod environment. Download JSVC source package First of all, we need to download JSVC source package from this URL: http://commons.apache.org/daemon/download_daemon.cgi , for example, I downloaded commons-daemon-1.0.5-src.tar.gz file. Or, download it via wget: wget -c http://apache.etoak.com/commons/daemon/source/commons-daemon-1.0.5-src.tar.gz Build JSVC executable Unzip the source package and build JSVC executable. chmod 755 commons-daemon-1.0.5-src.tar.gz tar zxvf commons-daemon-1.0.5-src.tar.gz cd commons-daemon-1.0.5-src/src/native/unix Before building the JSVC executable, please make sure you have set JAVA_HOME variable correctly. And make sur...