SSM框架整合(使用步骤)

1.导入SSM整合需要的jar包

2.准备配置文件和属性文件

(1)db.properties:设定连接数据库的属性:

mysql.driver=com.mysql.jdbc.Driver
mysql.url=jdbc:mysql://localhost:3306/mybatisdb?characterEncoding=utf8
mysql.username=root
mysql.password=root
validationQuery=SELECT 1
validationQuery用于验证查询,用于验证数据库是否能进行操作。

(2)log4j.properties:设置日志需要显示的对应信息

log4j.rootLogger=ERROR, stdout
log4j.logger.com.study.mapper.UsersMapper=DEBUG
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
(3)配置web.xml文件(结合web.xml文件的流程配置springMVC、Spring、Mybatis的配置文件):

a.web.xml中配置SpringMVC的前端控制器:

<!-- 配置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.xml</param-value>
		</init-param>
		<!-- 让servlet随服务启动 -->
		<load-on-startup>1</load-on-startup>
		<!-- 同异步设置,true为异步 -->
		<async-supported>true</async-supported>
	</servlet>
	<servlet-mapping>
		<servlet-name>SpringMVC</servlet-name>
		<url-pattern>*.action</url-pattern>
	</servlet-mapping>

这里由于配置springMVC的配置需要映射springmvc.xml,所以可以先去创建SpringMVC的配置文件并配置:

<?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:tx="http://www.springframework.org/schema/tx" 
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:c="http://www.springframework.org/schema/c"
	xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="
		http://www.springframework.org/schema/beans 
  		http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
  		http://www.springframework.org/schema/mvc
  		http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
  		http://www.springframework.org/schema/context
  		http://www.springframework.org/schema/context/spring-context-4.1.xsd">
	<!-- 扫描加载固定包下面的注解类 -->
	 <context:component-scan base-package="com.study.controller"/>
	<!-- 加载适配器和映射器等 -->
	<mvc:annotation-driven/>
	<!-- 加载静态文件 -->
	<mvc:default-servlet-handler/>
	<!-- 配置视图解析器 -->
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<!-- 前缀 
		<property name="prefix">
			<value>/WEB-INF/</value>
		</property>-->
		<!-- 后缀 -->
		<property name="suffix">
			<value>.jsp</value>
		</property>
	</bean>

</beans>

b. web.xml配置Spring

<context-param>
		<param-name>contextConfigLocation</param-name>
		<!-- 配置Spring的xml的固定写法 -->
		<param-value>classpath:applicationContext*.xml</param-value>
	</context-param>
	
		<!-- Spring监听器 -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	<!-- 防止Spring内存溢出监听器 -->
	<listener>
		<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
	</listener>

这里需要映射Spring的配置文件:applicationContext*.xml(*表示通配符,以这个 applicationContext开头的xml文件):

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:mybatis="http://mybatis.org/schema/mybatis-spring"    
    xmlns:context="http://www.springframework.org/schema/context"  
    xmlns:mvc="http://www.springframework.org/schema/mvc"  
    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.xsd  
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd  
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd  
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
        http://mybatis.org/schema/mybatis-spring  http://mybatis.org/schema/mybatis-spring.xsd  
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd"> 
<!-- 指明数据源使用的属性文件 -->
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
	<property name="locations">
		<list>
			<value>classpath:db.properties</value>
		</list>
	</property>
</bean>
<!-- mybatis:scan会将指定包下面的所有接口当做mapper处理,之后可以自动引入mapper接口,在这里可以先使用mybatis的逆向生成工具生成mapper,po,mapper.xml文件,详见下一篇文章:使用mybatis工具逆向生成mapper等文件 -->
<mybatis:scan base-package="com.study.mapper"/>

<!-- 扫描使用@service的注解类 -->
<context:component-scan base-package="com.study.service.imp"/>

<!-- 配置事务管理器 -->
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
	<property name="dataSource" ref="dataSource"></property>

</bean>       
 <!-- 启动AOP支持 -->
<aop:aspectj-autoproxy/>
<!-- 配置sqlSessionFactory -->   
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
	<property name="dataSource" ref="dataSource"></property>
	<property name="configLocation" value="classpath:mybatis-config.xml"></property><!-- 加载mybatis的配置文件 -->
	<property name="typeAliasesPackage" value="com.study.po"></property><!-- 定义别名,指定包下面的类 -->
</bean>   
</beans>

mybatis-config.xml: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">
 <!-- xml配置文件包含对MyBatis系统的核心配置 -->
<configuration>

	<!-- mappers告诉了MyBatis去哪里找持久化类的映射文件 -->
	<mappers>
		<mapper resource="com/study/mapping/UsersMapper.xml" />
		<!-- <mapper class="com.study.mapper.UserMapper"/>与上面实现的功能一样,只是写法不同 -->
	</mappers>
</configuration>

