ssm-ssm整合(springmvc+mybatis)

ssm框架整合在如今是很常用的,前面我們已經講解過ssm2以及sm的整合,那麼今天我們講解一下ssm的整合。

同樣的,我們以一個用戶登錄的案例進行講解。

項目結構如下所示:

數據庫表結構:

id-int
username-varchar
password-varchar

項目源碼下載:點擊下載

war包下載:點擊下載

項目演示視頻地址:點擊觀看

開發工具:

eclipse neon

tomcat7.0

Mybatis3.2.7

Spring3.2

jdk1.7


同樣的,項目包括view、Service、Model三層,那麼我們從小至上進行開發,即model-service-view

Model層

1、相關資源文件

log4j文件:

# Global logging configuration
#在開發環境下日誌級別要設置成DEBUG,生產環境設置成info或error
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

db.properties文件:

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1/bs?character=utf-8
jdbc.username=root
jdbc.password=0707

2、Mybatis配置文件SqlMapConfig.xml編寫

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

	<typeAliases>
		<package name="com.sw.po"/>
	</typeAliases>
	
</configuration>

3、編寫po對象文件

package com.sw.po;
/*
 *@Author swxctx
 *@time 2017年5月15日
 *@Explain:用戶表po對象
 *id:編號
 *username:用戶名
 *password:密碼
 */
public class User {
	private int id;
	private String username;
	private String password;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
}

4、編寫mapper.java文件

package com.sw.mapper;

/*
 *@Author swxctx
 *@time 2017年5月15日
 *@Explain:Mapper接口
 */
public interface UserMapper {
	
	/*用戶登錄:根據用戶名查找用戶密碼,檢查是否匹配進行登錄*/
	public String findPassByName(String username)throws Exception;
	
}

5、編寫mapper.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.sw.mapper.UserMapper">
	
	<!-- 用戶登錄(根據用戶名查找返回密碼,校驗) -->
	<select id="findPassByName" parameterType="String" resultType="String">
		select password from user where username=#{username}
	</select>
	
</mapper>

6、編寫applicationContext-dao文件,用於spring容器管理mapper以及整合mybatis

<?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:mvc="http://www.springframework.org/schema/mvc"
	xmlns:context="http://www.springframework.org/schema/context"
	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-3.2.xsd 
		http://www.springframework.org/schema/mvc 
		http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd 
		http://www.springframework.org/schema/context 
		http://www.springframework.org/schema/context/spring-context-3.2.xsd 
		http://www.springframework.org/schema/aop 
		http://www.springframework.org/schema/aop/spring-aop-3.2.xsd 
		http://www.springframework.org/schema/tx 
		http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">

	<!-- 加載配置文件 -->
	<context:property-placeholder location="classpath:db.properties"/>
	<!-- 配置註解自動掃描範圍 -->
  <!--   <context:component-scan base-package="com.sw.mapper"></context:component-scan> -->
    
    <!-- 自動裝配 -->
    <!--  <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/> -->
	
	<!-- 數據庫連接池 -->
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="${jdbc.driver}"/>
		<property name="url" value="${jdbc.url}"/>
		<property name="username" value="${jdbc.username}"/>
		<property name="password" value="${jdbc.password}"/>
		<property name="maxActive" value="10"/>
		<property name="maxIdle" value="5"/>
	</bean>	
	
	<!-- 管理mybatis -->
	<!-- mapper配置 -->
	<!-- 讓spring管理sqlsessionfactory 使用mybatis-spring.jar -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		
		<!-- 數據庫連接池 -->
		<property name="dataSource" ref="dataSource" />
		
		<!-- 加載mybatis的全局配置文件 -->
		<property name="configLocation" value="classpath:mybatis/SqlMapConfig.xml" />
	</bean>
	
	<!-- mapper掃描(自動掃描) -->
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<!-- 掃描的包名 -->
		<property name="basePackage" value="com.sw.mapper"></property>
		<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
	</bean>
	
</beans>

至此,Model層的開發已經完成,我們進行一下測試,如下:

