springMVC框架搭建(转)-程序员宅基地

技术标签: java  测试  web.xml  

原文:http://www.open-open.com/lib/view/open1338338587698.html

现在主流的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配置(部分)

01    <!-- Spring MVC配置 -->
02    <!-- ====================================== -->
03    <servlet>
04        <servlet-name>spring</servlet-name>
05        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
06        <!-- 可以自定义servlet.xml配置文件的位置和名称,默认为WEB-INF目录下,名称为[<servlet-name>]-servlet.xml,如spring-servlet.xml
07        <init-param>
08            <param-name>contextConfigLocation</param-name>
09            <param-value>/WEB-INF/spring-servlet.xml</param-value>  默认
10        </init-param>
11        -->
12        <load-on-startup>1</load-on-startup>
13    </servlet>
14     
15    <servlet-mapping>
16        <servlet-name>spring</servlet-name>
17        <url-pattern>*.do</url-pattern>
18    </servlet-mapping>
19       
20     
21     
22    <!-- Spring配置 -->
23    <!-- ====================================== -->
24    <listener>
25        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
26    </listener>
27       
28     
29    <!-- 指定Spring Bean的配置文件所在目录。默认配置在WEB-INF目录下 -->
30    <context-param>
31        <param-name>contextConfigLocation</param-name>
32        <param-value>classpath:config/applicationContext.xml</param-value>
33    </context-param>
 

 3. spring-servlet.xml配置

  spring-servlet这个名字是因为上面web.xml中<servlet-name>标签配的值为 spring(<servlet-name>spring</servlet-name>),再加上“-servlet”后缀而 形成的spring-servlet.xml文件名,如果改为springMVC,对应的文件名则为springMVC-servlet.xml。

01    <?xml version="1.0" encoding="UTF-8"?>
02    <beans xmlns="http://www.springframework.org/schema/beans"    
03           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"    
04            xmlns:context="http://www.springframework.org/schema/context"    
05       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
06           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd  
07           http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd  
08           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>">
09     
10        <!-- 启用spring mvc 注解 -->
11        <context:annotation-config />
12     
13        <!-- 设置使用注解的类所在的jar包 -->
14        <context:component-scan base-package="controller"></context:component-scan>
15     
16        <!-- 完成请求和注解POJO的映射 -->
17        <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
18     
19        <!-- 对转向页面的路径解析。prefix:前缀, suffix:后缀 -->
20        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/jsp/" p:suffix=".jsp" />
21    </beans>
 

  4. applicationContext.xml配置

01    <?xml version="1.0" encoding="UTF-8"?>
02    <beans xmlns="http://www.springframework.org/schema/beans"
03            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
04            xmlns:aop="http://www.springframework.org/schema/aop"
05            xmlns:tx="http://www.springframework.org/schema/tx"
06            xsi:schemaLocation="
07                http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
08                http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
09                http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
10     
11        <!-- 采用hibernate.cfg.xml方式配置数据源 -->
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        <!-- 将事务与Hibernate关联 -->
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       <!-- 测试Service -->
29       <bean id="loginService" class="service.LoginService"></bean>
30     
31        <!-- 测试Dao -->
32        <bean id="hibernateDao" class="dao.HibernateDao">
33            <property name="sessionFactory" ref="sessionFactory"></property>
34        </bean>
35    </beans>
 

  二、详解

  Spring MVC与Struts从原理上很相似(都是基于MVC架构),都有一个控制页面请求的Servlet,处理完后跳转页面。看如下代码(注解):

01    package controller;
02     
03    import javax.servlet.http.HttpServletRequest;
04     
05    import org.springframework.stereotype.Controller;
06    import org.springframework.web.bind.annotation.RequestMapping;
07    import org.springframework.web.bind.annotation.RequestParam;
08     
09    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参数来区分访问不同的方法,代码如下:

01    package controller;
02     
03    import org.springframework.stereotype.Controller;
04    import org.springframework.web.bind.annotation.RequestMapping;
05    import org.springframework.web.bind.annotation.RequestMethod;
06     
07    @Controller
08    @RequestMapping("/test2/login.do")  // 指定唯一一个*.do请求关联到该Controller
09    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也可以这么写:

