欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

SSM(Spring+Spring MVC+Mybatis)框架整合过程

程序员文章站 2024-03-05 15:39:43
...

最近做一个项目用到了SSM框架,在此记录一下。本人萌新,错误之处,欢迎大家交流指正。

这里将实现一个简单的登录功能。

一、代码结构

为了方便管理,这里使用Maven来管理整个项目。代码结构如下图所示:

SSM(Spring+Spring MVC+Mybatis)框架整合过程

entity定义各种实体类。

dao数据接入,定义各种操作数据库的接口。

mapper存放mybatis数据库映射配置。

service业务层,定义各种业务接口。

serviceImpl对业务层接口的实现。

controller控制层,用于对业务模块的流程控制。


二、Mybatis与Spring的整合

1、pom.xml配置

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>cn.ipoc</groupId>
  <artifactId>ssmtest</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>Maven Webapp Archetype</name>
  <url>http://maven.apache.org</url>
  
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <spring.version>4.1.4.RELEASE</spring.version>
    <jackson.version>2.5.0</jackson.version>
  </properties>
  
  <dependencies>
  
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    
    <!-- spring配置 -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-beans</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>${spring.version}</version>
      <scope>test</scope>
    </dependency>
    
    <!-- mybatis 包 -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.2.8</version>
    </dependency>

    <!--mybatis spring 插件 -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.2.2</version>
    </dependency>

    <!-- mysql连接 -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.44</version>
    </dependency>
    
    <!-- 数据源 -->
    <dependency>
      <groupId>com.mchange</groupId>
      <artifactId>c3p0</artifactId>
      <version>0.9.5-pre8</version>
    </dependency>

    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjweaver</artifactId>
      <version>1.8.4</version>
    </dependency>
    
    <!-- servlet -->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>3.0-alpha-1</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>
    
  </dependencies>
  <build>
    <finalName>ssmtest</finalName>
    <plugins>  
        <!-- define the project compile level -->  
        <plugin>  
            <groupId>org.apache.maven.plugins</groupId>  
            <artifactId>maven-compiler-plugin</artifactId>  
            <version>2.3.2</version>  
            <configuration>  
                <source>1.8</source>  
                <target>1.8</target>  
            </configuration>  
        </plugin>  
    </plugins>  
  </build>
</project>


2、web.xml配置

