基于Maven的SSM总体架构设计(三)

3.4 Spring+SpringMVC+MyBatis+Shiro框架整合

3.4.1 创建Maven Web工程

        为了便于项目依赖库(jar)的管理和不同项目中使用的依赖库(jar)版本一致,我们Maven对依赖库进行统一管理。因此,我们在MyEclipse中可以直接创建Maven Web项目,具体如下:
        MyEclipse->New->Web Project->add Maven support->Standard Maven JEE Project
图3-6 创建Maven Web工程
图3-7 Maven Web工程结构
我们按照Maven约定创建src/test/java和src/main/resources,如下图:
图3-8 Maven项目结构
        为了方便jar文件的版本在不同项目中进行统一管理,把Dependencies中的jar放入Dependency Management中。如下图:
图3-9 Maven依赖
Maven本地库的默认路径为:c:\Users\xxx.m2\repository

3.4.2 引入Spring,依赖注入(DI)实现

Spring为我们带来的好处就是让我们可以“专心做事”。

  • 依赖注入(DI)特性让我们编程时不用管理其依赖的组件。
  • 面向方面编程(AOP),将程序中的公共问题集中解决。
    首先,我们通过Spring管理组件之间的依赖关系。具体步骤如下:
    1、在pom.xml中引入spring基础jar包,如下:
<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-core</artifactId>
	<version>3.2.18.RELEASE</version>
</dependency>
<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-context</artifactId>
	<version>3.2.18.RELEASE</version>
</dependency>
<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-context-support</artifactId>
	<version>3.2.18.RELEASE</version>
</dependency>

2、在src/main/resources中添加spring.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:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
                           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
                           http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
</beans>

3、编写依赖注入案例,具体代码看参考案例:
图3-10 Spring依赖注入代码案例
4、在spring.xml中配置bean,及依赖关系

<bean id="colorInk" class="com.mesnac.service.impl.ColorInk" />
<bean id="greyInk" class="com.mesnac.service.impl.GreyInk" />

<bean id="printer" class="com.mesnac.service.impl.OfficePrinter" />
	<property name="ink" ref="greyInk" />
</bean>

3.4.3 引入junit,进行单元测试

        为了保证程序的质量,测试环节是必不可少的。Junit是最常用单元测试框架,可以使用junit提供的注解方便的编写单元测试用例。具体使用步骤:
1、在pom.xml中引入junit基础jar包,如下:

<dependency>
	<groupId>junit</groupId>
	<artifactId>junit</artifactId>
	<version>4.8.2</version>
</dependency>

2、在src/test/java下编写测试类,运行测试
图3-11 依赖注入单元测试

3.4.4 使用注解替代xml配置管理依赖

        随着项目规模的变大,spring相关的配置文件会非常庞大,虽然spring文件可以拆解成多个,但是在庞大的配置文件中定位一个bean也是非常耗时的,为了避免这种情况,我们可以采用注解的方式替代xml配置的方式管理依赖和组件声明。具体如下:
1、修改spring.xml配置,加入对业务包的注解扫描

<!-- 自动扫描dao和service包(自动注入) -->
<content:component-scan base-package="com.mesnac.sys.service.impl" />

