web mvc :spring mvc 基于spring Spring MVC 框架搭建及详解

1框架编辑

Spring MVC属于SpringFrameWork的后续产品,已经融合在Spring Web Flow里面。Spring 框架提供了构建 Web 应用程序的全功能 MVC 模块。使用 Spring 可插入的 MVC 架构,可以选择是使用内置的 Spring Web 框架还可以是 Struts 这样的 Web 框架。通过策略接口,Spring 框架是高度可配置的,而且包含多种视图技术,例如 JavaServer Pages( JSP)技术、Velocity、Tiles、iText 和 POI。Spring MVC 框架并不知道使用的视图,所以不会强迫您只使用 JSP 技术。Spring MVC 分离了 控制器、模型 对象、分派器以及处理程序对象的角色,这种分离让它们更容易进行定制。

2优点编辑

Lifecycle for overriding binding, validation, etc;易于同其它View框架(Tiles等)无缝集成,采用IOC便于测试。
它是一个典型的教科书式的mvc构架,而不像struts等都是变种或者不是完全基于mvc系统的框架,对于初学者或者想了解mvc的人来说我觉得 spring是最好的,它的实现就是教科书!第二它和 tapestry一样是一个纯正的servlet系统,这也是它和tapestry相比 struts所没有的优势。而且框架本身有代码,而且看起来容易理解。

3单元测试编辑

关于Spring MVC Controller 层的单元测试
测试准备工作:
1、搭建测试Web环境
@RunWith(UnitilsJUnit4TestClassRunner.class)
@SpringApplicationContext({"classpath:*.xml","file:src/main/webapp/WEB-INF/spring-configuration/*.xml","file:src/main/webapp/WEB-INF/*.xml" })
2、注入Controller 类
@SpringBeanByType
BeanController controller;
3、编写测试数据
测试数据的文件名一定要与测试类的文件名相同,比如测试数据BeanControllerTest.xml ,测试类 BeanControllerTest。
4、注入测试数据
@Test
@DataSet
public void testBean(){}

4常用注解编辑

MVC已经是现代Web开发中的一个很重要的部分,下面介绍一下Spring MVC的一些使用心得。
之前的项目比较简单,多是用JSP 、Servlet + JDBC 直接搞定,在项目中尝试用 Struts(Struts MVC)+Spring+Hibernate, 严格按照分层概念驱动项目开发,因项目需求一直不断变化,功能不断扩充、增强,技术构建也几经改变到目前有个稳定的应用,体会了很多感受,这次先对 Spring MVC 层进行一些个人总结。
MVC作为WEB项目开发的核心环节,正如三个单词的分解那样,C(控制器)将V(视图、用户客户端)与M(模块,业务)分开构成了MVC ,这边不去讨论项目中是否应用MVC ,也不针对MVC的实现原理进行讲解,而是探讨实践中如何从应用SSH, 到Spring MVC + Spring+Hibernate的演化过程。
先看 Struts 如何与 Spring 结合处理一次简单的请求响应代码,前台可以设为用 AJAX 调用:
1. 在 struts-config.xml 文件中加入
<!--用于声明GetPersonList。do请求委托Spring处理--><actionpath="/GetPersonList" scope="request"type="org.springframework.web.struts.DelegatingActionProxy"></action>
2.在 applicationContext.xml 文件中加入
<!-- 指定GetPersonList处理的代码,和注入实现业务的代码 --><beanname="/GetPersonList" class="cn.base.GetPersonListAction"><propertyname="getPersonList" ref=" getPersonListServices"></property></bean>
3.cn.base.GetPersonListAction 实现请求响应代码
可以看出一次请求需求如此多的步骤,在加上一个项目下来有很多这样的请求响应,将给配置文件管理带来很大的麻烦。
经过对 Spring 的深入应用, Spring 本身提供的 URL 请求控制,对其天然支持可以让我们不需要 applicationContext.xml 再次声明一次 URL 请求 Bean ,即减少了 Struts 的声明 URL ,达到减少些繁琐的配置。但只是少了一些而已,同样也会面临着配置文件的管理问题。
Spring 注解将给我们的工作带来些轻松,利用反射机制原理出现的注解就是为了解决配置大量的配置问题。请看下处理一次简单的请求响应代码
@Controller --声明控制器@RequestMapping("/person") –声明URL
public class PersonControl extends BaseController {
@Autowired –业务接口注入
private personServices personServices;/*** 获得人员列表*
@param request* @param response* @throws Exception*/@RequestMapping(params = "method=geList") --即处理/person.do? method=geList方法
public void getnodeList(HttpServletRequest request,HttpServletResponse response) throws Exception { //处理请求//处理响应}}
可以看出,在代码上加入注解可以省去我们上面说的多个配置文件的工作,达到简便的 MVC 处理请求响应。
在配上简单的配置文件声明,即可轻松处理项目的全部请求控制工作。
Spring MVC乱码问题
在使用Spring MVC 做java Web 项目时,乱码问题时常都会出现,解决方法也不尽相同,有简单也有复杂的;如果加入了Spring框架之后就不一样了,可以采用Spring框架自带的过滤器CharacterEncodingFilter,这样可以大大减轻了我们的工作量,即简单方便又容易理解,配置方式如下:在web.xml文件中filter的位置加上如下内容:
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>*.htm</url-pattern>
</filter-mapping>
springmvc实现上传文件代码片段
<?xml version="1.0" encoding="UTF-8"?>
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" /></bean>
@Controller@RequestMapping("/common")
public class CommonController {
@RequestMapping(value = "/upload")
public @ResponseBody String upload(@RequestParam("file") MultipartFile file, HttpSession session) throws Exception {
File localFile = new File("c:/test/a.rar");
file.transferTo(localFile);
return "success";
}
}
 
 
 

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配置(部分)

<!-- 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。

<?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 http://www.springframework.org/schema/context/spring-context-3.0.xsd">

	<!-- 启用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配置

<?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,处理完后跳转页面。看如下代码(注解):

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参数来区分访问不同的方法,代码如下:

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也可以这么写:

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 技术。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值