需求:在SSM框架上实现超市订单管理系统的登录和注销功能,要求在访问系统的所有请求进行身份验证以确保系统数据的安全性
项目结构:
首先,编写配置文件
spring框架的配置文件:applicationContext-mybatis.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:p="http://www.springframework.org/schema/p"
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-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="cn.smbms.service"/>
<context:component-scan base-package="cn.smbms.dao"/>
<!-- 读取数据库配置文件 -->
<context:property-placeholder location="classpath:database.properties"/>
<!-- JNDI获取数据源(使用dbcp连接池) -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" scope="singleton">
<property name="driverClassName" value="${driver}" />
<property name="url" value="${url}" />
<property name="username" value="${user}" />
<property name="password" value="${password}" />
<property name="initialSize" value="${initialSize}"/>
<property name="maxActive" value="${maxActive}"/>
<property name="maxIdle" value="${maxIdle}"/>
<property name="minIdle" value="${minIdle}"/>
<property name="maxWait" value="${maxWait}"/>
<property name="removeAbandonedTimeout" value="${removeAbandonedTimeout}"/>
<property name="removeAbandoned" value="${removeAbandoned}"/>
<!-- sql 心跳 -->
<property name= "testWhileIdle" value="true"/>
<property name= "testOnBorrow" value="false"/>
<property name= "testOnReturn" value="false"/>
<property name= "validationQuery" value="select 1"/>
<property name= "timeBetweenEvictionRunsMillis" value="60000"/>
<property name= "numTestsPerEvictionRun" value="${maxActive}"/>
</bean>
<!-- 事务管理 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 配置mybitas SqlSessionFactoryBean-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="classpath:mybatis-config.xml"/>
</bean>
<!-- AOP 事务处理 开始 -->
<aop:aspectj-autoproxy />
<aop:config proxy-target-class="true">
<aop:pointcut expression="execution(* *cn.smbms.service..*(..))" id="transService"/>
<aop:advisor pointcut-ref="transService" advice-ref="txAdvice" />
</aop:config>
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="smbms*" propagation="REQUIRED" rollback-for="Exception" />
</tx:attributes>
</tx:advice>
<!-- AOP 事务处理 结束 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="cn.smbms.dao" />
</bean>
</beans>
数据库配置文件:jdbc.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/smbms?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull
user=root
password=root
#这也是在实际项目中需要配置的
minIdle=45
maxIdle=50
initialSize=5
maxActive=100
maxWait=100
removeAbandonedTimeout=180
removeAbandoned=true
日志配置文件:log4j.properties
log4j.rootLogger=debug,CONSOLE,file
#log4j.rootLogger=ERROR,ROLLING_FILE
log4j.logger.cn.smbms=debug
log4j.logger.org.apache.ibatis=debug
log4j.logger.org.mybatis.spring=debug
log4j.logger.java.sql.Connection=debug
log4j.logger.java.sql.Statement=debug
log4j.logger.java.sql.PreparedStatement=debug
log4j.logger.java.sql.ResultSet=debug
######################################################################################
# Console Appender u65e5u5fd7u5728u63a7u5236u8f93u51fau914du7f6e
######################################################################################
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.Threshold=debug
log4j.appender.CONSOLE.DatePattern=yyyy-MM-dd
log4j.appender.CONSOLE.Target=System.out
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern= - (%r ms) - %d{yyyy-M-d HH:mm:ss}%x[%5p](%F:%L) %m%n
######################################################################################
# Rolling File u6587u4ef6u5927u5c0fu5230u8fbeu6307u5b9au5c3au5bf8u7684u65f6u5019u4ea7u751fu4e00u4e2au65b0u7684u6587u4ef6
######################################################################################
#log4j.appender.ROLLING_FILE=org.apache.log4j.RollingFileAppender
#log4j.appender.ROLLING_FILE.Threshold=INFO
#log4j.appender.ROLLING_FILE.File=${baojia.root}/logs/log.log
#log4j.appender.ROLLING_FILE.Append=true
#log4j.appender.ROLLING_FILE.MaxFileSize=5000KB
#log4j.appender.ROLLING_FILE.MaxBackupIndex=100
#log4j.appender.ROLLING_FILE.layout=org.apache.log4j.PatternLayout
#log4j.appender.ROLLING_FILE.layout.ConversionPattern=%d{yyyy-M-d HH:mm:ss}%x[%5p](%F:%L) %m%n
######################################################################################
# DailyRolling File u6bcfu5929u4ea7u751fu4e00u4e2au65e5u5fd7u6587u4ef6uff0cu6587u4ef6u540du683cu5f0f:log2009-09-11
######################################################################################
log4j.appender.file=org.apache.log4j.DailyRollingFileAppender
log4j.appender.file.DatePattern=yyyy-MM-dd
log4j.appender.file.File=${SMBMS_C12_09.root}/logs/log.log
log4j.appender.file.Append=true
log4j.appender.file.Threshold=debug
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern= - (%r ms) - %d{yyyy-M-d HH:mm:ss}%x[%5p](%F:%L) %m%n
#DWR u65e5u5fd7
#log4j.logger.org.directwebremoting = ERROR
#u663eu793aHibernateu5360u4f4du7b26u7ed1u5b9au503cu53cau8fd4u56deu503c
#log4j.logger.org.hibernate.type=DEBUG,CONSOLE
#log4j.logger.org.springframework.transaction=DEBUG
#log4j.logger.org.hibernate=DEBUG
#log4j.logger.org.acegisecurity=DEBUG
#log4j.logger.org.apache.myfaces=TRACE
#log4j.logger.org.quartz=DEBUG
#log4j.logger.com.opensymphony=INFO
#log4j.logger.org.apache.struts2=DEBUG
log4j.logger.com.opensymphony.xwork2=debug
mybatis框架配置文件:mybatis.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>
<settings>
<!-- changes from the defaults 不开启懒加载-->
<setting name="lazyLoadingEnabled" value="false" />
</settings>
<typeAliases>
<!--这里给实体类取别名,方便在mapper配置文件中使用-->
<package name="cn.smbms.pojo"/>
</typeAliases>
</configuration>
spirngmvc框架的配置文件:springmvc-servlet.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:p="http://www.springframework.org/schema/p"
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
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:component-scan base-package="cn.smbms.controller"/>
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>application/json;charset=UTF-8</value>
</list>
</property>
</bean>
<bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8</value>
<value>application/json</value>
</list>
</property>
<property name="features">
<list>
<!-- Date的日期转换器 -->
<value>WriteDateUseDateFormat</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<mvc:resources location="/statics/" mapping="/statics/**"></mvc:resources>
<!--拦截器 -->
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/sys/**"/>
<bean class="cn.smbms.interceptor.SysInterceptor"></bean>
</mvc:interceptor>
</mvc:interceptors>
<!-- 配置多视图解析器:允许同样的内容数据呈现不同的view -->
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="favorParameter" value="true"/>
<property name="defaultContentType" value="text/html"/>
<property name="mediaTypes">
<map>
<entry key="html" value="text/html;charset=UTF-8"/>
<entry key="json" value="application/json;charset=UTF-8"/>
<entry key="xml" value="application/xml;charset=UTF-8"/>
</map>
</property>
<property name="viewResolvers">
<list>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
</list>
</property>
</bean>
<!-- 配置interceptors -->
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/sys/**"/>
<bean class="cn.smbms.interceptor.SysInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>
<!-- 配置MultipartResolver,用于上传文件,使用spring的CommonsMultipartResolver -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="5000000"/>
<property name="defaultEncoding" value="UTF-8"/>
</bean>
</beans>
编写拦截器:
LoginController.java
package cn.smbms.controller;
import javax.annotation.Resource;
import javax.jms.Session;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import cn.smbms.pojo.User;
import cn.smbms.service.user.UserService;
import cn.smbms.tools.Constants;
@Controller
public class LoginController {
private Logger logger = Logger.getLogger(LoginController.class);
@Resource
private UserService userService;
@RequestMapping("/login.html")
public String login() {
logger.debug("LoginController welcome SMBMS==================");
return "login";
}
// 登录时候的验证
@RequestMapping(value = "/dologin.html", method = RequestMethod.POST)
public String doLogin(@RequestParam String userCode,
@RequestParam String userPassword, HttpServletRequest request,
HttpSession session) throws Exception {
logger.debug("doLogin====================================");
User user = userService.login(userCode, userPassword);
if (user != null) {
session.setAttribute(Constants.USER_SESSION, user);
return "redirect:/sys/main.html";
} else {
request.setAttribute("error", "用户名或者密码错误");
return "login";
}
}
@RequestMapping(value = "/sys/main.html")
public String main() {
return "frame";
}
// 退出登录
@RequestMapping(value = "/logout.html")
public String logout(HttpSession httpSession) {
httpSession.removeAttribute(Constants.USER_SESSION);
return "login";
}
}
BaseController.java
package cn.smbms.controller;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
public class BaseController {
/**
* 使用@InitBinder解决SpringMVC日期类型无法绑定的问题
* @param dataBinder
*/
@InitBinder
public void initBinder(WebDataBinder dataBinder){
System.out.println("initBinder=======================");
dataBinder.registerCustomEditor(Date.class,
new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
/*dataBinder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
public void setAsText(String value) {
System.out.println("InitBinder setAsText value=======================" + value);
try {
setValue(new SimpleDateFormat("yyyy-MM-dd").parse(value));
} catch(ParseException e) {
System.out.println(e.getMessage());
e.printStackTrace();
setValue(null);
}
}
public String getAsText() {
System.out.println("InitBinder getAsText=======================");
return new SimpleDateFormat("yyyy-MM-dd").format((Date) getValue());
}
});*/
}
}
UserController.java
UserMapper.java
UserMapper.xml
UserService.java
UserServiceImpl.java
前端页面:
login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>系统登录 - 超市订单管理系统</title>
<link type="text/css" rel="stylesheet" href="${pageContext.request.contextPath }/statics/css/style.css" />
<script type="text/javascript">
/* if(top.location!=self.location){
top.location=self.location;
} */
</script>
</head>
<body class="login_bg">
<section class="loginBox">
<header class="loginHeader">
<h1>超市订单管理系统</h1>
</header>
<section class="loginCont">
<form class="loginForm" action="${pageContext.request.contextPath }/dologin.html" name="actionForm" id="actionForm" method="post" >
<div class="info">${error }</div>
<div class="inputbox">
<label for="user">用户名:</label>
<input type="text" class="input-text" id="userCode" name="userCode" placeholder="请输入用户名" required/>
</div>
<div class="inputbox">
<label for="mima">密码:</label>
<input type="password" id="userPassword" name="userPassword" placeholder="请输入密码" required/>
</div>
<div class="subBtn">
<input type="submit" value="登录"/>
<input type="reset" value="重置"/>
</div>
</form>
</section>
</section>
</body>
</html>
frame.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@include file="/WEB-INF/jsp/common/head.jsp"%>
<div class="right">
<img class="wColck" src="${pageContext.request.contextPath }/statics/images/clock.jpg" alt=""/>
<div class="wFont">
<h2>${userSession.userName }</h2>
<p>欢迎来到超市订单管理系统!</p>
</div>
</div>
</section>
<%@include file="/WEB-INF/jsp/common/foot.jsp" %>
foot.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<footer class="footer">
版权归北大青鸟
</footer>
<script type="text/javascript" src="${pageContext.request.contextPath }/statics/js/time.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath }/statics/js/jquery-1.8.3.min.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath }/statics/js/common.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath }/statics/calendar/WdatePicker.js"></script>
</body>
</html>
head.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>超市订单管理系统</title>
<link type="text/css" rel="stylesheet" href="${pageContext.request.contextPath }/statics/css/style.css" />
<link type="text/css" rel="stylesheet" href="${pageContext.request.contextPath }/statics/css/public.css" />
</head>
<body>
<!--头部-->
<header class="publicHeader">
<h1>超市订单管理系统</h1>
<div class="publicHeaderR">
<p><span>下午好!</span><span style="color: #fff21b"> ${userSession.userName }</span> , 欢迎你!</p>
<a href="${pageContext.request.contextPath }/logout.html">退出</a>
</div>
</header>
<!--时间-->
<section class="publicTime">
<span id="time">2015年1月1日 11:11 星期一</span>
<a href="#">温馨提示:为了能正常浏览,请使用高版本浏览器!(IE10+)</a>
</section>
<!--主体内容-->
<section class="publicMian ">
<div class="left">
<h2 class="leftH2"><span class="span1"></span>功能列表 <span></span></h2>
<nav>
<ul class="list">
<li ><a href="${pageContext.request.contextPath }/jsp/bill.do?method=query">订单管理</a></li>
<li><a href="${pageContext.request.contextPath }/jsp/provider.do?method=query">供应商管理</a></li>
<li><a href="${pageContext.request.contextPath }/user/userlist.html">用户管理</a></li>
<li><a href="${pageContext.request.contextPath }/jsp/pwdmodify.jsp">密码修改</a></li>
<li><a href="${pageContext.request.contextPath }/logout.html">退出系统</a></li>
</ul>
</nav>
</div>
<input type="hidden" id="path" name="path" value="${pageContext.request.contextPath }"/>
<input type="hidden" id="referer" name="referer" value="<%=request.getHeader("Referer")%>"/>
401.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>超市账单管理系统</title>
<link type="text/css" rel="stylesheet" href="${pageContext.request.contextPath }/statics/css/style.css">
</head>
<body>
<div>
<h2>对不起,您没有权限访问,请返回到<a href="login.html">首页</a></h2>
</div><!--/span-->
<div>
<img src="statics/images/jg.png"/>
</div><!--/span-->
</body>
</html>
运行项目