package com.sw.test;


import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.sw.mapper.UserMapper;

/*
 *@Author swxctx
 *@time 2017年5月15日
 *@Explain:Spring與Mybatis整合測試-dao
 */
public class UserDaoTest {
	private ApplicationContext applicationContext;
	@Before
	public void setUp() throws Exception {
		//spring
		applicationContext = new ClassPathXmlApplicationContext("classpath:/spring/applicationContext-dao.xml");
	}
	
	@Test
	public void test() throws Exception {
		UserMapper userMapper = (UserMapper) applicationContext.getBean("userMapper");
		String pass=userMapper.findPassByName("bs");
		System.out.println(pass);
	}

}

測試結果如下圖:

如上圖所示,Mybatis與Spring的整合已經完成,可以正常運行,model層至此開發完畢,接下來進行Service層的開發。


Service層

Service層主要包括Service接口以及Service實現類,通過Spring管理Service層的實現類。

1、編寫Service層接口

package com.sw.service;
/*
 *@Author swxctx
 *@time 2017年5月15日
 *@Explain:Service層接口
 */
public interface UserService {
	public final static String SERVICE_NAME="UserServiceImpl";
	/*用戶登錄驗證*/
	public String findLoginCheck(String username)throws Exception;
}

2、編寫Service實現類

package com.sw.service.impl;

import org.springframework.stereotype.Service;

import com.sw.container.SwServiceProvider;
import com.sw.mapper.UserMapper;
import com.sw.service.UserService;

/*
 *@Author swxctx
 *@time 2017年5月15日
 *@Explain:Service層接口實現類
 */
@Service
public class UserServiceImpl implements UserService{
	//登錄檢查
	@Override
	public String findLoginCheck(String username) throws Exception {
		UserMapper userMapper=(UserMapper) SwServiceProvider.getService("userMapper");
		String pass = userMapper.findPassByName(username);
		return pass;
	}
	
}

3、將Service層實現類放入spring管理,編寫applicationContext-service.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:mvc="http://www.springframework.org/schema/mvc"
	xmlns:context="http://www.springframework.org/schema/context"
	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-3.2.xsd 
		http://www.springframework.org/schema/mvc 
		http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd 
		http://www.springframework.org/schema/context 
		http://www.springframework.org/schema/context/spring-context-3.2.xsd 
		http://www.springframework.org/schema/aop 
		http://www.springframework.org/schema/aop/spring-aop-3.2.xsd 
		http://www.springframework.org/schema/tx 
		http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">
	
	<!-- Service層配置 -->
	
	<!-- 配置註解自動掃描範圍 -->
  <!--   <context:component-scan base-package="com.sw"></context:component-scan> -->
	
	<!-- Servic層方法實現配置 -->
	 <bean id="UserServiceImpl" class="com.sw.service.impl.UserServiceImpl"></bean>

</beans>

4、接下來我們需要通過Spring控制事務,編寫applicationContext-transaction.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:mvc="http://www.springframework.org/schema/mvc"
	xmlns:context="http://www.springframework.org/schema/context"
	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-3.2.xsd 
		http://www.springframework.org/schema/mvc 
		http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd 
		http://www.springframework.org/schema/context 
		http://www.springframework.org/schema/context/spring-context-3.2.xsd 
		http://www.springframework.org/schema/aop 
		http://www.springframework.org/schema/aop/spring-aop-3.2.xsd 
		http://www.springframework.org/schema/tx 
		http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">

	<!-- 事務控制 -->

	<!-- 事務管理器 
	對mybatis操作數據庫事務控制,spring使用jdbc的事務控制類
	-->
	<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<!-- 數據源
		dataSource在applicationContext-dao.xml中配置了
		 -->
		<property name="dataSource" ref="dataSource"/>
	</bean>
		
	<!-- 通知 -->
	<tx:advice id="txAdvice" transaction-manager="transactionManager">
		<tx:attributes>
			<!-- 傳播行爲 -->
			<tx:method name="save*" propagation="REQUIRED"/>
			<tx:method name="delete*" propagation="REQUIRED"/>
			<tx:method name="insert*" propagation="REQUIRED"/>
			<tx:method name="update*" propagation="REQUIRED"/>
			<tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
			<tx:method name="get*" propagation="SUPPORTS" read-only="true"/>
			<tx:method name="select*" propagation="SUPPORTS" read-only="true"/>
		</tx:attributes>
	</tx:advice>
	
	<!-- aop -->
	<aop:config>
		<aop:advisor advice-ref="txAdvice" pointcut="execution(* com.sw.service.impl.*.*(..))"/>
	</aop:config>
	