01    package controller;
02     
03    import org.springframework.stereotype.Controller;
04    import org.springframework.web.bind.annotation.RequestMapping;
05     
06    @Controller
07    @RequestMapping("/test3/*")  // 父request请求url
08    public class TestController3 {
09     
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

转载于:https://www.cnblogs.com/jiangyaqiong/p/3408318.html

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weixin_30613433/article/details/98514922

智能推荐

51nod 1094 和为k的连续区间-程序员宅基地

1094 和为k的连续区间基准时间限制:1 秒 空间限制:131072 KB 分值: 10 难度:2级算法题 收藏 关注一整数数列a1, a2, ... , an(有正有负),以及另一个整数k,求一个区间[i, j],(1 <= i <= j <= n),使得a[i] + ... + a[j] = k。Inpu

软件架构设计---软件架构文档化-程序员宅基地

软件架构文档化 记录软件架构的活动就是架构编档过程,也就是架构的文档化。它包含两个方面:一是过程,编档过程能促使架构设计师进一步思考,使得架构更加完善;二是结果,描述架构的文档将作为架构开发的成果,供项目关系人使用。 1.架构文档的使用者 架构文档的使用者是架构的项目关系人。编写技术文档(尤其是软件架构文档)最基本的原则之一是要从读者的角度来编写,易于编写但很难..._软件架构文档

Rabbitmq同时处理多个消息(多线程)_rabbitmq多线程_李奈 - Leemon的博客-程序员宅基地

Rabbitmq同时处理多个消息(多线程)文章目录Rabbitmq同时处理多个消息(多线程)一, 失败不重试,直接确认二, 失败重试5次,再直接确认basicQos预取方法参数解析basicQos(int prefetchCount)basicQos(int prefetchCount, boolean global)basicQos(int prefetchSize, int prefetchCount, boolean global)参数:prefetchSize:可接收消息的大_rabbitmq多线程

JAVAssist---动态修改注解-程序员宅基地

先来看看我们需要修改注解的代码:[java] view plain copy print?/** * EntityManager的实例化 * @author 陈丽娜 * @version 1.0.0 , 2015年3月30日 下午8:43:27 * @param */ public class Collect

OpenAL快速入门教程_openal教程-程序员宅基地

转发,原文地址:OpenAL快速入门教程OpenAL快速入门1. 为什么使用OpenAL也许你已经用过AudioToolbox框架并用以下代码来播放一个音乐文件:NSString* path = [[NSBundle mainBundle] pathForResource:@"soundEffect1" ofType:@"caf"];NSURL *_openal教程

eclipse里的maven配置国内镜像_eclipse maven 国内镜像地址-程序员宅基地

前言较新版本的eclipse都自带maven,不必再下载maven了,但是其下载jar包的速度实在不敢恭维,这里就简单记录下,eclipse里的maven怎么配置国内镜像正文打开eclipse,选择Window - Perferences然后Maven - User Settings - 点击open fileeclipse中就打开了自带maven的配置文件,当然你也可以看路径在电脑..._eclipse maven 国内镜像地址

随便推点

带你用Python采集文档内容并保存PDF_python提取文档内容另存为pdf_搬砖python中~的博客-程序员宅基地

知识点:requestscss选择器第三方库:requests >>> pip install requestsparsel >>> pip install parselpdfkit >>> pip install pdfkit开发环境:版 本:anaconda5.2.0(python3.6.5)编辑器:pycharm (安装包/安装教程/激活码/使用教程/插件[翻译插件/主题/汉化包])软件环境: wkhtmltopdf _python提取文档内容另存为pdf

Mysql Error:The user specified as a definer (‘mysql.infoschema’@’localhost’) does not exist_the user specified as a definer ('register'@'local-程序员宅基地

grant all on . to ‘mysql.infoschema’@‘localhost’;然后再用Navicat连就能连上了。我的是这么解决的_the user specified as a definer ('register'@'localhost') does not exist

通过华为镜像站快速下载JDK_华为镜像下载jdk-程序员宅基地

由于Oracle官网国内下载速度比较慢,可以到华为镜像站快速下载JDK华为开源镜像站链接_华为镜像下载jdk

Java接口发送与接收_java发送接口怎么写-程序员宅基地

Java像服务器发送与接收_java发送接口怎么写

数据结构中八大排序算法-程序员宅基地

一、冒泡排序思想:重复走访过要排序的序列,一次比较两个元素,如果他们的顺序错误就将他们进行交换,一次冒上来的是最小的,其次是第二小。时间复杂度:O(n^2)空间复杂度:O(1)稳定性:稳定1./** * 冒泡排序 * @param disOrderArray * @return */ public static int[] BubbleSort(int[]

十天的心理挑战_30天积极心理挑战-程序员宅基地

十天的心理挑战如果本书所教你的都没做,但至少这一样练习得好好做,我称其为“十天的心理挑战”它曾确实帮助过我,何以见得?因为他使我得以控制自己的内心,不在继续朝负面去想。你作好准备了吗?以下就是游戏的规则:一.在随后一连十天里,心里不可有任何一刻的消极或负面念头、情绪、问话、字眼或引喻。二.当你一有消极或负面的反映时----一定会有的-----就要立即提问自己好多_30天积极心理挑战