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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<!--
Spring MVC配置 -->
<!--
====================================== -->
<servlet>
    <servlet-name>spring</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!--
能够自己定义servlet.xml配置文件的位置和名称,默觉得WEB-INF文件夹下。名称为[<servlet-name>]-servlet.xml。如spring-servlet.xml
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring-servlet.xml</param-value> 
默认
    </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配置 -->
<!--
====================================== -->
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
   
 
<!--
指定Spring Bean的配置文件所在文件夹。默认配置在WEB-INF文件夹下 -->
<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中<servlet-name>标签配的值为spring(<servlet-name>spring</servlet-name>)。再加上“-servlet”后缀而形成的spring-servlet.xml文件名称。假设改为springMVC,相应的文件名称则为springMVC-servlet.xml。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?

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  
       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>">
 
    <!--
启用spring mvc 注解 -->
    <context:annotation-config

/>
 
    <!--
设置使用注解的类所在的jar包 -->
    <context:component-scan

base-package
="controller"></context:component-scan>
 
    <!--
完毕请求和注解POJO的映射 -->
    <bean

class
="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"

/>
 
    <!--
对转向页面的路径解析。

prefix:前缀。 suffix:后缀 -->

    <bean

class
="org.springframework.web.servlet.view.InternalResourceViewResolver"

p:prefix
="/jsp/"

p:suffix
=".jsp"

/>
</beans>

  4. applicationContext.xml配置

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<?

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: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方式配置数据源 -->
    <bean

id
="sessionFactory"

class
="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <property

name
="configLocation">
            <value>classpath:config/hibernate.cfg.xml</value>
        </property>
    </bean>
     
    <!--
将事务与Hibernate关联 -->
    <bean

id
="transactionManager"

class
="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property

name
="sessionFactory">
            <ref

local
="sessionFactory"/>
        </property>
    </bean>
     
    <!--
事务(注解 )-->
    <tx:annotation-driven

transaction-manager
="transactionManager"

proxy-target-class
="true"/>
 
   <!--
測试Service -->
   <bean

id
="loginService"

class
="service.LoginService"></bean>
 
    <!--
測试Dao -->
    <bean

id
="hibernateDao"

class
="dao.HibernateDao">
        <property

name
="sessionFactory"

ref
="sessionFactory"></property>
    </bean>
</beans>

  二、具体解释

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
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的Action
public

class

TestController {
 
    @RequestMapping("test/login.do")  //
请求url地址映射,类似Struts的action-mapping
    public

String testLogin(
@RequestParam(value="username")String
username, String password, HttpServletRequest request) {
        //
@RequestParam是指请求url地址映射中必须含有的參数(除非属性required=false)
        //
@RequestParam可简写为:@RequestParam("username")
 
        if

(!
"admin".equals(username)
|| !
"admin".equals(password))
{
            return

"loginError"
//
跳转页面路径(默觉得转发),该路径不须要包括spring-servlet配置文件里配置的前缀和后缀
        }
        return

"loginSuccess"
;
    }
 
    @RequestMapping("/test/login2.do")
    public

ModelAndView testLogin2(String username, String password, 
int

age){
        //
request和response不必非要出如今方法中,假设用不上的话能够去掉
        //
參数的名称是与页面控件的name相匹配,參数类型会自己主动被转换
         
        if

(!
"admin".equals(username)
|| !
"admin".equals(password)
|| age < 
5)
{
            return

new

ModelAndView(
"loginError"); //
手动实例化ModelAndView完毕跳转页面(转发)。效果等同于上面的方法返回字符串
        }
        return

new

ModelAndView(
new

RedirectView(
"../index.jsp"));  //
採用重定向方式跳转页面
        //
重定向另一种简单写法
        //
return new ModelAndView("redirect:../index.jsp");
    }
 
    @RequestMapping("/test/login3.do")
    public

ModelAndView testLogin3(User user) {
        //
相同支持參数为表单对象,类似于Struts的ActionForm。User不须要不论什么配置。直接写就可以
        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");
    }
 
    @Resource(name
"loginService")  //
获取applicationContext.xml中bean的id为loginService的,并注入
    private

LoginService loginService;  
//等价于spring传统注入方式写get和set方法,这种优点是简洁工整,省去了不必要得代码
 
    @RequestMapping("/test/login4.do")
    public

String testLogin4(User user) {
        if

(loginService.login(user) == 
false)
{
            return

"loginError"
;
        }
        return

"loginSuccess"
;
    }
}

  以上4个方法演示样例,是一个Controller里含有不同的请求url,也能够採用一个url訪问。通过url參数来区分訪问不同的方法,代码例如以下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
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")  //
指定唯一一个*.do请求关联到该Controller
public

class

TestController2 {
     
    @RequestMapping
    public

String testLogin(String username, String password, 
int

age) {
        //
假设不加不论什么參数,则在请求/test2/login.do时,便默认运行该方法
         
        if

(!
"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 password) {
        //
根据params的參数method的值来区分不同的调用方法
        //
能够指定页面请求方式的类型,默觉得get请求
         
        if

(!
"admin".equals(username)
|| !
"admin".equals(password))
{
            return

"loginError"
;
        }
        return

"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

"loginSuccess"
;
    }
}

  事实上RequestMapping在Class上。可看做是父Request请求url,而RequestMapping在方法上的可看做是子Request请求url。父子请求url终于会拼起来与页面请求url进行匹配,因此RequestMapping也能够这么写:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package

controller;
 
import

org.springframework.stereotype.Controller;
import

org.springframework.web.bind.annotation.RequestMapping;
 
@Controller
@RequestMapping("/test3/*")  //
父request请求url
public

class

TestController3 {
 
    @RequestMapping("login.do")  //
子request请求url。拼接后等价于/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"
;
    }
}

  三、结束语

  掌握以上这些Spring MVC就已经有了非常好的基础了,差点儿可应对与不论什么开发。在熟练掌握这些后,便可更深层次的灵活运用的技术,如多种视图技术,比如 Jsp、Velocity、Tiles、iText 和 POI。Spring MVC框架并不知道使用的视图,所以不会强迫您仅仅使用 JSP 技术。