2、使用@Service("beanName”)把业务类标注为业务组件
3、使用@Autowired或@Resource在setter方法上标注注入
4、重新运行单元测试

3.4.5 改进单元测试

        为了在测试类中直接注入被测组件,我们需要对测试类进行改进。具体如下:
1、在pom.xml中引入spring-test

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>3.2.18.RELEASE</version>
</dependency>

2、编写测试用例基类,修改测试类,运行测试

package com.mesnac.test;

import javax.annotation.Resource;

import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)						//告诉spring如何执行
@ContextConfiguration(location={"classpath:spring.xml})		//指定spring配置文件的位置
public class ServiceTestCase<T> {
	protected T service;
	@Resource
	public void setService(T service) {
		this.service = service;
	}
}

3.4.6 引入SpringMvc实现视图和模型分离

        相比struts2的过滤器机制,SpringMvc的Servlet运行效率更高,而在互联网应用中struts2的漏洞频频爆出,导致越来越多的开放群体逐渐放弃struts2,改为与Spring本就是一体的SpringMvc实现控制器部分。具体如下:
1、在pom.xml中引入spring-webmvc

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>3.2.18.RELEASE</version>
</dependency>

2、在src/main/resources中增加spring-mvc.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:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
                           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
                           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
                           http://www.springframework.org/schema/tx http://www.springframework.org/schema/aop/spring-tx.xsd">
    <!-- 自动扫描action包(自动注入) -->
    <context:component-scan base-package="com.mesnac.action" />
    <!-- 自动扫描action包(依赖注入) -->
    <mvc:annotation-driven/>
    <!-- 访问静态资源 -->
    <mvc:default-servlet-handler/>
    <!-- 视图解析器 -->
    <bean  class="org.springframework.web.servlet.view.InternalResourceViewResolver">
       <property name="prefix" value="/jsp/"/>
       <property name="suffix" value=".jsp"/>
    </bean>
</beans>

3、编写Action类,在类前增加@Controller注解

package com.mesnac.action;
import java.util.List;
//省略其他导入包...
@Controller
@RequestMapping("/sys/userInfoAction")
public class UserInfoAction {
	private UserInfoService service;
	
	@Resource
	public void setService(UserInfoService service) {
		this.service = service;
	}
	
	@RequestMapping("/toList")
	public ModelAndView toList() {
		ModelAndView mv = null;
		try {
			List<UserInfo> lst = this.service.getByParam(null);
			
			for(UserInfo u : lst) {
				System.out.println(u.getId() + "\t" + u.getUserName() + "\t" + u.getPassword() + "\t" + u.getRemark());
				mv = new ModelAndView();
				mv.addObject("userInfoList", lst);
				mv.setViewName("/system/user/index");
			}
		}
		catch(Exception ex) {
			ex.printStackTrace();
			mv = new ModelAndView("redirect:/error.jsp");
		}
		return mv;
	}
}

4、编写Action单元测试基类

package com.mesnac.test;
import javax.annotation.Resource;

@RunWith(SpringJUnit4ClassRunner.class)				//告诉spring如何执行
@WebAppConfiguration								//标明是web应用测试
@ContextConfiguration(location={"classpath:spring.xml", "classpath:spring-mvc.xml"})					//加载spring配置文件
public class ActionTestCase<T> {
	protected T action;
	private MockMvc mockMvc;
	private MockHttpSession session;
	@Resource
	public void setAction(T action) {
		this.action = action;
		this.mockMvc = MockMvcBuilders.standaloneSetup(this.action).build();
		this.session = new MockHttpSession();
	}
	protected MockMvc getMockMvc() {
		return this.mockMvc;
	}
	protected MockHttpSession getSession() {
	 	return this.session;
	}
}

5、编写Action的单元测试类,并运行测试

package com.mesnac.action.test;
import org.junit.Test;

public class UserInfoActionTest extends ActionTestCase<UserInfoAction> {
	@Test
	public void testToList() throws Exception {
		String actionurl = "/sys/userInfoAction/toList";
		MockHttpServletRequestBuilder rb = MockMvcRequestBuilders.post(actionurl);
		super.getMockMvc().perform(rb).andExpect(MockMvcResultMatchers.status().isOk()).andReturn();
	}
	@Test
	public void testToEdit() throws Exception {
		String actionurl = "/sys/userInfoAction/toEdit";
		MockHttpServletRequestBuilder rb = MockMvcRequestBuilder.post(actionurl);
		rb.param("userName", "zhenglb");
		super.getMockMvc().perform(rb).andExpect(MockMvcResultMatchers.status().isOk()).andReturn();
	}
}

6、在web.xml中集成spring和springMvc

<!--加载spring配置文件-->
<context-param>
	<param-name>contextConfigLocation</param-name>
	<param-value>classpath:spring.xml</param-value>
</context-param>

<!-- 处理由JavaBean Introspector功能引起的缓存泄漏监听器,配置在spring主监听器之前 -->
<listener>
	<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
</listener>
<!-- Spring主监听器 -->
<listener>
	<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- spring mvc -->
<servlet>
	<servlet-name>springmvc</servlet-name>
	<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
	<init-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:spring-mvc.xml</param-value>
	</init-param>
</servlet>
<servlet-mapping>
	<servlet-name>springmvc</servlet-name>
	<url-pattern>/</url-pattern>
</servlet-mapping>

7、结合JSTL和EL表达式编写视图展现页面

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<h3>用户列表</h3>
<hr />
<div>
	<ul>
		<li>Id</li>
		<li>UserName</li>
		<li>Password</li>
		<li>Remark</li>
	</ul>
	<c:forEach items="${userInfoList}" var="user">
	<ul>
		<li>${user.id}</li>
		<li>${user.userName}</li>
		<li>${user.password}</li>
		<li>${user.remark}</li>
	</ul>
	</c:forEach>
</div>

(未完待续…)
完整资料下载

猜你喜欢

转载自blog.csdn.net/zlbdmm/article/details/83183437