目录
3.1 applicationContext-dao.xml
3.2 applicationContext-service.xml
一、先看效果
1.1 登录页面
1.2 主页面
1.3 目录结构
二、 数据库脚本
/*
Navicat Premium Data Transfer
Source Server : localhost_3305
Source Server Type : MySQL
Source Server Version : 50651 (5.6.51)
Source Host : localhost:3305
Source Schema : ssm
Target Server Type : MySQL
Target Server Version : 50651 (5.6.51)
File Encoding : 65001
Date: 12/01/2024 20:01:14
*/
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for account
-- ----------------------------
DROP TABLE IF EXISTS `account`;
CREATE TABLE `account` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`money` double NULL DEFAULT NULL,
`date` date NULL DEFAULT NULL,
`head` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`password` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 11 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;
-- ----------------------------
-- Records of account
-- ----------------------------
INSERT INTO `account` VALUES (1, '杨逍1', 10000, '2023-01-01', 'u=897851687,2835494130&fm=253&fmt=auto&app=138&f=JPEG.webp', '111');
INSERT INTO `account` VALUES (2, '延期', 10000, '2023-01-01', 'u=4251408926,3626211699&fm=253&fmt=auto&app=138&f=JPEG.webp', '111');
INSERT INTO `account` VALUES (6, '张无忌', 200, '2024-01-03', 'u=4251408926,3626211699&fm=253&fmt=auto&app=138&f=JPEG.webp', '111');
INSERT INTO `account` VALUES (10, 'admin', 100, '2024-01-11', 'u=4251408926,3626211699&fm=253&fmt=auto&app=138&f=JPEG.webp', '111');
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`username` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`password` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 6 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;
-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES (1, 'admin', '111');
INSERT INTO `user` VALUES (2, 'admin2', '111');
INSERT INTO `user` VALUES (3, 'admin3', '111');
INSERT INTO `user` VALUES (4, '红红', '111');
INSERT INTO `user` VALUES (5, 'text', '111');
SET FOREIGN_KEY_CHECKS = 1;
三、reources
3.1 applicationContext-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:tx="http://www.springframework.org/schema/tx"
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/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
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<!--加载配置文件-->
<context:property-placeholder location="classpath:db.properties"></context:property-placeholder>
<!--dataSource-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
destroy-method="close">
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<property name="driverClassName" value="${jdbc.driver}" />
</bean>
<!--sqlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!--扫描mapper接口生成代理类,并交给spring的ioc容器管理-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.by.mapper"></property>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
</bean>
</beans>
3.2 applicationContext-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:tx="http://www.springframework.org/schema/tx"
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/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
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<!--配置spring要扫描的包-->
<context:component-scan base-package="com.by.service"></context:component-scan>
<!--导入配置文件
<import resource="classpath:applicationContext-dao.xml"></import>
<import resource="classpath:applicationContext-tx.xml"></import>
-->
</beans>
3.3 applicationContext-tx.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:tx="http://www.springframework.org/schema/tx"
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/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
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<!--事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!--开启spring事务注解的支持-->
<tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
<!--
<!–增强:要搞的事情,eg:日志、事务–>
<tx:advice id="txManager" transaction-manager="transactionManager">
<tx:attributes>
<!–
隔离级别:默认值REPEATABLE_READ,mysql默认隔离级别
传播行为:默认值REQUIRED,有就加入,没有则新建
超时:默认值-1,永不超时
是否只读:默认值false,加log适合增删改
回滚规则:可省略,所有异常都回滚
–>
<tx:method name="get*" propagation="SUPPORTS" read-only="true"/>
<tx:method name="select*" propagation="SUPPORTS" read-only="true"/>
<tx:method name="*"/>
</tx:attributes>
</tx:advice>
<aop:config>
<!–切点:要增强的方法–>
<aop:pointcut id="pointcut" expression="execution(* com.by.service.*.*(..))"/>
<!–切面:把增强应用到切点上–>
<aop:advisor advice-ref="txManager" pointcut-ref="pointcut"></aop:advisor>
</aop:config>
-->
</beans>
3.4 db.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3305/ssm?characterEncoding=utf-8
jdbc.username=root
jdbc.password=
3.5 log4j.properties
log4j.rootLogger=DEBUG,A1
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} - %c%l%m%n
3.6 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:p="http://www.springframework.org/schema/p"
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/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!--
DispatcherServlet(前端控制器):扫描controller,接受请求
HandlerMapping(处理器映射器):查找handler
HandlerAdaptor(处理器适配器):调用handler
ViewResolver(视图解析器):解析jsp的具体路径
view(视图渲染器):把数据填充到request,跳转页面
-->
<!--配置springmvc要扫描的包-->
<context:component-scan base-package="com.by.controller"></context:component-scan>
<!--开启springmvc注解的支持:HandlerMapping和HandlerAdaptor-->
<mvc:annotation-driven conversion-service="cs"></mvc:annotation-driven>
<!--配置视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!-- 配置类型转换器工厂 -->
<bean id="cs" class="org.springframework.context.support.ConversionServiceFactoryBean">
<!-- 给工厂注入一个新的类型转换器 -->
<property name="converters">
<set>
<!-- 配置自定义类型转换器 -->
<bean class="com.by.converter.DateConverter"></bean>
</set>
</property>
</bean>
<!--配置文件上传解析器-->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="5242880" />
<property name="defaultEncoding" value="UTF-8" />
</bean>
<!--配置静态资源映射:访问图片时不进入前端控制器-->
<mvc:resources mapping="/head/**" location="/head/"></mvc:resources>
<!-- 配置拦截器-->
<mvc:interceptors>
<mvc:interceptor>
<!-- 匹配的是url路径 -->
<!-- 1. 先拦截所有请求-->
<mvc:mapping path="/**"></mvc:mapping>
<!-- 2. 将登录和注册的路径放行-->
<mvc:exclude-mapping path="/account/loginServlet"/>
<mvc:exclude-mapping path="/user/toZhuce"/>
<mvc:exclude-mapping path="/user/Zhuce"/>
<bean class="com.by.interceptor.LoginInterceptor"></bean>
</mvc:interceptor>
</mvc:interceptors>
</beans>
四、pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.by</groupId>
<artifactId>ssm</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<spring.version>5.1.8.RELEASE</spring.version>
<slf4j.version>1.6.6</slf4j.version>
<log4j.version>1.2.12</log4j.version>
<mysql.version>5.1.47</mysql.version>
<mybatis.version>3.4.5</mybatis.version>
<druid.version>1.1.0</druid.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<!--mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.0</version>
</dependency>
<!--jsp-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- log start -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j.version}</version>
</dependency>
<!--文件上传-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
</dependencies>
<build>
<plugins>
<!-- 配置Tomcat插件 -->
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<!--端口号-->
<port>8080</port>
<!--项目名-->
<path>/</path>
<!--按UTF-8进行编码-->
<uriEncoding>UTF-8</uriEncoding>
</configuration>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
<resource>
<directory>src/main/resources</directory>
</resource>
</resources>
</build>
</project>
五、JSP页面
5.1 index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>登录界面</title>
</head>
<body>
<h2 class="dl">登录界面</h2>
<form action="/account/loginServlet" method="post" class="was-validated">
用户名:<input type="text" name="name"><br>
密 码:<input type="text" name="password"><br>
验证码 :<input type="text" name="checkCode"/><br/>
<img alt="验证码" id="imagecode" src="<%= request.getContextPath()%>/imageServlet"/>
<input type="submit" value="提交"><hr>
还没有账户?点击<a href="/user/toZhuce">这里</a>注册
</div>`
</form>
</body>
<!-- 新 Bootstrap4 核心 CSS 文件 -->
<link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.3.1/css/bootstrap.min.css">
<!-- jQuery文件。务必在bootstrap.min.js 之前引入 -->
<script src="https://cdn.staticfile.org/jquery/3.2.1/jquery.min.js"></script>
<!-- bootstrap.bundle.min.js 用于弹窗、提示、下拉菜单,包含了 popper.min.js -->
<script src="https://cdn.staticfile.org/popper.js/1.15.0/umd/popper.min.js"></script>
<!-- 最新的 Bootstrap4 核心 JavaScript 文件 -->
<script src="https://cdn.staticfile.org/twitter-bootstrap/4.3.1/js/bootstrap.min.js"></script>
</html>
5.2 add_account.jsp
<%--
Created by IntelliJ IDEA.
User: Hero
Date: 2024/1/10
Time: 17:19
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h2>新增账户</h2>
<form action="/account/addAccount" method="post" enctype="multipart/form-data">
账号:<input type="text" name="name"><br>
金额:<input type="text" name="money"><br>
日期:<input type="text" name="date"><br>
头像:<input type="file" name="img"><br>
<input type="submit" value=" 保 存 ">
</form>
</body>
</html>
5.3 select_account.jsp
<%--
Created by IntelliJ IDEA.
User: Hero
Date: 2024/1/10
Time: 15:55
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<html>
<head>
<title>Title</title>
<style>
#boby1 {
height: 200px;
background-image: linear-gradient(to right, pink , powderblue);
}
h2.cx {
position:relative;
left:560px;
top:30px;
}
h3 {
position: relative;
left: 400px;
top: 40px;
}
table.table{
text-align:center;
}
</style>
</head>
<body id="boby1">
<!-- 新 Bootstrap4 核心 CSS 文件 -->
<link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.3.1/css/bootstrap.min.css">
<!-- jQuery文件。务必在bootstrap.min.js 之前引入 -->
<script src="https://cdn.staticfile.org/jquery/3.2.1/jquery.min.js"></script>
<!-- bootstrap.bundle.min.js 用于弹窗、提示、下拉菜单,包含了 popper.min.js -->
<script src="https://cdn.staticfile.org/popper.js/1.15.0/umd/popper.min.js"></script>
<!-- 最新的 Bootstrap4 核心 JavaScript 文件 -->
<script src="https://cdn.staticfile.org/twitter-bootstrap/4.3.1/js/bootstrap.min.js"></script>
<h2 class="cx">查询所有账户</h2>
<h2 class="admin">欢迎${sessionScope.account1.name}登录</h2>
<h3><a href="/account/toAddAccount">新增账户</a></h3>
<form action="/account/sou" method="post">
输入关键字查询: <input type="text" name="name" placeholder="输入姓名查询">
<button type="submit">搜索</button>
</form>
<form action="/account/deleteAccountByIds" method="post">
<input type="submit" value="批量删除">
<table class=" table table-bordered">
<tr>
<th><input type="checkbox" id="checkAll">全选</th>
<th>姓名</th>
<th>金额</th>
<th>日期</th>
<th>头像</th>
<th>操作</th>
</tr>
<c:forEach items="${accountList}" var="account">
<tr>
<td><input type="checkbox" name="id" value="${account.id}"></td>
<td>${account.name}</td>
<td>${account.money}</td>
<td><fmt:formatDate value="${account.date}" pattern="yyyy-MM-dd"></fmt:formatDate></td>
<td><img src="/head/${account.head}" height="40px" width="50px"></td>
<td><a href="/account/updateAccount?id=${account.id}">修改</a>
<a href="/account/deleteAccount?id=${account.id}">删除</a>
</td>
</tr>
</c:forEach>
</table>
</form>
</body>
<script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#checkAll").click(function() {
$("input[name='id']").each(function() {
$(this).prop("checked", !$(this).prop("checked"));
});
});
});
</script>
</html>
5.4 update.jsp
<%--
Created by IntelliJ IDEA.
User: 黄远超
Date: 2024/1/10
Time: 20:54
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h2>修改账户</h2>
<form action="/account/updateAccountById" method="post" enctype="multipart/form-data">
<%-- id:<input type="text" name="id"><br>--%>
姓名:<input type="text" name="name"><br>
金额:<input type="text" name="money"><br>
日期:<input type="text" name="date"><br>
头像:<input type="file" name="img"><br>
<input type="submit" value=" 保 存 ">
</form>
</body>
</html>
5.5 zhuce.jsp
<%--
Created by IntelliJ IDEA.
User: 黄远超
Date: 2024/1/12
Time: 11:15
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form action="/user/Zhuce" method="post">
账号:<input type="text" name="username"><br>
密码:<input type="text" name="password"><br>
<input type="submit" value="注册">
</form>
</body>
</html>
5.6 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>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</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>CharacterEncodingFilter</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>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>imageServlet</servlet-name>
<servlet-class>com.by.servlet.ImageServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>imageServlet</servlet-name>
<url-pattern>/imageServlet</url-pattern>
</servlet-mapping>
</web-app>
六、源代码
6.1 controller
① AccountController
package com.by.controller;
import com.by.pojo.Account;
import com.by.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
/**
* 注意:1.一次只写一层
*/
@Controller
@RequestMapping("/account")
public class AccountController {
@Autowired
private AccountService accountService;
@RequestMapping("/selectAccount")
public String selectAccount(Model model) {
List<Account> accountList = accountService.selectAccount();
model.addAttribute("accountList", accountList);
return "select_account";
}
@RequestMapping("/toAddAccount")
public String toAddAccount() {
return "add_account";
}
@RequestMapping("/addAccount")
public String addAccount(Account account, MultipartFile img, HttpServletRequest request) throws IOException {
//1.获得tomcat的路径
String realPath = request.getSession().getServletContext().getRealPath("/head/");
//2.创建目录
File file = new File(realPath);
if (!file.exists()) {
file.mkdirs();
}
//3.上传图片
String filename = img.getOriginalFilename();
img.transferTo(new File(realPath, filename));
account.setHead(filename);
accountService.addAccount(account);
return "redirect:/account/selectAccount";
}
// 删除员工
@RequestMapping("/deleteAccount")
public String deleteAccount(HttpServletRequest request) {
String id1 = request.getParameter("id");
int id = Integer.parseInt(id1);
accountService.deleteAccount(id);
return "redirect:/account/selectAccount";
}
// 修改员工信息
@RequestMapping("/updateAccount")
public String updateAccount(Model model, HttpServletRequest request) {
String id1 = request.getParameter("id");
int id = Integer.parseInt(id1);
HttpSession httpSession = request.getSession();
httpSession.setAttribute("id", id);
return "/update";
}
// 修改
@RequestMapping("/updateAccountById")
public String updateAccountById(HttpServletRequest request, Account account, MultipartFile img) throws IOException, ParseException {
//1.获得tomcat的路径
String realPath = request.getSession().getServletContext().getRealPath("/head/");
//2.创建目录
// File file = new File(realPath);
// if(!file.exists()){
// file.mkdirs();
// }
//3.上传图片
String filename = img.getOriginalFilename();
img.transferTo(new File(realPath, filename));
account.setHead(filename);
// int id = Integer.parseInt(request.getParameter("id"));
HttpSession httpSession = request.getSession();
int id = (int) httpSession.getAttribute("id");
String date = request.getParameter("date");
SimpleDateFormat sim = new SimpleDateFormat("yyyy-MM-dd");
Date date1 = sim.parse(date);
String name = request.getParameter("name");
Double money = Double.valueOf(request.getParameter("money"));
account.setDate(date1);
account.setName(name);
account.setMoney(money);
account.setId(id);
accountService.updateAccountById(account);
return "redirect:/account/selectAccount";
}
// 模糊查询
@RequestMapping("/sou")
public String sou(Model model, String name) {
List<Account> accountList = accountService.sou(name);
model.addAttribute("accountList", accountList);
return "select_account";
}
// 批量删除
@RequestMapping("/deleteAccountByIds")
public String deleteAccountByIds(Integer[] id){
accountService.deleteAccountByIds(id);
return "redirect:/account/selectAccount";
}
@RequestMapping("/loginServlet")
public String loginServlet(HttpServletRequest request, Model model, Account account, HttpServletResponse response) throws IOException {
//用于验证验证码
String piccode = (String) request.getSession().getAttribute("piccode");
String checkCode = request.getParameter("checkCode");
response.setContentType("text/html;charset=utf-8");//解决乱码问题
if (checkCode.equalsIgnoreCase(piccode)) {
Account account1 = accountService.loginServlet(account);
if (account1 != null) {
HttpSession httpSession = request.getSession();
httpSession.setAttribute("account1",account1);
return "redirect:/account/selectAccount";
} else {
return "forward:/index.jsp";
}
} else {
return "forward:/index.jsp";
}
}
}
②UserController
/*
* Copyright (c) 2020, 2024, webrx.cn All rights reserved.
*
*/
package com.by.controller;
import com.by.pojo.User;
import com.by.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* <p>Project: ssm - UserController</p>
* <p>Powered by webrx On 2024-01-12 11:14:36</p>
* <p>描述:<p>
*
* @author 简单遗忘 [[email protected]]
* @version 1.0
* @since 17
*/
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
// 注册
@RequestMapping("/toZhuce")
public String toZhuce(){
return "/zhuce";
}
// 注册业务
@RequestMapping("/Zhuce")
public String Zhuce(User user){
userService.Zhuce(user);
return "redirect:/index.jsp";
}
}
6.2 converter
①DateConverter
package com.by.converter;
import org.springframework.core.convert.converter.Converter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateConverter implements Converter<String, Date> {
@Override
public Date convert(String source) {
try {
DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
return format.parse(source);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
6.3 interceptor
package com.by.interceptor;
import com.by.pojo.Account;
import com.by.pojo.User;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
Account account = (Account) request.getSession().getAttribute("account1");
if(account!=null){
return true;
}else {
response.sendRedirect("/index.jsp");
return false;
}
}
}
6.4 mapper
①AccountMapper
package com.by.mapper;
import com.by.pojo.Account;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface AccountMapper {
List<Account> selectAccount();
void addAccount(Account account);
void deleteAccount(Integer id);
void updateAccountById(Account account);
List<Account> sou(String name);
Account loginServlet(Account account);
void deleteAccountByIds( @Param("ids") Integer[] id);
}
②AccountMapper.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.by.mapper.AccountMapper">
<select id="selectAccount" resultType="com.by.pojo.Account">
SELECT * FROM account
</select>
<insert id="addAccount" parameterType="com.by.pojo.Account">
INSERT INTO account(name, money, date, head) VALUES(#{name}, #{money}, #{date}, #{head})
</insert>
<delete id="deleteAccount" parameterType="int">
delete from account where id=#{id}
</delete>
<update id="updateAccountById" parameterType="com.by.pojo.Account">
UPDATE account set name=#{name},money=#{money},date=#{date},head=#{head} WHERE id=#{id}
</update>
<select id="sou" resultType="com.by.pojo.Account" parameterType="string">
select * from account where name like '%${value}%'<!--${}括号中只能是value-->
</select>
<select id="loginServlet" resultType="com.by.pojo.Account" parameterType="com.by.pojo.Account">
select * from account where name=#{name} and password=#{password}
</select>
<delete id="deleteAccountByIds" parameterType="int[]">
delete from account where id in
<foreach collection="ids" item="id" open="(" close=")" separator=",">
#{id}
</foreach>
</delete>
</mapper>
③UserMapper
package com.by.mapper;
import com.by.pojo.User;
public interface UserMapper {
void Zhuce(User user);
}
④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.by.mapper.UserMapper">
<insert id="Zhuce" parameterType="com.by.pojo.Account">
INSERT INTO user(username, password) VALUES(#{username}, #{password})
</insert>
</mapper>
6.5 pojo
①Account
package com.by.pojo;
import java.util.Date;
public class Account {
private Integer id;
private String name;
private Double money;
private Date date;
private String head;
private String password;
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getHead() {
return head;
}
public void setHead(String head) {
this.head = head;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Double getMoney() {
return money;
}
public void setMoney(Double money) {
this.money = money;
}
}
②User
/*
* Copyright (c) 2020, 2024, webrx.cn All rights reserved.
*
*/
package com.by.pojo;
/**
* <p>Project: ssm - User</p>
* <p>Powered by webrx On 2024-01-12 11:20:57</p>
* <p>描述:<p>
*
* @author 简单遗忘 [[email protected]]
* @version 1.0
* @since 17
*/
public class User {
private Integer id;
private String username;
private String password;
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
6.6 service
①AccountService
package com.by.service;
import com.by.pojo.Account;
import java.util.List;
public interface AccountService {
List<Account> selectAccount();
void addAccount(Account account);
void deleteAccount(Integer id);
void updateAccountById(Account account);
List<Account> sou(String name);
Account loginServlet(Account account);
void deleteAccountByIds(Integer[] id);
}
②AccountServiceImpl
package com.by.service;
import com.by.mapper.AccountMapper;
import com.by.pojo.Account;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Service
public class AccountServiceImpl implements AccountService {
@Autowired
private AccountMapper accountMapper;
@Transactional
@Override
public List<Account> selectAccount() {
return accountMapper.selectAccount();
}
@Override
public void addAccount(Account account) {
accountMapper.addAccount(account);
}
@Override
public void deleteAccount(Integer id) {
accountMapper.deleteAccount(id);
}
@Override
public void updateAccountById(Account account) {
accountMapper.updateAccountById(account);
}
@Override
public List<Account> sou(String name) {
return accountMapper.sou(name);
}
@Override
public Account loginServlet(Account account) {
return accountMapper.loginServlet(account);
}
@Override
public void deleteAccountByIds(Integer[] id) {
accountMapper.deleteAccountByIds(id);
}
}
③UserService
package com.by.service;
import com.by.pojo.User;
public interface UserService {
void Zhuce(User user);
}
④UserServiceImpl
package com.by.service;
import com.by.mapper.UserMapper;
import com.by.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserServiceImpl implements UserService{
@Autowired
private UserMapper userMapper;
@Override
public void Zhuce(User user) {
userMapper.Zhuce(user);
}
}
6.7 servlet
①ImageServlet
package com.by.servlet;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
public class ImageServlet extends HttpServlet {
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
BufferedImage bi = new BufferedImage(68, 22, BufferedImage.TYPE_INT_RGB);//创建图像缓冲区
Graphics g = bi.getGraphics(); //通过缓冲区创建一个画布
Color c = new Color(200, 150, 255); //创建颜色
g.setColor(c);//为画布创建背景颜色
g.fillRect(0, 0, 68, 22); //填充矩形
char[] ch = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();//转化为字符型的数组
Random r = new Random();
int len = ch.length;
int index; //index用于存放随机数字
StringBuffer sb = new StringBuffer();
for (int i = 0; i < 4; i++) {
index = r.nextInt(len);//产生随机数字
g.setColor(new Color(r.nextInt(88), r.nextInt(188), r.nextInt(255))); //设置颜色
g.drawString(ch[index] + "", (i * 15) + 3, 18);//画数字以及数字的位置
sb.append(ch[index]);
}
request.getSession().setAttribute("piccode", sb.toString());
ImageIO.write(bi, "JPG", response.getOutputStream());
}
}