<web-app xmlns="http://java.sun.com/xml/ns/javaee"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   
                        http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"  
                        version="3.0">  
    <!-- <display-name>Archetype Created Web Application</display-name> -->  
    
    <!-- Spring配置 -->
    <!-- 配置Spring配置文件路径,让ContextLoaderListener进行解析 -->  
    <context-param>
    	<param-name>contextConfigLocation</param-name>
    	<param-value>classpath:applicationContext.xml</param-value>
    </context-param>
    
   	<!-- 配置Spring上下文监听器,再启动WEB容器时,
   	              自动装载applicationContext.xml配置 -->
   	<listener>
   		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
   	</listener>
   	
   	<!-- 配置Spring字符编码过滤器 -->
   	<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>/*</url-pattern>
    </filter-mapping>
</web-app>  


3、applicationContext配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
      http://www.springframework.org/schema/context
      http://www.springframework.org/schema/context/spring-context.xsd">
      
      <!-- 引入jdbc配置 -->
      <context:property-placeholder location="classpath:jdbc.properties"/>
      
      <!-- 扫描文件-->
      <context:component-scan base-package="cn.ipoc"/>

      <!--配置数据源-->
      <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
	      <property name="driverClass" value="${jdbc_driverClassName}"/>
	      <property name="jdbcUrl" value="${jdbc_url}"/>
	      <property name="user" value="${jdbc_username}"/>
	      <property name="password" value="${jdbc_password}"/>
	      <!--连接池中保存的最大连接数目-->
	      <property name="maxPoolSize" value="${maxPoolSize}"/>
	      <!--连接池中保存的最少连接数目-->
	      <property name="minPoolSize" value="${minPoolSize}"/>
	      <!-- 初始化连接大小 -->
	      <property name="initialPoolSize" value="${initialPoolSize}"/>
	      <!-- 获取连接最大等待时间 -->
	      <property name="maxConnectionAge" value="${maxConnectionAge}"/>
	      <!-- 连接池最大空闲 -->
	      <property name="maxIdleTime" value="${maxIdleTime}"/>
      </bean>
     	
      <!--配置sqlSessionFactory 并将数据源注入-->
      <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
	      <!--注入数据源-->
	      <property name="dataSource" ref="dataSource"/>
	      <!--指定要使用到的mybatis配置文件-->
	      <property name="configLocation" value="classpath:mybatis-config.xml"/>
	      <!--用于配置mapper映射xml-->
	      <property name="mapperLocations" value="classpath*:cn/ipoc/mapper/*.xml"/>
      </bean>
      
      <!-- 创建数据映射器-->
      <bean  class="org.mybatis.spring.mapper.MapperScannerConfigurer">
          <property name="basePackage" value="cn.ipoc.dao"/>
          <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>  
      </bean>
      <!-- 对数据源进行事务管理 -->
      <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
      	  <property name="dataSource" ref="dataSource"/>
      </bean>
      
</beans>

4、jdbc.properties配置

jdbc.properties保存数据库相关信息,需要根据数据库配置进行修改。

jdbc_driverClassName=com.mysql.jdbc.Driver
jdbc_url=jdbc:mysql://localhost:3306/test_my?characterEncoding=utf8
jdbc_username=root
jdbc_password=123456
maxPoolSize=20
minPoolSize=2
initialPoolSize=2
maxConnectionAge=6000
maxIdleTime=60


5、mybatis-config配置

为了方便后续编程,在mybatis的配置文件中为实体类设置简短别名。

<?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>

    <!--为cn.ipoc.entity.User 设置别名 User 方便调用-->
    <typeAliases>
        <typeAlias alias="User" type="cn.ipoc.entity.User"/>
    </typeAliases>
   
</configuration>

配置完成后,可以开始设计相关数据库表结构。


6、User类

现在开始实现entity下的User类。

package cn.ipoc.entity;

public class User {
	private String uid;
	private String password;
	
	public User() {
		super();
	}
	
	//初始化构造函数
	public User(String uid,String password) {
		this.uid=uid;
		this.password=password;
	}
	
	public String getUid() {
		return uid;
	}
	public void setUid(String uid) {
		this.uid=uid;
	}
	
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password=password;
	}
}

7、dao接口

在"cn.ipoc.dao"中定义UserDao接口。

package cn.ipoc.dao;

import cn.ipoc.entity.User;

public interface UserDao {
	public User selectById(String uid);
}


8、映射文件

在"cn.ipoc.mapper"中配置mybatis映射文件。

<?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">

 <!--namespace用于与DAO层的接口类进行绑定,这样我们无需实现DAO层的接口
  类,其接口类就能够自动的找到相关的SQL语句进行绑定实现-->

<mapper namespace="cn.ipoc.dao.UserDao">
    <!--select表示查询,它的id名称必须与DAO层接口的方法名相同,否则无法绑定-->    
    <select id="selectById" parameterType="String" resultType="User">
        select * from user where uid = #{id}
    </select>
</mapper>


9、测试

至此,Mybatis与Spring整合的相关配置已基本完成。下面在"cn.ipoc.test"下定义一个test类来测试整合是否成功。

package cn.ipoc.test;

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

import cn.ipoc.dao.UserDao;
import cn.ipoc.entity.User;

public class test {
	private static ApplicationContext ac;
	static {
	         ac = new ClassPathXmlApplicationContext("applicationContext.xml");
	}
	public static void main(String[] args) {
		
		UserDao mapper = (UserDao) ac.getBean("userDao");
		User user = mapper.selectById("user001");
		System.out.println("user="+user.getUid()+"\n"+"password="+user.getPassword());
	}
}

如果整合成功,控制台会输出如下信息:

SSM(Spring+Spring MVC+Mybatis)框架整合过程

三、Mybatis与Spring MVC整合

在完成Mybatis和Spring的整合后,接下来开始Mybatis与Spring MVC的整合。

首先在web.xml中配置Spring MVC的前端控制器DispatcherServlet。

1、web.xml

<!-- springMVC 核心控制器  DispatcherServlet 配置 -->
    <servlet>
    	<servlet-name>dispatcher</servlet-name>
    	<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    	<init-param>
    		<!-- 标明springmvc配置位置 -->
    		<param-name>contextConfigLocation</param-name>
    		<param-value>classpath:spring-mvc.xml</param-value>
    	</init-param>
    	<load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
    	<servlet-name>dispatcher</servlet-name>
    	<!-- 拦截所有*.do 的请求,交给DispatcherServlet处理,性能最好 -->
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>
    
    <!-- 设定默认的首页 -->
    <welcome-file-list>
    	<welcome-file>login.jsp</welcome-file>
    </welcome-file-list>

2、spring-mvc.xml

接下来在spring-mvc.xml中配置Spring MVC的框架,存放在"src/main/resources"下。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc" 
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
      http://www.springframework.org/schema/context
      http://www.springframework.org/schema/context/spring-context.xsd
      http://www.springframework.org/schema/mvc
      http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">
	
	<!-- 配置扫描控制器, Spring自动到 cn.ipoc.controller下
	              扫描带有@controller @service @component等注解等类,将他们自动实例化-->
	<context:component-scan base-package="cn.ipoc" />
	
	<!--<mvc:annotation-driven /> 会自动注册DefaultAnnotationHandlerMapping与
	     AnnotationMethodHandlerAdapter 两个bean,它解决了一些 @controller 注解使用时的提前配置-->
    <mvc:annotation-driven />
	
	<!-- 配置页面控制器 -->
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/"/>
		<property name="suffix" value=".jsp" /> 
    </bean>
    
</beans>


3、业务实现

在"cn.ipoc.service"中编写接口类UserService。

package cn.ipoc.service;

public interface UserService {
	public int login(String username,String password);
}


接下来,在"cn.ipoc.serviceImpl"中编写UserServiceImpl类实现UserService中的login方法。

package cn.ipoc.serviceIpml;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.ipoc.dao.UserDao;
import cn.ipoc.entity.User;
import cn.ipoc.service.UserService;

@Service("UserService")
public class UserServiceImpl implements UserService{

	//自动注入userdao 用于访问数据库
	@Autowired
	UserDao userDao;

	public int login(String username, String password) {
		// TODO Auto-generated method stub
		User user=userDao.selectById(username);
		if(null!=user) {
			if(user.getUid().equals(username)&&user.getPassword().equals(password)) {
				return 0; //登录成功
			}else {
				return 1; //用户名或密码错误
			}
		}else {
			return 2;     //用户不存在
		}
	}
}

4、控制层实现

在"cn.ipoc.controller"中实现LoginCtrl类,用于处理前端提交的业务。

package cn.ipoc.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import cn.ipoc.service.UserService;

//@Controller 注解表示本类为web层控制组件
@Controller
//@RequestMapping("/user") 用于标定访问时对url位置
@RequestMapping("/user")
@Scope("prototype")
public class LoginCtrl {
	//自动注入业务层的UserService类
	@Autowired
	UserService userService;
	
	//login业务的访问位置为  /user/login
	@RequestMapping("/login")
	public String login(HttpServletRequest request) 
			throws ServletException, IOException{
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		int loginStatus = userService.login(username, password);
		if(loginStatus==0) {
			request.setAttribute("msg", "登录成功");
		}else if(loginStatus==1) {
			request.setAttribute("msg", "用户名或密码错误");
		}else {
			request.setAttribute("msg", "用户不存在");
		}
		return "status";
	}
}

5、jsp实现

login.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
<head>
    <title></title>
</head>
<body>
<form name="form" action="<%=basePath %>user/login.do" method="post" >
  <table width="300" border="1" align="center">
  <tr>
    <td colspan="2">登入窗口</td>
  </tr>
  <tr>
      <td>用户名:</td>
      <td><input type="text" name="username">
      </td>
  </tr>
  <tr>
      <td>密码:</td>
      <td><input  type="password" name="password"/>
      </td>
  </tr>
  <tr>
    <td colspan="2">
      <input type="submit" name="submit" value="登录"/>
    </td>
  </tr>
  </table>
</form>
</body>
</html>

status.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
<head>
    <title></title>
</head>
<body>
<br>
${msg}
<br>

</body>
</html>

至此,所有的整合工作已完成。看一下整合结果吧。

登录界面

SSM(Spring+Spring MVC+Mybatis)框架整合过程

登录成功

SSM(Spring+Spring MVC+Mybatis)框架整合过程

登录失败

SSM(Spring+Spring MVC+Mybatis)框架整合过程

相关标签: Java SSM