Spring MVC 框架搭建及具体解释的更多相关文章

  1. spring mvc 框架搭建及详解

    现 在主流的Web MVC框架除了Struts这个主力 外,其次就是Spring MVC了,因此这也是作为一名程序员需要掌握的主流框架,框架选择多了,应对多变的需求和业务时,可实行的方案自然就多了.不 ...

  2. Spring MVC框架搭建

    Spring MVC篇一.搭建Spring MVC框架 本项目旨在搭建一个简单的Spring MVC框架,了解Spring MVC的基础配置等内容. 一.项目结构 本项目使用idea intellij ...

  3. Spring MVC框架搭建及其详解

    现在主流的Web MVC框架除了Struts这个主力 外,其次就是Spring MVC了,因此这也是作为一名程序员需要掌握的主流框架,框架选择多了,应对多变的需求和业务时,可实行的方案自然就多了.不过 ...

  4. Java Spring MVC框架搭建(一)

    环境准备 >>>>>>java JDK和tomcat,eclipse 1.创建项目 2.项目名称自定义,这边为demo 3.我们已经创建完一个动态网站的项目,还得下 ...

  5. 从零开始学 Java - 搭建 Spring MVC 框架

    没有什么比一个时代的没落更令人伤感的了 整个社会和人都在追求创新.进步.成长,没有人愿意停步不前,一个个老事物慢慢从我们生活中消失掉真的令人那么伤感么?或者说被取代?我想有些是的,但有些东西其实并不是 ...

  6. Spring MVC篇一、搭建Spring MVC框架

    本项目旨在搭建一个简单的Spring MVC框架,了解Spring MVC的基础配置等内容. 一.项目结构 本项目使用idea intellij创建,配合maven管理.整体的目录结构如图: 其中ja ...

  7. 如何搭建Spring MVC 框架---Hello World

    传送门 现在的Web框架基本都采用了MVC(model-view-Controller)设计模式,其中,Servlet和Filter都可以充当控制器.Spring MVC采用一个Servlet作为控制 ...

  8. 十七、IntelliJ IDEA 中的 Maven 项目初体验及搭建 Spring MVC 框架

    我们已经将 IntelliJ IDEA 中的 Maven 项目的框架搭建完成.接着上文,在本文中,我们更近一步,利用 Tomcat 运行我们的 Web 项目. 如上图所示,我们进一步扩展了项目的结构, ...

  9. Spring MVC 框架的架包分析,功能作用,优点

    由于刚搭建完一个MVC框架,决定分享一下我搭建过程中学习到的一些东西.我觉得不管你是个初级程序员还是高级程序员抑或是软件架构师,在学习和了解一个框架的时候,首先都应该知道的是这个框架的原理和与其有关j ...

随机推荐

  1. 洛谷 [AHOI2001]质数和分解

     题目描述 Description 任何大于 1 的自然数 n 都可以写成若干个大于等于 2 且小于等于 n 的质数之和表达式(包括只有一个数构成的和表达式的情况),并且可能有不止一种质数和的形式.例 ...

  2. PHP数组和数据结构(下)未完。。。。

    1.数组的遍历 (1)each(): 接受一个数组作为参数,返回数组中当前元素的键/值对,并向后移动数组指针到下一个元素的位置 键/值对被返回为带有四个元素的关联和索引混合的数组,键名分别为0,1,k ...

  3. [转]No configuration found for the specified action解决办法

    使用Struts2,配置一切正常,使用常用tag也正常,但是在使用<s:form>标记时,发现控制台总是输出警告信息, 警告信息内容如下: 警告: ...... <div> h ...

  4. Java后台JSON数据的使用

    1. List集合转换成json代码 List list = new ArrayList(); list.add( "first" ); list.add( "secon ...

  5. <摘录>GCC 中文手

    GCC 中文手册 作者:徐明 GCC Section: GNU Tools (1) Updated: 2003/12/05 Index Return to Main Contents -------- ...

  6. iOS 在某一个ViewController跳转到TabViewController中的某一个ViewController

    要做到这个分为两步 第一步, 导入app #import "AppDelegate.h" 第二步, 监听方法中先写加入以下代码: [self dismissViewControll ...

  7. Android-Universal-Image-Loader载入图片

    直接看代码:MainActivity: package com.example.textwsjdemo; import com.nostra13.universalimageloader.cache. ...

  8. 3dsMAX 插件

    SDK C++ 对性能有要求 底层接口 MAXScript 上层接口 a few more function whick sdk does not afford MCG像蓝图一样的东西 http:// ...

  9. 在MySQL中使用子查询和标量子查询的基本用法

    一.MySQL 子查询 子查询是将一个 SELECT 语句的查询结果作为中间结果,供另一个 SQL 语句调用.MySQL 支持 SQL 标准要求的所有子查询格式和操作,也扩展了特有的几种特性.子查询没 ...

  10. Spark Streaming ReceiverTracker架构设计

    本节的主要内容: 一.ReceiverTracker的架构设计 二.消息循环系统 三.ReceiverTracker具体实现 Spark Streaming作为Spark Core基础 架构之上的一个 ...