练习涉及:spring+jq+ajax+mybatis+springAOP
功能涉及:
1. 登录(校验)
2. 金额校验
3. 验收收款人信息
4. 转账
页面预览:
项目概览:
使用jar包:
src:
create database bank;
use bank;
select version() from dual;
create table t_account (aid int(10) not null auto_increment,
apwd varchar(100) not null,
money double,
uid int(10) not null,
primary key(aid));
select * from t_account;
insert into t_account values(default,'123456',8548.60,1);
insert into t_account values(default,'123456',10000.00,2);
create table t_user (uid int(10) not null auto_increment,
uname varchar(100) not null,
pwd varchar(100) not null,
primary key(uid));
insert into t_user values(default,'张三','123');
insert into t_user values(default,'李四','123');
select * from t_user;
select * from t_account a join t_user u on a.aid=u.uid;
package com.han.advice;
import org.apache.log4j.Logger;
import org.springframework.aop.MethodBeforeAdvice;
import java.lang.reflect.Method;
public class MyAfter implements MethodBeforeAdvice {
@Override
public void before(Method method, Object[] objects, Object o) throws Throwable {
/*获取Log4j的对象*/
Logger logger = Logger.getLogger(MyAfter.class);
/*日志输出*/
if (o!=null){
logger.debug(objects[0]+"登录成功");
}
}
}
package com.han.advice;
import org.apache.log4j.Logger;
import org.springframework.aop.MethodBeforeAdvice;
import java.lang.reflect.Method;
public class MyBefore implements MethodBeforeAdvice {
@Override
public void before(Method method, Object[] objects, Object o) throws Throwable {
/*获取Log4j的对象*/
Logger logger = Logger.getLogger(MyBefore.class);
/*日志输出*/
logger.debug(objects[0]+"发起了登录请求");
}
}
package com.han.controller;
import com.han.pojo.Account;
import com.han.service.CheckAccountService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet(value = "/checkAccount",loadOnStartup = 2)
public class CheckAccountServlet extends HttpServlet {
/*声明业务层属性*/
private CheckAccountService checkAccountService;
@Override
public void init() throws ServletException {
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationcontext.xml");
checkAccountService = (CheckAccountService) ac.getBean("checkAccountServiceImpl");
}
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//设置请求编码格式
req.setCharacterEncoding("utf-8");
//设置响应编码格式
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
/*获取请求数据中的方法名*/
String methodName = req.getParameter("methodName");
/*根据请求调用对应的逻辑代码*/
if ("checkOutInfo".equals(methodName)){
checkOutInfo(req,resp);
}else if ("checkMoneyInfo".equals(methodName)){
checkMoneyInfo(req,resp);
}else if ("checkInInfo".equals(methodName)){
checkInInfo(req,resp);
}else if ("transferInfo".equals(methodName)){
transferInfo(req,resp);
}else {
System.out.println("没有对应的逻辑方法"+methodName);
}
}
/*转账*/
private void transferInfo(HttpServletRequest req, HttpServletResponse resp) throws IOException {
/*获取请求信息*/
String outId = req.getParameter("outId");
String inId = req.getParameter("inId");
String money = req.getParameter("money");
/*处理请求*/
int i = checkAccountService.transferInfoService(outId,inId,money);
/*响应结果*/
if (i>0){
resp.sendRedirect(req.getContextPath()+"/success.jsp");
}else {
resp.sendRedirect(req.getContextPath()+"/error.jsp");
}
}
/*校验收款人信息*/
private void checkInInfo(HttpServletRequest req, HttpServletResponse resp) throws IOException {
/*获取请求信息*/
String inId = req.getParameter("inId");
String inName = req.getParameter("inName");
/*处理请求*/
/*调用业务层方法*/
Account account = checkAccountService.checkInInfoService(inId,inName);
/*响应结果*/
resp.getWriter().write(account != null ? "true" : "false");
}
/*校验金额*/
private void checkMoneyInfo(HttpServletRequest req, HttpServletResponse resp) throws IOException {
/*获取请求信息*/
String outId = req.getParameter("outId");
String money = req.getParameter("money");
/*处理请求*/
/*调用业务层方法*/
Account account = checkAccountService.checkMoneyInfoService(outId,money);
/*响应结果*/
resp.getWriter().write(account != null ? "true" : "false");
}
/*声明方法:校验转账账户信息*/
private void checkOutInfo(HttpServletRequest req, HttpServletResponse resp) throws IOException {
/*获取请求信息*/
String outId = req.getParameter("outId");
String outPwd = req.getParameter("outPwd");
/*处理请求:*/
/*调用业务层方法*/
Account account = checkAccountService.checkOutAccountInfoService(outId,outPwd);
/*响应结果*/
resp.getWriter().write(account != null ? "true" : "false");
}
}
package com.han.controller;
import com.han.pojo.User;
import com.han.service.UserService;
import com.han.service.impl.UserServiceImpl;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@WebServlet(value = "/userLogin",loadOnStartup = 1)
public class UserServlet extends HttpServlet {
private UserService us;
public void init(){
//获取Spring容器对象
ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
//获取业务层对象
us = (UserService) ac.getBean("userServiceImpl");
}
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//设置请求编码格式
req.setCharacterEncoding("utf-8");
//设置响应编码格式
resp.setContentType("text/html;charset=utf-8");
resp.setCharacterEncoding("utf-8");
String uname = req.getParameter("uname");
String pwd = req.getParameter("pwd");
//调用业务层方法根据用户名和密码获取用户信息
User user = us.userLoginService(uname, pwd);
//响应处理结果:
//获取Session对象:
HttpSession session = req.getSession();
if (user!=null){
//将用户信息存储到session中
session.setAttribute("user",user);
//重定向到主页面
resp.sendRedirect(req.getContextPath()+"/main.jsp");
}else{
//增加失败标记
session.setAttribute("flag","userFail");
//重定向到登录页面
resp.sendRedirect(req.getContextPath()+"/login.jsp");
}
}
}
package com.han.mapper;
import com.han.pojo.Account;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
public interface CheckAccountMapper {
/*校验转账账户信息;根据账户ID和密码获取账户信息*/
@Select("select * from t_account where aid=#{outId} and apwd=#{outPwd}")
Account checkAccountOutInfoMapper(@Param("outId") String outId, @Param("outPwd") String outPwd);
/*校验金额*/
@Select("select * from t_account where aid=#{outId} and money>=#{money}")
Account checkMoneyInfoMapper(@Param("outId") String outId, @Param("money") String money);
/*校验收款人信息*/
@Select("select a.* from t_account a join t_user u on a.aid=u.uid where a.aid=#{inId} and u.uname=#{inName}")
Account checkInInfoMapper(@Param("inId") String inId, @Param("inName") String inName);
/*转账功能*/
/*转出*/
@Update("update t_account set money=money-${money} where aid=#{outId}")
int transferOut(@Param("outId")String outId ,@Param("money") String money);
/*转入*/
@Update("update t_account set money=money+${money} where aid=#{inId}")
int transferIn(@Param("inId")String inId ,@Param("money") String money);
}
package com.han.mapper;
import com.han.pojo.User;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
public interface UserMapper {
@Select("select * from t_user where uname=#{uname} and pwd=#{pwd}")
User userLoginMapper(@Param("uname") String uname, @Param("pwd") String pwd);
}
package com.han.pojo;
import java.util.Objects;
public class Account {
private Integer aid;
private String apwd;
private Double money;
private Integer uid;
private User user;
@Override
public String toString() {
return "Account{" +
"aid=" + aid +
", apwd='" + apwd + '\'' +
", money=" + money +
", uid=" + uid +
", user=" + user +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Account account = (Account) o;
return Objects.equals(aid, account.aid) &&
Objects.equals(apwd, account.apwd) &&
Objects.equals(money, account.money) &&
Objects.equals(uid, account.uid) &&
Objects.equals(user, account.user);
}
@Override
public int hashCode() {
return Objects.hash(aid, apwd, money, uid, user);
}
public Integer getAid() {
return aid;
}
public void setAid(Integer aid) {
this.aid = aid;
}
public String getApwd() {
return apwd;
}
public void setApwd(String apwd) {
this.apwd = apwd;
}
public Double getMoney() {
return money;
}
public void setMoney(Double money) {
this.money = money;
}
public Integer getUid() {
return uid;
}
public void setUid(Integer uid) {
this.uid = uid;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Account() {
}
public Account(Integer aid, String apwd, Double money, Integer uid, User user) {
this.aid = aid;
this.apwd = apwd;
this.money = money;
this.uid = uid;
this.user = user;
}
}
package com.han.pojo;
import java.util.Objects;
public class User {
private Integer uid;
private String uname;
private String pwd;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User user = (User) o;
return Objects.equals(uid, user.uid) &&
Objects.equals(uname, user.uname) &&
Objects.equals(pwd, user.pwd);
}
@Override
public int hashCode() {
return Objects.hash(uid, uname, pwd);
}
@Override
public String toString() {
return "User{" +
"uid=" + uid +
", uname='" + uname + '\'' +
", pwd='" + pwd + '\'' +
'}';
}
public Integer getUid() {
return uid;
}
public void setUid(Integer uid) {
this.uid = uid;
}
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public User() {
}
public User(Integer uid, String uname, String pwd) {
this.uid = uid;
this.uname = uname;
this.pwd = pwd;
}
}
package com.han.service.impl;
import com.han.mapper.CheckAccountMapper;
import com.han.pojo.Account;
import com.han.service.CheckAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class CheckAccountServiceImpl implements CheckAccountService {
@Autowired
private CheckAccountMapper checkAccountMapper;
/*校验转账账户信息*/
@Override
public Account checkOutAccountInfoService(String outId, String outPwd) {
return checkAccountMapper.checkAccountOutInfoMapper(outId,outPwd);
}
/*校验金额*/
@Override
public Account checkMoneyInfoService(String outId, String money) {
return checkAccountMapper.checkMoneyInfoMapper(outId,money);
}
/*校验收款人信息*/
@Override
public Account checkInInfoService(String inId, String inName) {
return checkAccountMapper.checkInInfoMapper(inId,inName);
}
/*转账功能*/
@Override
public int transferInfoService(String outId, String inId, String money) {
/*出账*/
int i = checkAccountMapper.transferOut(outId,money);
/*入账*/
i += checkAccountMapper.transferIn(inId,money);
return i;
}
}
package com.han.service.impl;
import com.han.mapper.UserMapper;
import com.han.pojo.User;
import com.han.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
public UserServiceImpl(UserMapper userMapper) {
this.userMapper = userMapper;
}
@Override
public User userLoginService(String uname, String pwd) {
return userMapper.userLoginMapper(uname,pwd);
}
}
package com.han.service;
import com.han.pojo.Account;
public interface CheckAccountService {
/*校验转账账户信息*/
Account checkOutAccountInfoService(String outId, String outPwd);
/*校验金额*/
Account checkMoneyInfoService(String outId, String money);
/*校验收款人信息*/
Account checkInInfoService(String inId, String inName);
/*转账功能*/
int transferInfoService(String outId, String inId, String money);
}
package com.han.service;
import com.han.pojo.User;
public interface UserService {
User userLoginService(String uname, String pwd) ;
}
配置文件:
<?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/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
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
">
<!--加载属性配置文件-->
<context:property-placeholder location="classpath:db.properties"/>
<!--配置注解扫描-->
<context:component-scan base-package="com.han.service.impl"></context:component-scan>
<!-- 配置数据源bean -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<!-- 基本属性 url、user、password -->
<property name="driverClassName" value="${mysql.driver}" />
<property name="url" value="${mysql.url}" />
<property name="username" value="${mysql.username}" />
<property name="password" value="${mysql.password}" />
</bean>
<!-- 配置工厂bean -->
<bean id="factory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- 配置mapper扫描bean -->
<bean id="mapper" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="sqlSessionFactoryBeanName" value="factory" />
<property name="basePackage" value="com.han.mapper" />
</bean>
<!--<!– 配置业务层bean –>
<!–用户登录–>
<bean id="us" class="com.han.service.impl.UserServiceImpl">
<property name="userMapper" ref="userMapper"></property>
</bean>
<!–配置信息校验–>
<bean id="checkAccountService" class="com.han.service.impl.CheckAccountServiceImpl">
<property name="checkAccountMapper" ref="checkAccountMapper"></property>
</bean>-->
<!-- <!– 配置通知bean –>-->
<!-- <bean id="before" class="com.han.advice.MyBefore"></bean>-->
<!-- <bean id="after" class="com.han.advice.MyAfter"></bean>-->
<!-- <!– 配置AOP组装规则 –>-->
<!-- <aop:config>-->
<!-- <aop:pointcut id="mp" expression="execution(* com.han.service.impl.UserServiceImpl.userLoginService(String,String))"/>-->
<!-- <aop:advisor advice-ref="before" pointcut-ref="mp"></aop:advisor>-->
<!-- <aop:advisor advice-ref="after" pointcut-ref="mp"></aop:advisor>-->
<!-- </aop:config>-->
<!--SpringTX的事务管理-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!--配置事务管理方法-->
<tx:advice id="advice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="sel*"/>
<tx:method name="ins*"/>
<tx:method name="up*"/>
<tx:method name="del*"/>
<tx:method name="transfer*"/>
</tx:attributes>
</tx:advice>
<!--配置事务管理切面-->
<aop:config>
<aop:pointcut id="mp" expression="execution(* com.han.service.impl.*.*(..))"/>
<!--增加事务通知-->
<aop:advisor advice-ref="advice" pointcut-ref="mp"></aop:advisor>
</aop:config>
</beans>
mysql.driver=com.mysql.jdbc.Driver
mysql.url=jdbc:mysql://localhost:3306/[数据库名]
mysql.username=root
mysql.password=[数据库密码]
log4j.rootLogger=info
log4j.logger.com.han.mapper=debug, CONSOLE,LOGFILE
log4j.logger.com.han.service.Impl=debug, CONSOLE,LOGFILE
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=- %c-%d-%m%n
log4j.appender.LOGFILE=org.apache.log4j.FileAppender
log4j.appender.LOGFILE.File=E:\axis.log
log4j.appender.LOGFILE.Append=true
log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
log4j.appender.LOGFILE.layout.ConversionPattern=- %c-%d-%m%n
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<!--配置全局参数:记录Spring配置文件名-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationcontext.xml</param-value>
</context-param>
<!--配置监听器-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>
前端代码:
login.jsp:
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<base href="<%=basePath %>"/>
<title>登录页面</title>
</head>
<body>
<h3 align="center">欢迎登录银行转账系统</h3>
<hr>
<div style="width: 400px;margin: auto">
<c:if test="${sessionScope.flag=='userFail'}">
<font color="red" size="20px">用户名或密码错误</font>
</c:if>
<c:remove var="flag" scope="session"/>
<form action="${pageContext.request.contextPath}/userLogin" method="post">
<table style="margin: auto;margin-top: 30px" cellpadding="10px">
<tr>
<td>用户名:</td>
<td>
<input type="text" name="uname" value="">
</td>
</tr>
<tr>
<td>密码:</td>
<td>
<input type="password" name="pwd" value="">
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="点击登录">
</td>
<td></td>
</tr>
</table>
</form>
</div>
</body>
</html>
main.jsp:
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<base href="<%=basePath %>"/>
<title>银行转账系统</title>
<%--引入jQuery--%>
<script type="text/javascript" src="js/j.js"></script>
<%--声明js代码域--%>
<script type="text/javascript">
/*声明页面加载事件*/
$(function () {
/*欢迎标题随机色*/
window.setInterval(function () {
var colors = ('#'+('00000'+(Math.random()*0x1000000<<0).toString(16)).slice(-6));
$("#title").css("color",colors);
},1000)
})
/*转账信息校验*/
/*给密码框添加焦点事件,完成校验*/
$(function () {
$("#outPwd").blur(function () {
/*发起ajax请求*/
$.post("checkAccount",{outId:$("#outId").val(),outPwd:$("#outPwd").val(),methodName:"checkOutInfo"},function (data) {
if (eval(data)){
$("#outSpan").html("√").css("color","green").addClass("success").removeClass("error");
}else{
$("#outSpan").html("×").css("color","red").addClass("error").removeClass("success");
}
})
})
})
/*转账金额校验*/
$(function () {
$("#money").blur(function () {
/*发起ajax请求*/
$.post("checkAccount",{outId:$("#outId").val(),money:$("#money").val(),methodName:"checkMoneyInfo"},function (data) {
if (eval(data)){
$("#moneySpan").html("√").css("color","green").addClass("success").removeClass("error");
}else{
$("#moneySpan").html("×").css("color","red").addClass("error").removeClass("success");
}
})
})
})
/*收款人信息校验*/
$(function () {
$("#inName").blur(function () {
/*发起ajax请求*/
$.post("checkAccount",{inId:$("#inId").val(),inName:$("#inName").val(),methodName:"checkInInfo"},function (data) {
if (eval(data)){
$("#inNameSpan").html("√").css("color","green").addClass("success").removeClass("error");
}else{
$("#inNameSpan").html("×").css("color","red").addClass("error").removeClass("success");
}
})
})
})
/*转账功能*/
$(function () {
$("#btn").click(function () {
/*校验转账信息是否正确*/
if ($(".success").length==3){
/*提交表单*/
$("#fm").submit();
}else{
alert("请填写正确的账户信息")
}
})
})
</script>
</head>
<body>
<h3 align="center">
<%--跑马灯--%>
<marquee width=50% behavior=alternate align=middle">
<font id="title">欢迎${sessionScope.user.uname}登录银行转账系统</font>
</marquee>
</h3>
<hr>
<div style="width: 400px;margin:auto;">
<form action="checkAccount" method="post" id="fm">
<input type="hidden" name="methodName" value="transferInfo">
<table style="margin:auto;margin-top: 30px;" cellpadding="10px">
<tr>
<td>转账账户:</td>
<td>
<input type="text" name="outId" id="outId" value="">
</td>
</tr>
<tr>
<td>转账账户密码:</td>
<td>
<input type="password" id="outPwd" value="">
<span id="outSpan"></span>
</td>
</tr>
<tr>
<td>金额:</td>
<td>
<input type="text" name="money" id="money" value="">
<span id="moneySpan"></span>
</td>
</tr>
<tr>
<td>收款账号:</td>
<td>
<input type="text" id="inId" name="inId" value="">
</td>
</tr>
<tr>
<td>收款人姓名:</td>
<td>
<input type="text" id="inName" value="">
<span id="inNameSpan"></span>
</td>
</tr>
<tr>
<td colspan="2">
<input type="button" value="开始转账" id="btn">
</td>
</tr>
</table>
</form>
</div>
</body>
</html>