SSM的整合(spring+springmvc +mybatis)

spring+springmvc +mybatis的整合

1.创建项目

在这里插入图片描述

2.导包

1.spring+springmvc
2.mybatis+spring-mybaits
3.pageHelper插件
3.相关数据源
5.mysql

在这里插入图片描述

3.集成spring+mybaits[无mybatis.cfg.xml]

1.创建log4j.properties
# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# MyBatis logging configuration...
log4j.logger.org.mybatis.example.BlogMapper=TRACE
# 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
2.创建application-dao.xml
<?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" 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
        ">
	<!-- 声明数据源 -->
	<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<!-- 注入数据库的连接属性 -->
		<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
		<property name="url" value="jdbc:mysql://127.0.0.1:3306/test"></property>
		<property name="username" value="root"></property>
		<property name="password" value="123456"></property>
	</bean>
	
	<!-- 声明mybatis的配置 -->
	<bean id="configuration" class="org.apache.ibatis.session.Configuration">
		<!-- 设置日志输出形式 -->
		<property name="logImpl" value="org.apache.ibatis.logging.log4j.Log4jImpl" ></property>
	</bean>
	<!-- 声明sqlSessionFactory -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<!-- 注入 数据源-->
		<property name="dataSource" ref="dataSource"></property>
		<!-- 配置configration  configLocation这两个属性不能同时存在-->
		<property name="configuration" ref="configuration"></property>
		<!-- 配置插件 -->
		<property name="plugins">
			<!-- 分页插件 -->
			<array>
				<bean class="com.github.pagehelper.PageInterceptor"></bean>
			</array>
		</property>
		<!-- 配置映射文件 -->
		<property name="mapperLocations" >
			<array>
				<value>classpath:mapper/*Mapper.xml</value>
			</array>
		</property>
	</bean>
	 
	 
	 <!-- 配置mapper的扫描 -->
	 <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
	 	<!-- 注入扫描的包 -->
	 	<property name="basePackage">
	 		<value>com.sxt.mapper</value>
	 	</property>
	 	<!-- 注入sqlSessionFactory -->
	 	<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
	 	
	 </bean>
	
	
	

</beans>


3.创建application-service.xml
<?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" 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/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
        ">
	<!-- 扫描 -->
	<context:component-scan base-package="com.sxt.service.impl"></context:component-scan>
	
	<!-- 声明一个事务管理器 -->
	<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<!-- 注入数据源 -->
		<property name="dataSource" ref="dataSource"></property>
	</bean>
	
	<!-- 配置事务的传播特性-->
	<tx:advice id="myAdvise" transaction-manager="transactionManager">	
		<!-- 配置方法的传播特性 -->
		<tx:attributes>
		
			<!-- 
			propagation  的属性值 说明
				REQUIRED 如果当前没有事务,就新建一个事务,如果已经存在一个事务中,加入到这个事务中。这是最常见的选择。
				SUPPORTS 支持当前事务,如果当前没有事务,就以非事务方式执行。  [不推荐]
				MANDATORY 使用当前的事务,如果当前没有事务,就抛出异常。  [不推荐]
				REQUIRES_NEW 新建事务,如果当前存在事务,把当前事务挂起。  [不推荐]
				NOT_SUPPORTED 以非事务方式执行操作,如果当前存在事务,就把当前事务挂起。 [不推荐]
				NEVER 以非事务方式执行,如果当前存在事务,则抛出异常。 [不推荐]
				NESTED 如果当前存在事务,则在嵌套事务内执行。如果当前没有事务,则执行与REQUIRED类 似的操作  【可能用到】
				read-only="true",只读事务,对数据库只能是查询操
				timeout :设置事务的超时时间  -1代表没有超时时间   500 如果service的方法500毫秒还执行完成,那么就回滚事务
			 -->
			<tx:method name="add*" propagation="REQUIRED"/>
			<tx:method name="save*" propagation="REQUIRED"/>
			<tx:method name="update*" propagation="REQUIRED"/>
			<tx:method name="mod*" propagation="REQUIRED"/>
			<tx:method name="delete*" propagation="REQUIRED"/>
			<tx:method name="del*" propagation="REQUIRED"/>
			<tx:method name="reset*" propagation="REQUIRED"/>
			<tx:method name="*" read-only="true"/>
		</tx:attributes>
	</tx:advice>
	
	<!-- 进行AOP织入 -->
	<aop:config>
		<!-- 声明切面 -->
		<aop:pointcut expression="execution(* com.sxt.service.impl.*.*(..))" id="pc"/>
		<!-- 织入 -->
		<aop:advisor advice-ref="myAdvise" pointcut-ref="pc"/>
	</aop:config>
	
</beans>


4.创建applicationContext.xml
<?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" 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
        ">
   	<import resource="classpath:application-dao.xml"/>
   	<import resource="classpath:application-service.xml"/>

</beans>


5.测试是否集成成功

在这里插入图片描述

4.集成springmvc

1.创建springmvc.xml
<?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"
	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/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        ">
	<!-- 扫描控制器 -->
	<context:component-scan base-package="com.sxt.controller"></context:component-scan>
	<!-- 启动配置注解的映射器 -->
	<mvc:annotation-driven></mvc:annotation-driven>
	<!-- 配置视图解析器 -->
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<!-- 配置转发地址的前缀 -->
		<property name="prefix" value="/WEB-INF/view/"></property>
		<!-- 配置转发地址的后缀缀 -->
		<property name="suffix" value=".jsp"></property>
	</bean>
	<!-- 过滤放行静态资源文件 -->
	<mvc:default-servlet-handler/>
</beans>
2.配置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>06_ssm</display-name>
  
   <!-- 编码过滤器开始 -->
  <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>
  </filter>
  <filter-mapping>
  	<filter-name>encodingFilter</filter-name>
  	<!-- <url-pattern>/*</url-pattern> -->
  	<servlet-name>springmvc</servlet-name>
  </filter-mapping>
  
  <!-- 编码过滤器结束-->
  
  <!-- 配置spirng的监听器加载spring的配置文件 开始 -->
  <listener>
  	<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <context-param>
  	<!-- 在ContextLoaderListener-ContextLoader-CONFIG_LOCATION_PARAM-contextConfigLocation -->
  	<param-name>contextConfigLocation</param-name>
  	<param-value>classpath*:applicationContext.xml</param-value>
  </context-param>
  <!-- 配置spirng的监听器加载spring的配置文件 结束 -->
  
  <!-- 配置springmvc的前端控制器开始 -->
  <servlet>
  	<servlet-name>springmvc</servlet-name>
  	<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  	<!-- 注入配置文件的路径 spirngmvc.xml -->
  	<init-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath*:springmvc.xml</param-value>  	
  	</init-param>
  	<!-- 容器启动时创建对象 -->
  	<load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
  	<servlet-name>springmvc</servlet-name>
  	<!-- 
		  	第一种:*.action,访问以.action结尾 由DispatcherServlet进行解析
		  	第二种:/,所以访问的地址都由DispatcherServlet进行解析,对于静态文件的解析需要配置不让DispatcherServlet进行解析
		  	使用此种方式可以实现 RESTful风格的url
  		 -->
		<url-pattern>*.action</url-pattern>
  </servlet-mapping>
 <!-- 配置springmvc的前端控制器结束 -->
  
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>
3.发布到tomcat启动测试

5.完成sys_user表的查询

1.创建表

在这里插入图片描述

2.创建User

在这里插入图片描述

3.创建UserMapper

在这里插入图片描述

4.创建UserMapper.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.sxt.mapper.UserMapper" >
  <resultMap id="BaseResultMap" type="com.sxt.domain.User" >
    <id column="user_id" property="userId" jdbcType="INTEGER" />
    <result column="user_name" property="userName" jdbcType="VARCHAR" />
    <result column="user_address" property="userAddress" jdbcType="VARCHAR" />
    <result column="user_birthday" property="userBirthday" jdbcType="DATE" />
  </resultMap>
  <sql id="Base_Column_List" >
    user_id, user_name, user_address, user_birthday
  </sql>
  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
    select 
    <include refid="Base_Column_List" />
    from sys_user
    where user_id = #{userId,jdbcType=INTEGER}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
    delete from sys_user
    where user_id = #{userId,jdbcType=INTEGER}
  </delete>
  <insert id="insert" parameterType="com.sxt.domain.User" >
    insert into sys_user (user_id, user_name, user_address, 
      user_birthday)
    values (#{userId,jdbcType=INTEGER}, #{userName,jdbcType=VARCHAR}, #{userAddress,jdbcType=VARCHAR}, 
      #{userBirthday,jdbcType=DATE})
  </insert>
  <insert id="insertSelective" parameterType="com.sxt.domain.User" >
    insert into sys_user
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="userId != null" >
        user_id,
      </if>
      <if test="userName != null" >
        user_name,
      </if>
      <if test="userAddress != null" >
        user_address,
      </if>
      <if test="userBirthday != null" >
        user_birthday,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="userId != null" >
        #{userId,jdbcType=INTEGER},
      </if>
      <if test="userName != null" >
        #{userName,jdbcType=VARCHAR},
      </if>
      <if test="userAddress != null" >
        #{userAddress,jdbcType=VARCHAR},
      </if>
      <if test="userBirthday != null" >
        #{userBirthday,jdbcType=DATE},
      </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="com.sxt.domain.User" >
    update sys_user
    <set >
      <if test="userName != null" >
        user_name = #{userName,jdbcType=VARCHAR},
      </if>
      <if test="userAddress != null" >
        user_address = #{userAddress,jdbcType=VARCHAR},
      </if>
      <if test="userBirthday != null" >
        user_birthday = #{userBirthday,jdbcType=DATE},
      </if>
    </set>
    where user_id = #{userId,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.sxt.domain.User" >
    update sys_user
    set user_name = #{userName,jdbcType=VARCHAR},
      user_address = #{userAddress,jdbcType=VARCHAR},
      user_birthday = #{userBirthday,jdbcType=DATE}
    where user_id = #{userId,jdbcType=INTEGER}
  </update>
  
  <!-- 全查询 -->
  <select id="queryAllUser" resultMap="BaseResultMap" >
    select 
    <include refid="Base_Column_List" />
    from sys_user
  </select>
</mapper>
5.创建UserVo

和页面上的表单数据对应
在这里插入图片描述

6.创建UserService

在这里插入图片描述

7.创建UserServiceImpl

@Service
public class UserServiceImpl implements UserService {

	@Autowired
	private UserMapper userMapper;

	@Override
	public void addUser(UserVo userVo) {
		userMapper.insertSelective(userVo);
	}

	@Override
	public void updateUser(UserVo userVo) {
		userMapper.updateByPrimaryKeySelective(userVo);
	}
	@Override
	public void deleteUser(Integer userId) {
		userMapper.deleteByPrimaryKey(userId);
	}
	@Override
	public User queryUserById(Integer userId) {
		return userMapper.selectByPrimaryKey(userId);
	}
	@Override
	public List<User> queryAllUser() {
		return userMapper.queryAllUser();
	}

}

8.创建UserController

在这里插入图片描述

9.创建index.jsp

在这里插入图片描述

10.创建list.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://"
			+ request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>用户列表</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
</head>

<body>
	<h1>
		所有用户
	</h1>
	<hr>
	<table border="1" width="100%" cellpadding="5" cellspacing="5">
		<tr>
			<th>编号</th>
			<th>姓名</th>
			<th>地址</th>
			<th>生日</th>
		</tr>
		<c:forEach var="sn" items="${list }">
			<tr>
				<td align="center">${sn.userId }</td>
				<td align="center">${sn.userName }</td>
				<td align="center">${sn.userAddress }</td>
				<td align="center">
				<fmt:formatDate value="${sn.userBirthday }" pattern="yyyy-MM-dd HH:mm:ss"/>
				</td>
			</tr>
		</c:forEach>
	</table>
</body>
</html>

6.完成sys_user表的添加

1.修改list.jsp

在这里插入图片描述

2.创建add.jsp

在这里插入图片描述

3.修改UserController

在这里插入图片描述

7.完成sys_user表的修改删除

1.修改list.jsp

在这里插入图片描述

2.创建update.jsp

在这里插入图片描述

3.修改UserController

/**
	 * 跳转到修改页面
	 */
	@RequestMapping("toUpdateUser")
	public String toUpdateUser(UserVo userVo){
		User user=this.userService.queryUserById(userVo.getUserId());
		/**
		 * 参数1数据来源对象
		 * 参数2目标对象
		 * 参数3忽略的属性
		 */
		BeanUtils.copyProperties(user, userVo,"userId");
		return "update";
	}
	
	/**
	 * 修改用户
	 */
	@RequestMapping("updateUser")
	public String updateUser(UserVo userVo){
		this.userService.updateUser(userVo);
		return "redirect:loadAllUser.action";
	}
	
	/**
	 * 删除用户
	 */
	@RequestMapping("deleteUser")
	public String deleteUser(UserVo userVo){
		this.userService.deleteUser(userVo.getUserId());
		return "redirect:loadAllUser.action";
	}
	

8.优化${pageContext.request.contextPath }

思路:全局都是使用/bjsxt这个根路径
/bjsxt= servletContext.getContextPath()
监听ServletContext的创建,再向servletContext里面放/bjsxt
在这里插入图片描述

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值