SSM框架整合 一
需求:在SSM框架上实现超市订单管理系统的登录和注销功能,要求在访问系统的所有请求进行身份验证以确保系统数据的安全性
项目结构:
首先,编写配置文件
spring框架的配置文件:applicationContext-mybatis.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 | <? 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
1 2 3 4 5 6 7 8 9 10 11 12 | 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 | 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 \u65e5\u5fd7\u5728\u63a7\u5236\u8f93\u51fa\u914d\u7f6e ###################################################################################### 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 \u6587\u4ef6\u5927\u5c0f\u5230\u8fbe\u6307\u5b9a\u5c3a\u5bf8\u7684\u65f6\u5019\u4ea7\u751f\u4e00\u4e2a\u65b0\u7684\u6587\u4ef6 ###################################################################################### #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 \u6bcf\u5929\u4ea7\u751f\u4e00\u4e2a\u65e5\u5fd7\u6587\u4ef6\uff0c\u6587\u4ef6\u540d\u683c\u5f0f: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 \u65e5\u5fd7 #log4j.logger.org.directwebremoting = ERROR #\u663e\u793aHibernate\u5360\u4f4d\u7b26\u7ed1\u5b9a\u503c\u53ca\u8fd4\u56de\u503c #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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <? 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 | <? 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 | 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | <%@ 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
1 2 3 4 5 6 7 8 9 10 11 | <%@ 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
1 2 3 4 5 6 7 8 9 10 11 12 | <%@ 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | <%@ 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | <%@ 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 > |
运行项目
分类:
SSM框架整合
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY