SSM框架整合
1、整合步骤:
创建项目,添加 jar 包
创建包,创建实体与 Mapper
添加连接数据库的 properties 文件
添加 Log4j 配置文件
添加 Spring 配置文件
添加 SpringMVC 配置文件
修改 web.xml 文件
2.使用工具生成
3.1添加数据库与 log4j 配置文件
3.1.1 添加连接数据的 properties 文件
3.1.2 添加 log4j 配置文件
3.1.2 添加 log4j 配置文件
3.2添加 Spring 配置文件
在 SSM 框架整合时为了能够清晰的对 Spring 配置项进行管理,我们可以采用“分而治
之”的方式来定义 Spring 配置文件。将 Spring 配置文件分解成三个配置文件,在不同的配置文件中配置不同的内容。
applicationContext-dao.xml
该配置文件的作用是用来配置与 Mybatis 框架整合。
applicationContext-trans.xml
该配置文件的作用是用来配置 Spring 声明式事务管理。
applicationContext-service.xml
该配置文件的作用是用来配置注解扫描以及其他的 Spring 配置。
applicationContext-dao.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"
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.xsd"
>
<!--配置解析 Properties 文件的工具类-->
<context:property-placeholder
location="classpath:db.properties"/>
<!--配置数据源-->
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!--配置 SqlSessionFactory-->
<bean id="sqlSessionFactoryBean"
class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="typeAliasesPackage" value="com.bjsxt.pojo"/>
</bean>
<!--配置 MapperScannerConfigurer-->
<bean id="mapperScannerConfigurer"
class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.bjsxt.mapper"/>
</bean>
</beans>
3.2.2 配置声明式事务管理
applicationContext-trans.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: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/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!--配置事务管理器的切面-->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--配置事务属性-->
<tx:advice id="myAdvice"
transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="add*" propagation="REQUIRED"/>
<tx:method name="modify*" propagation="REQUIRED"/>
<tx:method name="drop*" propagation="REQUIRED"/>
<tx:method name="find*" read-only="true"/>
</tx:attributes>
</tx:advice>
<!--配置切点-->
<aop:config>
<aop:pointcut id="myPointcut" expression="execution(*
com.bjsxt.service.*.*(..))"/>
<aop:advisor advice-ref="myAdvice"
pointcut-ref="myPointcut"/>
</aop:config>
</beans>
3.2.3 配置注解扫描
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: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/context
http://www.springframework.org/schema/context/spring-context.xsd"
>
<!-- 配置注解扫描-->
<context:component-scan base-package="com.bjsxt.service"/>
</beans>
3.3配置 SpringMVC
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:context="http://www.springframework.org/schema/context"
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/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.bjsxt.web.controller"/>
<!-- 配置注解驱动-->
<mvc:annotation-driven/>
<!-- 配置视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!--配置静态资源映射器-->
<mvc:resources mapping="/js/**" location="/WEB-INF/js/"/>
<mvc:resources mapping="/img/**" location="/WEB-INF/img/"/>
<mvc:resources mapping="/css/**" location="/WEB-INF/css/"/>
</beans>
3.4Spring 与 SpringMVC 父子容器问题
在 Spring 与 Springmvc 同时使用时,Spring 的 ContextLoaderListener 会创建的 SpringIOC容器,SpringMVC 的 DispatcherServlet 会创建 SpringMVC 的 IOC 容器。SpringMVC会将 SpringIOC 容器设置为父容器
正确使用方式:
在 SpringMVC 的配置文件中扫描@Controller 注解,在 Spring 的配置文件中扫描除了
@Controller 以外的其他注解。在 SpringMVC 的控制器可以注入 SpringIOC 容器中的 Bean 对象,因为父容器对子容器是可见的。
3.5配置 web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!--指定 Spring 配置文件的位置以及名称-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext-*.xml</param-value>
</context-param>
<!--配置启动 Spring 框架的监听器-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderList
ener</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.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- 配置字符编码过滤器-->
<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>
</filter-mapping>
</web-app>
4 实现用户登录业务
需求:实现用户登录业务,同时记录用户的登录日志。登录日志要求记录用户名、登录
时间以及登录的 IP 地址。
4.1实现用户登录
4.1.1 创建业务层
public interface UsersService {
Users userLogin(Users users);
}
/**
* 用户登录业务层
*/
@Service
public class UsersServiceImpl implements UsersService {
80
@Autowired
private UsersMapper usersMapper;
/**
* 用户登录
* @param users
* @return
*/
@Override
public Users userLogin(Users users) {
UsersExample usersExample = new UsersExample();
UsersExample.Criteria criteria =
usersExample.createCriteria();
criteria.andUsernameEqualTo(users.getUsername());
criteria.andUserpwdEqualTo(users.getUserpwd());
List<Users> list =
this.usersMapper.selectByExample(usersExample);
if(list == null || list.size() <= 0){
throw new UserNotFoundException("用户名或密码有误!");
}
return list.get(0);
}
}
4.1.2 创建自定义异常
/**
* 自定义异常,表示用户登录状态
*/
public class UserNotFoundException extends RuntimeException {
public UserNotFoundException(){
}
public UserNotFoundException(String msg){
super(msg);
}
public UserNotFoundException(String msg,Throwable throwable){
super(msg,throwable);
}
}
4.1.3 创建用户登录控制器
/**
* 用户管理控制器
*/
@Controller
@RequestMapping("/user")
public class UsersController {
@Autowired
private UsersService usersService;
/**
* 处理用户登录请求
*/
@RequestMapping("/userLogin")
public String userLogin(Users users, HttpSession session){
Users user = this.usersService.userLogin(users);
session.setAttribute("user",user);
return "redirect:/page/index";
}
}
4.1.4 全局异常处理器
/**
* 全局异常处理器
*/
@ControllerAdvice
public class GlobalExceptionController {
@ExceptionHandler({com.bjsxt.exception.UserNotFoundException.clas
s})
public String userNotFoundExceptionHandler(Exception e, Model
82
model){
model.addAttribute("msg",e.getMessage());
return "login";
}
@ExceptionHandler({java.lang.Exception.class})
public String exceptionHandler(Exception e){
return "redirect:/page/error";
}
}
4.1.5 创建用户登录页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
${msg}
<form action="/user/userLogin" method="post">
登录名:<input type="text" name="username"/><br/>
密码:<input type="password" name="userpwd"/><br/>
<input type="submit" value="OK"/>
</form>
</body>
</html>
4.1.6 创建异常提示页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
出错了!请求与管理员联系:oldlu@bjsxt.com
</body>
</html>
4.1.7 创建页面跳转控制器
/**
* 页面跳转控制器
*/
@Controller
public class PageController {
/**
* 请求首页
*/
@RequestMapping("/")
public String showIndex(){
return "index";
}
/**
* 处理页面跳转请求
*/
@RequestMapping("/page/{page}")
public String showPage(@PathVariable String page){
return page;
}
}
4.1.8 创建判断用户是否登录的拦截器
/**
* 判断用户是否登录
*/
public class LoginInterceptor implements HandlerInterceptor {
/**
84
* 判断用户是否登录
* @param request
* @param response
* @param handler
* @return
* @throws Exception
*/
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
HttpSession session = request.getSession();
Users user = (Users) session.getAttribute("user");
if(user == null || user.getUsername().length() <= 0){
response.sendRedirect("/page/login");
return false;
}
return true;
}
@Override
public void postHandle(HttpServletRequest request,
HttpServletResponse response, Object handler, ModelAndView
modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex) throws
Exception {
}
}
4.1.9 配置拦截器
<!--配置拦截器-->
<mvc:interceptors>
<mvc:interceptor>
85
<mvc:mapping path="/**"/>
<mvc:exclude-mapping path="/page/login"/>
<mvc:exclude-mapping path="/user/userLogin"/>
<mvc:exclude-mapping path="/page/error"/>
<bean class="com.bjsxt.interceptor.LoginInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>
4.2记录用户登录日志
4.2.1 创建表
CREATE TABLE `logs` (
`logid` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(30) DEFAULT NULL, `ip` varchar(30) DEFAULT NULL, `logtime` date DEFAULT NULL, PRIMARY KEY (`logid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
4.2.2 创建实体类与 Mapper
4.2.3 创建日志记录切面
/**
* 用户登录日志记录切面
*/
@Aspect
@Component
public class UsersLoginLogAOP {
@Autowired
private LogsMapper logsMapper;
/**
* 配置切点
*/
@Pointcut("execution(*com.bjsxt.service.UsersService.userLogin(..))")
public void myPointcut(){
}
/**
* 在后置通知中记录登录日志
*/
@AfterReturning("myPointcut()")
public void userLoginLog(JoinPoint joinPoint){
Object[] objects = joinPoint.getArgs();
UsersExt users = (UsersExt)objects[0];
Logs logs = new Logs();
logs.setLogtime(new Date());
logs.setUsername(users.getUsername());
logs.setIp(users.getIp());
this.logsMapper.insertSelective(logs);
}
}
4.2.4 创建 Users 扩展实体类
public class UsersExt extends Users {
private String ip;
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
}
4.2.5 修改控制器
/**
* 处理用户登录请求
*/
@RequestMapping("/userLogin")
public String userLogin(UsersExt users, HttpSession session,
HttpServletRequest request){
String ip= request.getRemoteAddr();
users.setIp(ip);
Users user = this.usersService.userLogin(users);
session.setAttribute("user",user);
return "redirect:/page/index";
}
4.2.6 配置切面
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: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/context
http://www.springframework.org/schema/context/spring-context.xsd"
>
<!-- 配置注解扫描-->
<context:component-scan
base-package="com.bjsxt.service,com.bjsxt.aop"/>
</beans>
applicationCotnext-trans.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: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/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!--配置事务管理器的切面-->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--配置事务属性-->
<tx:advice id="myAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="add*" propagation="REQUIRED"/>
<tx:method name="modify*" propagation="REQUIRED"/>
<tx:method name="drop*" propagation="REQUIRED"/>
<tx:method name="userLogin" propagation="REQUIRED"/>
<tx:method name="find*" read-only="true"/>
</tx:attributes>
</tx:advice>
<!--配置切点-->
<aop:config>
<aop:pointcut id="myPointcut"
expression="execution(*com.bjsxt.service.*.*(..))"/>
<aop:advisor advice-ref="myAdvice" pointcut-ref="myPointcut"/>
</aop:config>
<aop:aspectj-autoproxy proxy-target-class="true"/>
</beans>