</beans>

5、接下來我們需要在web.xml文件中配置監聽器以及加載配置文件配置

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>ssm-template</display-name>
  
  <!-- spring配置 -->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:/spring/applicationContext-*.xml</param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  
</web-app>

如上,service層的配置也已經完畢,接下來,介紹一個加載spring配置文件的小程序,主要用於每次獲取bean時加載配置文件,避免每次加載所造成的資源浪費,當然在這裏也可以使用@Autowired來進行自動裝配加載,但是我個人比較習慣配置的方式,接下來編寫工具類,如下:

加載配置文件:

package com.sw.container;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/*
 *@Author swxctx
 *@time 2017年5月15日
 *@Explain:服務類,用用戶加載applicationContext.xml文件
 */
public class ServiceProvideCord {
	
	protected static ApplicationContext applicationContext;
	
	public static void load(String[] fileName){
		applicationContext = new ClassPathXmlApplicationContext(fileName);
	}
}

獲取service:

package com.sw.container;

import org.apache.commons.lang.StringUtils;

/*
 *@Author swxctx
 *@time 2017年5月15日
 *@Explain:Service層服務類
 */
@SuppressWarnings("static-access")
public class SwServiceProvider {
	private static ServiceProvideCord serviceProvideCord;
	
	//靜態加載
	static{
		serviceProvideCord = new ServiceProvideCord();
		serviceProvideCord.load(new String[]{"classpath:/spring/applicationContext-service.xml",
				"classpath:/spring/applicationContext-dao.xml",
				"classpath:/spring/applicationContext-transaction.xml"});
	}
	
	public  static Object getService(String serviceName){
		//服務名稱爲空
		if(StringUtils.isBlank(serviceName)){
			throw new RuntimeException("當前服務名稱不存在...");
		}
		Object object = null;
		if(serviceProvideCord.applicationContext.containsBean(serviceName)){
			//獲取bean
			object = serviceProvideCord.applicationContext.getBean(serviceName);
		}
		if(object==null){
			throw new RuntimeException("服務名稱爲【"+serviceName+"】下的服務節點不存在...");
		}
		return object;
	}
}

在這裏使用的是數組加載多個配置文件。

接下來我們可以進行測試了,如下:

package com.sw.test;

import org.junit.Test;
import com.sw.container.SwServiceProvider;
import com.sw.service.UserService;

/*
 *@Author swxctx
 *@time 2017年5月15日
 *@Explain:Service層測試
 */
public class UserServiceTest {
	
	@Test
	public void testLogin() throws Exception {
		UserService userService = (UserService) SwServiceProvider.getService("UserServiceImpl");
		String pass=userService.findLoginCheck("bs");
		System.out.println(pass);
	}

}

從上面的代碼我們可以看到,這裏使用了工具類SwServiceProvider來對bean進行獲取,測試結果如下:

如上所示,配置成功,接下來可以進行view層的開發了。


View層

view層使用Springmvc來對錶單進行處理,在這裏使用的是註解的方式進行Controller的開發,在這裏各有所長,也可以根據自己的喜好選擇配置文件的方式,或者繼承Request進行開發。

1、編寫登錄界面

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

	<form action="logincheck.action" mephod="post">
		用戶:<input type="text" id="username" name="username" placeholder="用戶名"><br>
		密碼:<input type="password" id="password" name="password" placeholder="密碼" ><br>
		<input type="submit" value="提交">
	</form>

</body>
</html>