applicationContext-druid.xml:配置数据源,这里用到的是阿里巴巴的druid(德鲁伊)数据源

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

	<!-- 配置数据源,使用的是alibaba的Druid(德鲁伊)数据源 -->
	<!-- id与name是否相同 -->
    <bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
        <property name="url" value="${mysql.url}" />
        <property name="username" value="${mysql.username}" />
        <property name="password" value="${mysql.password}" />
        <!-- 初始化连接大小 -->
        <property name="initialSize" value="0" />
        <!-- 连接池最大使用连接数量 -->
        <property name="maxActive" value="20" />
        <!-- 连接池最大空闲 
        <property name="maxIdle" value="20" />
        -->
        <!-- 连接池最小空闲 -->
        <property name="minIdle" value="0" />
        <!-- 获取连接最大等待时间 -->
        <property name="maxWait" value="60000" />
        <!-- 
        <property name="poolPreparedStatements" value="true" /> 
        <property name="maxPoolPreparedStatementPerConnectionSize" value="33" /> 
        -->
        <property name="validationQuery" value="${validationQuery}" />
        <property name="testOnBorrow" value="false" />
        <property name="testOnReturn" value="false" />
        <property name="testWhileIdle" value="true" />
        <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
        <property name="timeBetweenEvictionRunsMillis" value="60000" />
        <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
        <property name="minEvictableIdleTimeMillis" value="25200000" />
        <!-- 打开removeAbandoned功能 -->
        <property name="removeAbandoned" value="true" />
        <!-- 1800秒,也就是30分钟 -->
        <property name="removeAbandonedTimeout" value="1800" />
        <!-- 关闭abanded连接时输出错误日志 -->
        <property name="logAbandoned" value="true" />
        <!-- 监控数据库 -->
        <!-- <property name="filters" value="stat" /> -->
        <property name="filters" value="mergeStat" />
    </bean>

	<!-- 输出可执行的SQL -->
	<!-- 参考:https://github.com/alibaba/druid/wiki/%E9%85%8D%E7%BD%AE_LogFilter -->
	<!-- 
	<bean id="log-filter" class="com.alibaba.druid.filter.logging.Log4jFilter">
		<property name="statementExecutableSqlLogEnable" value="true" />
	</bean>
	 -->

	<!-- 配置Spring监控 -->
	<!-- 参考:https://github.com/alibaba/druid/wiki/%E9%85%8D%E7%BD%AE_Druid%E5%92%8CSpring%E5%85%B3%E8%81%94%E7%9B%91%E6%8E%A7%E9%85%8D%E7%BD%AE -->
	<bean id="druid-stat-interceptor"
		class="com.alibaba.druid.support.spring.stat.DruidStatInterceptor">
	</bean>

	<bean id="druid-stat-pointcut" class="org.springframework.aop.support.JdkRegexpMethodPointcut"
		scope="prototype">
		<property name="patterns">
			<list>
				<value>com.study.service.*</value>
				<value>com.study.mapper.*</value>
			</list>
		</property>
	</bean>

	<aop:config>
		<aop:advisor advice-ref="druid-stat-interceptor"
			pointcut-ref="druid-stat-pointcut" />
	</aop:config>


</beans>

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:mybatis="http://mybatis.org/schema/mybatis-spring"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc" 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.xsd  
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd  
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd  
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
        http://mybatis.org/schema/mybatis-spring  http://mybatis.org/schema/mybatis-spring.xsd  
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd">
	<!-- 配置事务增强 -->
	<tx:advice id="txAdvice" transaction-manager="txManager">
		<!-- 事务属性定义 -->
		<!-- propagation="SUPPORTS":支持当前事务,如果当前没有事务,就以非事务方式执行。  -->
		<tx:attributes>
			<tx:method name="add*" propagation="REQUIRED" />
			<tx:method name="append*" propagation="REQUIRED" />
			<tx:method name="insert*" propagation="REQUIRED" />
			<tx:method name="save*" propagation="REQUIRED" />
			<tx:method name="update*" propagation="REQUIRED" />
			<tx:method name="modify*" propagation="REQUIRED" />
			<tx:method name="edit*" propagation="REQUIRED" />
			<tx:method name="delete*" propagation="REQUIRED" />
			<tx:method name="remove*" propagation="REQUIRED" />
			<tx:method name="repair" propagation="REQUIRED" />
			<tx:method name="delAndRepair" propagation="REQUIRED" />

			<tx:method name="get*" propagation="SUPPORTS" />
			<tx:method name="find*" propagation="SUPPORTS" />
			<tx:method name="load*" propagation="SUPPORTS" />
			<tx:method name="search*" propagation="SUPPORTS" />
			<tx:method name="datagrid*" propagation="SUPPORTS" />

			<tx:method name="*" propagation="SUPPORTS" />
		</tx:attributes>
	</tx:advice>
	<!-- 配置事务切面 -->
	<aop:config>
		<aop:pointcut id="aopid"
			expression="execution(* com.study.service.*Imp.*(..))" />
		<aop:advisor advice-ref="txAdvice" pointcut-ref="aopid" />
	</aop:config>

	<!-- 注解方式的事务管理 -->
	<!-- <tx:annotation-driven transaction-manager="txManager"/> -->
</beans>
这里Spring的配置文件和MyBatis的配置文件就配置完成了。

c.在web.xml中配置druid数据源Filter:在b项中需要用druid数据源,所以需要配置

<!-- Druid数据源Filter -->
	<filter>
		<filter-name>DruidWebStatFilter</filter-name>
		<filter-class>com.alibaba.druid.support.http.WebStatFilter</filter-class>
		<!-- 设置不过滤以下面为后缀的文件 -->
		<init-param>
			<param-name>exclusions</param-name>
			<param-value>*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>DruidWebStatFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	<!-- 配置监控数据库的servlet -->
	<servlet>
		<servlet-name>DruidStatView</servlet-name>
		<servlet-class>com.alibaba.druid.support.http.StatViewServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>DruidStatView</servlet-name>
		<url-pattern>/druid/*</url-pattern>
	</servlet-mapping>

d.在xml中配置编码过滤器:

<!-- 编码过滤器 -->
	<filter>
		<filter-name>encodingFilter</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
		<async-supported>true</async-supported>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>UTF-8</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>encodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
到这里需要配置的文件基本配置完成了。

3.使用MyBatis工具生成的mapper,mapper.xml,po如下:详见下一篇文章:使用mybatis工具逆向生成mapper等文件

po:Users.java

package com.study.po;

public class Users {
    private Integer id;

    private String username;

    private String password;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username == null ? null : username.trim();
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password == null ? null : password.trim();
    }

	@Override
	public String toString() {
		return "Users [id=" + id + ", username=" + username + ", password=" + password + "]";
	}
    
}

mapper:UsersMapper.java

package com.study.mapper;

import com.study.po.Users;

public interface UsersMapper {
    int deleteByPrimaryKey(Integer id);

    int insert(Users record);

    int insertSelective(Users record);

    Users selectByPrimaryKey(Integer id);

    int updateByPrimaryKeySelective(Users record);

    int updateByPrimaryKey(Users record);
}

mapper.xml:UsersMapper.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.study.mapper.UsersMapper">
  <resultMap id="BaseResultMap" type="com.study.po.Users">
    <id column="id" jdbcType="INTEGER" property="id" />
    <result column="username" jdbcType="VARCHAR" property="username" />
    <result column="password" jdbcType="VARCHAR" property="password" />
  </resultMap>
  <sql id="Base_Column_List">
    id, username, password
  </sql>
  <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
    select 
    <include refid="Base_Column_List" />
    from users
    where id = #{id,jdbcType=INTEGER}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
    delete from users
    where id = #{id,jdbcType=INTEGER}
  </delete>
  <insert id="insert" parameterType="com.study.po.Users">
    insert into users (id, username, password
      )
    values (#{id,jdbcType=INTEGER}, #{username,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR}
      )
  </insert>
  <insert id="insertSelective" parameterType="com.study.po.Users">
    insert into users
    <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="id != null">
        id,
      </if>
      <if test="username != null">
        username,
      </if>
      <if test="password != null">
        password,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides=",">
      <if test="id != null">
        #{id,jdbcType=INTEGER},
      </if>
      <if test="username != null">
        #{username,jdbcType=VARCHAR},
      </if>
      <if test="password != null">
        #{password,jdbcType=VARCHAR},
      </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="com.study.po.Users">
    update users
    <set>
      <if test="username != null">
        username = #{username,jdbcType=VARCHAR},
      </if>
      <if test="password != null">
        password = #{password,jdbcType=VARCHAR},
      </if>
    </set>
    where id = #{id,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.study.po.Users">
    update users
    set username = #{username,jdbcType=VARCHAR},
      password = #{password,jdbcType=VARCHAR}
    where id = #{id,jdbcType=INTEGER}
  </update>
</mapper>


4.编写controller,service,jsp:

UsersController.java:

package com.study.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.study.po.Users;
import com.study.service.UsersService;

@Controller
public class UserController {
	
	@Autowired//自动装配
	private UsersService usersService;

	@RequestMapping(value="/{fromName}")
	public String index(@PathVariable String fromName){
		return fromName;
	}
	
	@RequestMapping(value="/login")
	public String login(HttpServletRequest request,Model model){
		int id = Integer.parseInt(request.getParameter("id"));
		Users users = usersService.selectById(id);
		model.addAttribute("users", users);
		return "login";
		
	}
}
UsersService.java:

package com.study.service;

import com.study.po.Users;

public interface UsersService {

	Users selectById(Integer id);
}

UsersServiceImp.java:UsersService接口的实现类

package com.study.service.imp;

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

import com.study.mapper.UsersMapper;
import com.study.po.Users;
import com.study.service.UsersService;

@Service
public class UsersServiceImp implements UsersService{
	@Autowired
	private UsersMapper usersMapper;

	@Override
	public Users selectById(Integer id) {
		Users user = usersMapper.selectByPrimaryKey(id);
		return user;
	}

}

login.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="login.action">
<input type="text" name="id">
<input type="submit" value="提交">
</form>
${requestScope.users }
</body>
</html>


















评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值