2、成功界面

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>success</title>
</head>
<body>
	<p>登錄成功</p>
</body>
</html>

3、編寫失敗界面

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>err</title>
</head>
<body>
	<p>登錄失敗</p>
</body>
</html>

4、進行controller的開發

首先我們需要在springmvc.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:mvc="http://www.springframework.org/schema/mvc"
	xmlns:context="http://www.springframework.org/schema/context"
	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-3.2.xsd 
		http://www.springframework.org/schema/mvc 
		http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd 
		http://www.springframework.org/schema/context 
		http://www.springframework.org/schema/context/spring-context-3.2.xsd 
		http://www.springframework.org/schema/aop 
		http://www.springframework.org/schema/aop/spring-aop-3.2.xsd 
		http://www.springframework.org/schema/tx 
		http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">

	<!-- 掃描controller -->
	<context:component-scan base-package="com.sw.controller"></context:component-scan>
	
	<!-- 使用註解的方式開發 -->
	<!-- 配置適配器與映射器-通過drivern進行綜合 -->
	<mvc:annotation-driven></mvc:annotation-driven>
	
	<!-- 配置視圖解析器 -->
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<!-- 配置頁面路徑的前綴 -->
		<property name="prefix" value="/WEB-INF/page/"/>
		<!-- 配置jsp路徑的後綴 -->
		<property name="suffix" value=".html"/>
	</bean>
	
</beans>

5、進一步在web.xml中配置前端控制器

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>ssm-template</display-name>
  
  <!-- spring配置 -->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:/spring/applicationContext-*.xml</param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  
  <!-- 配置SpringMVC前端控制器 -->
  <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:/springmvc/springmvc.xml</param-value>
  	</init-param>
  </servlet>
  
  <servlet-mapping>
  	<servlet-name>springmvc</servlet-name>
  	<url-pattern>*.action</url-pattern>
  </servlet-mapping>
</web-app>

如上web.xml爲最終整體的配置。

6、接下來需要編寫vo對象,用於映射表單的數據(這裏更簡潔的辦法爲使用SpringMVC的參數綁定,即不需要編寫此文件,在實際開發中也應該使用參數綁定,通過User類注入即可,不用再編寫UserForm類),如下

package com.sw.view.form;
/*
 *@Author swxctx
 *@time 2017年5月16日
 *@Explain:vo對象
 */
public class UserForm {
	private String username;
	private String password;
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	
}

7、最後可以進行Controller的開發了,如下:

package com.sw.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.sw.container.SwServiceProvider;
import com.sw.service.UserService;
import com.sw.view.form.UserForm;

/*
 *@Author swxctx
 *@time 2017年5月16日
 *@Explain:完成登錄相關工作
 */
@Controller
public class LoginController{
	//vo對象
	//UserForm userForm = new UserForm();
	
	//service
	UserService userService = (UserService) SwServiceProvider.getService(UserService.SERVICE_NAME);
	
	//登錄驗證
	@RequestMapping("/logincheck")
	public ModelAndView loginCheck(UserForm userForm)throws Exception{
		String pass = userService.findLoginCheck(userForm.getUsername());
		ModelAndView modelAndView = new ModelAndView();
		//判斷
		if(userForm.getPassword().equals(pass)){
			modelAndView.setViewName("login/success");
		}else{
			modelAndView.setViewName("login/err");
		}
		return modelAndView;
	}
}

至此,ssm的整合已經完成了,接下來我們到瀏覽器測試一下。

登錄界面:


登錄成功:

登錄失敗:


結語:ssm的整合開發其實與ssh以及ssm2大同小異,其基本原理都是mvc,將項目分層開發,分層管理,從model到service再到view,其實就是一個用戶的操作過程逆向;獲取數據、裝配數據、顯示數據,按照這一規律進行開發,則已經很明瞭。

在本文中,其實並不適合學習,可以下載源碼進行相關的測試,更深入的學習,本章僅僅進行了整合,並沒有考慮資源的分配以及各種優化配置。

個人觀點,請多指教。






發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章