一个简易的基于SSM的数据处理后台
- 一、环境的搭建
- 二、具体业务功能的实现
- 以上
一、环境的搭建
1.1环境搭建步骤
1.1.1创建工程(Project&Module)
在创建工程这一步,建议如果是联网状态,直接通过maven提供的maven模版中-webapp创建一个模块,这样做,就可以直接降低之后,为了添加webapp这个文件夹的琐碎步骤,而另外两个java和resource文件夹以及一个test文件夹。会在你创建文件夹选项下,给你选择;
1.1.2导入静态页面
将提供的静态资源,直接复制、粘贴当项目中webapp目录下,这一步骤,可以需要较长的时间;
1.1.3 导入需要坐标(见资料中的pom.xml)
导入maven需要的jar包的坐标,
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.5</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.27</version>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.10</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.2.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.3</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.7</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.8.1</version>
<scope>compile</scope>
</dependency>
1.1.4 创建包结构(controller、service、dao、entity、utils)
1.1.5 导入数据库脚本(test.sql)
在数据库可视化工具中,直接导入test.sql,执行;建库建表
/*
SQLyog Ultimate v12.09 (64 bit)
MySQL - 5.7.24-log : Database - test
*********************************************************************
*/
/*!40101 SET NAMES utf8 */;
/*!40101 SET SQL_MODE=''*/;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
CREATE DATABASE /*!32312 IF NOT EXISTS*/`test` /*!40100 DEFAULT CHARACTER SET utf8 */;
USE `test`;
/*Table structure for table `sys_role` */
DROP TABLE IF EXISTS `sys_role`;
CREATE TABLE `sys_role` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`roleName` varchar(50) DEFAULT NULL,
`roleDesc` varchar(50) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
/*Data for the table `sys_role` */
insert into `sys_role`(`id`,`roleName`,`roleDesc`) values (1,'院长','负责全面工作'),(2,'研究员','课程研发工作'),(3,'讲师','授课工作'),(4,'助教','协助解决学生的问题');
/*Table structure for table `sys_user` */
DROP TABLE IF EXISTS `sys_user`;
CREATE TABLE `sys_user` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`username` varchar(50) DEFAULT NULL,
`email` varchar(50) DEFAULT NULL,
`password` varchar(80) DEFAULT NULL,
`phoneNum` varchar(20) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
/*Data for the table `sys_user` */
insert into `sys_user`(`id`,`username`,`email`,`password`,`phoneNum`) values (1,'zhangsan','zhangsan@itcast.cn','123','13888888888'),(2,'lisi','lisi@itcast.cn','123','13999999999'),(3,'wangwu','wangwu@itcast.cn','123','18599999999');
/*Table structure for table `sys_user_role` */
DROP TABLE IF EXISTS `sys_user_role`;
CREATE TABLE `sys_user_role` (
`userId` bigint(20) NOT NULL,
`roleId` bigint(20) NOT NULL,
PRIMARY KEY (`userId`,`roleId`),
KEY `roleId` (`roleId`),
CONSTRAINT `sys_user_role_ibfk_1` FOREIGN KEY (`userId`) REFERENCES `sys_user` (`id`),
CONSTRAINT `sys_user_role_ibfk_2` FOREIGN KEY (`roleId`) REFERENCES `sys_role` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*Data for the table `sys_user_role` */
insert into `sys_user_role`(`userId`,`roleId`) values (1,1),(1,2),(2,2),(2,3);
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
1.1.6 创建POJO类
Role:
package com.zkwf.entity;
public class Role {
private Long id;
private String roleName;
private String roleDesc;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public String getRoleDesc() {
return roleDesc;
}
public void setRoleDesc(String roleDesc) {
this.roleDesc = roleDesc;
}
@Override
public String toString() {
return "Role{" +
"id=" + id +
", roleName='" + roleName + '\'' +
", roleDesc='" + roleDesc + '\'' +
'}';
}
}
User:
package com.zkwf.entity;
import java.util.List;
public class User {
private Long id;
private String username;
private String email;
private String password;
private String phoneNum;
private List<Role> roleList;
public List<Role> getRoleList() {
return roleList;
}
public void setRoleList(List<Role> roleList) {
this.roleList = roleList;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPhoneNum() {
return phoneNum;
}
public void setPhoneNum(String phoneNum) {
this.phoneNum = phoneNum;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", email='" + email + '\'' +
", password='" + password + '\'' +
", phoneNum='" + phoneNum + '\'' +
", roleList=" + roleList +
'}';
}
}
1.1.7 创建配置文件(applicationContext.xml,spring-mvc.xml, jdbc.properties , log4 j .properties,SqlMapConfig.xml,UserMapper.xml),以及web配置文件web.xml的配置
1.1.7.1 applicationContext.xml(为spring框架的核心配置文件)
该核心配置文件的作用主要用于,spring容器创建,以POJO对象的创建;以及事务的管理,事务注解驱动的配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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
">
<!--由于有import标签 就可以使用它进行一个分模块配置-->
<!--spring关于jdbc模版的配置-->
<import resource="classpath:applicationContext-DataSource.xml"></import>
<!--分别对有关DAO,Serivce进行配置-->
<bean id="roleDao" class="com.zkwf.Dao.Impl.RoleDaoImpl">
<property name="jdbcTemplate" ref="jdbcTemplate"/>
</bean>
<bean id="roleSerivce" class="com.zkwf.Service.Impl.RoleSerivceImpl">
<property name="roleDao" ref="roleDao"/>
</bean>
<bean id="userDao" class="com.zkwf.Dao.Impl.UserDaoImpl">
<property name="jdbcTemplate" ref="jdbcTemplate"/>
</bean>
<bean id="userService" class="com.zkwf.Service.Impl.UserServiceImpl">
<property name="userDao" ref="userDao"/>
<property name="roleDao" ref="roleDao"/>
</bean>
<!--配置平台事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
<property name="defaultTimeout" value="1"/>
</bean>
<!--将mapper交个spring管理-->
<bean id="SqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--set注入,把数据库连接池赋给了dataSource属性-->
<property name="dataSource" ref="dataSource"/>
<!--
mybatis主配置文件的位置,因为是在spring中指定mybatis主配置文件,所以要用classpath:
configLocation:属性是Resource类型的,负责读取配置文件
赋值使用 value 指定文件的路径
-->
<property name="configLocation" value="classpath:SqlMapConfig.xml"/>
<property name="mapperLocations" value="classpath:com/zkwf/mapping/UserMapper.xml"></property>
</bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 扫描所有dao接口的实现,加入到IOC容器中-->
<property name="basePackage" value="com.zkwf.DaoPlus"/>
</bean>
<!--配置注解扫描-->
<context:component-scan base-package="com.zkwf.Service.Impl"></context:component-scan>
<context:component-scan base-package="com.zkwf.DaoPlus"></context:component-scan>
<!--配置事务注解驱动-->
<tx:annotation-driven/>
</beans>
关于提及此文件中提及的标签中applicationContext-DataSource.xml,总所周知,在spring中标签常用与,进行分模块开发,在本次设计中,将spring的jdbcTemplate(因为本项目只是简易的集成了mybatis,使用nybatis也主要使用xml配置文件进行sql语言的编写,而数据访问层的主要操作还是要通过spring提供的jdbc模版进行操作)作为另一个模块直接导入使用
applicationContext-DataSource.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"
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
">
<!--由于有import标签 就可以使用它进行一个分模块配置-->
<!--要连接数据库就要使用jspring提供的jdbc模版那么就要配置jdbc-->
<!--配置数据源需要外部参数,最好将这些写在另一个配置文件中,引入context命名空间-->
<context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>
<!--配置模版需要一个数据源-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${driverClassName}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</bean>
<!--配置JDBC模版-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>
</beans>
1.1.7.2 spring-mvc.xml(为springMVC框架的核心配置文件)
该文件主要配置mvc注解驱动,配置默认访问的servlet(对外开发静态资源的访问),以及部分简易的师徒解析器,配置spring-mvc的注解扫描,以及一个拦截器,以及一个简单的异常处理
<?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: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/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
">
<!--1、配置mvc注解驱动-->
<mvc:annotation-driven/>
<!--2、核心控制器配置了缺省 那么我们就要对外开发对与静态资源的访问-->
<mvc:default-servlet-handler/>
<!--3、配置视图解析器-->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/pages/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!--扫描注解-->
<context:component-scan base-package="com.zkwf.Controller"/>
<!--配置拦截器-->
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**"/>
<mvc:exclude-mapping path="/user/login"/>
<!--请求静态资源放行-->
<mvc:exclude-mapping path="/img/**">
<mvc:exclude-mapping path="/css/**">
<mvc:exclude-mapping path="/plugins/**">
<mvc:exclude-mapping path="/pages/**">
<bean class="com.zkwf.Intercetor.Intercetor"></bean>
</mvc:interceptor>
</mvc:interceptors>
<!--配置简单异常处理-->
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="defaultErrorView" value="error"/>
</bean>
</beans>
1.1.7.3 SqlMapConfig.xml(为mybatis框架的核心配置文件)
该配置文件为mybatis的核心配置文件,主要配置有,运行环境,配置的mapper,重命名等
<?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>
<!--引入的文件有一定的顺序-->
<!--配置外部配置文件-->
<properties resource="jdbc.properties"></properties>
<!--重命名-->
<typeAliases>
<typeAlias type="com.zkwf.entity.User" alias="user"></typeAlias>
</typeAliases>
<!--配置运行环境-->
<environments default="">
<environment id="">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="${driverClassName}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<!--配置mapper-->
<mappers>
<mapper resource="com/zkwf/mapping/UserMapper.xml"></mapper>
</mappers>
</configuration>
1.1.7.4 UserMapper.xml(为mybatis的映射配置文件)
<?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.zkwf.DaoPlus.UserMapping">
<!--查询所有user对象-->
<select id="findAllUser" resultType="user">
select * from sys_user
</select>
</mapper>
1.1.7.5 jdbc.properties(为连接数据库的外部配置文件)
#jdbc.driver=com.mysql.jdbc.Driver
#jdbc.url=jdbc:mysql://localhost:3306/test
#jdbc.username=root
#jdbc.password=root
driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/test?rewriteBatchedStatements=true
username=root
password=12345678
1.1.7.6 log4j .properties(为日志配置文件)
### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
### direct messages to file mylog.log ###
log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.file.File=c:/mylog.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
### set log levels - for more verbose logging change 'info' to 'debug' ###
log4j.rootLogger=info, stdout
1.1.7.6 web.xml配置
该配置文件主要用于,web项目启动便创建spring容器,配置listener,servlet(核心控制器)、以及过滤器的配置
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<!--配置一个初始化就创建一个spring容器-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!--配置一个过滤器 涉及编码格式-->
<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>
<!--先配置web的listern-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--再配置-spring-mvc的类型控制器-->
<servlet>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
二、具体业务功能的实现
2.1关与角色
2.1.1 角色列表的展示
2.1.1.1 Controller层处理
//交给spring进行管理
@Controller
//配置当前类的父访问路径
@RequestMapping("/role")
public class RoleController {
//给一个role的service属性 先用注入 通过注解
@Autowired
private RoleSerivce roleSerivce;
@RequestMapping("/list")
public ModelAndView RoleList(){
ModelAndView modelAndView = new ModelAndView();
//设置模型和视图
List<Role> roleList = roleSerivce.findAllRole();
modelAndView.addObject("roleList",roleList);
modelAndView.setViewName("role-list");
return modelAndView;
}
}
2.1.1.2 Service层处理
//通过配置文件 set方法注入
private RoleDao roleDao;
public void setRoleDao(RoleDao roleDao) {
this.roleDao = roleDao;
}
/**
* 查询所有的角色的业务逻辑
* @return List<Role>
*/
@Override
public List<Role> findAllRole() {
//集成一个缓存
//得到一个redis客户端
//Jedis jedis = JedisUtil.getJedis();
//List<String> roleList = jedis.lrange("roleList", 0, -1);
List<Role> roleList = roleDao.findAllRole();
return roleList;
}
2.1.1.3 Dao层处理
private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
@Override
public List<Role> findAllRole() {
List<Role> roleList = jdbcTemplate.query("SELECT * FROM sys_role", new BeanPropertyRowMapper<Role>(Role.class));
return roleList;
}
2.1.2 角色列表的删除
2.1.1.1 Controller层处理
@RequestMapping("/delRole")
public String delRole(Long roleId){
ModelAndView modelAndView = new ModelAndView();
//设置模型和视图
roleSerivce.DeleteRoleByID(roleId);
return "redirect:/role/list";
}
此方法中参数值的注入 是由spring自动注入,注入的前提的,通过前台传过来的路径中有和该参数名一致的,参数
2.1.1.2 Service层处理
@Override
public void DeleteRoleByID(Long roleId) {
roleDao.delectRoleById(roleId);
}
2.1.1.3 Dao层处理
@Override
public void delectRoleById(Long roleId) {
jdbcTemplate.update("delete from sys_role where id = ?",roleId);
}
2.1.3 角色列表的增加
2.1.1.1 Controller层处理
@RequestMapping("/add")
public String AddRole(Role role){
ModelAndView modelAndView = new ModelAndView();
//设置模型和视图
roleSerivce.saveRole(role);
return "redirect:/role/list";
}
该role对象的属性的注入,也是有spring框架自动注入,spring会根据前台传递过来的数据根据属性名自动的注入到对应对象的同名属性中,从而完成对象的注入
2.1.1.2 Service层处理
/**
* 增加一个角色
* @param role
*/
@Override
public void saveRole(Role role) {
roleDao.saveRole(role);
}
2.1.1.3 Dao层处理
@Override
public void saveRole(Role role) {
jdbcTemplate.update("insert into sys_role values(?,?,?)",null,role.getRoleName(),role.getRoleDesc());
}
2.2关于用户
2.2.1 用户列表的展示
2.2.1.1 Controller层实现
@RequestMapping("/findAll")
public ModelAndView findAllUser(){
ModelAndView modelAndView = new ModelAndView();
List<User> userList = userService.findAllUser();
modelAndView.addObject("userList",userList);
modelAndView.setViewName("user-list");
return modelAndView;
}
2.2.1.2 Service层实现
@Autowired
private UserMapping mapper;
@Override
public List<User> findAllUser() {
List<User> userList1 = mapper.findAllUser();
//List<User> userList = userDao.findAllUser();
for (User user : userList1) {
List<Role> roleList = roleDao.findUserRoleById(user.getId());
user.setRoleList(roleList);
}
return userList1;
}
2.2.1.3 Dao层实现
该数据访问的实现主要通过mybatis核心配置文件+映射文件(详情见上问关于环境搭建)
public interface UserMapping {
List<User> findAllUser();
}
2.2.2 用户的登录
2.2.2.1 设置一个拦截器
拦截器的作用,主要对请求的所有访问控制器的方法,使用步骤,
1、先的创建一个Intercetor包里面创建一个拦截器类去实现HandlerInterceptor,然后重写preHandle方法,根据具体需求,放不放行;
具体实现:
package com.zkwf.Intercetor;
import com.zkwf.entity.User;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* @description:
* @author: Sw_Ljb
* @PACKAGE_NAME:com.zkwf
* @time: 2022/6/18 下午3:57
* @version: 1.0
*/
public class Intercetor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("拦截器.......");
HttpSession session = request.getSession();
User user = (User) session.getAttribute("user");
request.removeAttribute("user");
if (user==null){
response.setStatus(200);
response.sendRedirect(request.getContextPath()+"/login.jsp");
return false;
}else {
return true;
}
}
}
2、在spring-mvc中配置一个拦截器文件
具体实现见上文,环境搭建中关于spring-mvc配置文件的实现
2.2.2.2登录的Controller实现
@RequestMapping("/login")
public String login(String username, String password, HttpSession session){
// spring会自动去根据前台的传过来的属性名注入与之相对应的参数名中
User u =userService.login(username,password);
if (u==null){
//转发到login.jsp
return "redirect:/login.jsp";
}else {
//session主要用于存储登录对象,spring会自动去注入由tomcat提供的session对象,
session.setAttribute("user",u);
return "redirect:/user/findAll";
}
}
2.2.2.3登录的Service实现
@Override
public User login(String username, String password) {
User user = userDao.findUser(username, password);
return user;
}
2.2.2.4登录的DAO实现
@Override
public User findUser(String username, String password) {
try {
User user = jdbcTemplate.queryForObject("select * from sys_user where username=? and password=?", new BeanPropertyRowMapper<User>(User.class), username, password);
return user;
}catch (Exception e){
return null;
}
}
2.2.3 用户的删除
分析:由于数据表中含有三张表,一张为user表,一张为role表,因为这两张表是一个多对多的关系,所以需要一个中间表作为维护;而中间表中的属性为另外两张表中的主键,也就说这张表与另外两张表产生了一个依赖关系,要进行删除就得有个先后次序,先为依赖者,后为被依赖者,在本次操作中,依赖者为中间表,被依赖者为user表,而两次的数据库操作就涉及到事务处理了,但是由于我们本次开发使用的框架,并不建议我们直接用jdbc原生的事物管理去做事物的处理,本次开发使用的spring提供的声明式事物管理(关于事务管理器的配置 以及事务注解驱动 详情见上文中关于spring核心配置文件的说明)
2.2.3.1删除操作
2.2.3.1.1删除的Controller层实现
@RequestMapping("/del")
public String delUser(Long userId) throws Exception {
userService.delUserById(userId);
return "redirect:/user/findAll";
}
2.2.3.1.1删除的Service层实现
@Override
@Transactional(isolation = Isolation.READ_COMMITTED,propagation = Propagation.REQUIRED)
public void delUserById(Long userId) throws Exception{
//先删除关系表中的数据
userDao.delUserRelRole(userId);
//搞个错误,这里用到事务
//int i= 1/0;
//在删除user表中数据
userDao.delUserById(userId);
}
2.2.3.1.1删除的DAO层实现
/**
* 先删除关系表中数据
* @param userId
*/
@Override
public void delUserRelRole(Long userId) {
jdbcTemplate.update("delete from sys_user_role where userId = ?",userId);
}
@Override
public void delUserById(Long userId) {
jdbcTemplate.update("delete from sys_user where id = ?",userId);
}
2.2.4 用户的增加
2.2.4.1增加分析
关于增加操作,一个难点在于,前台不提供后台自动的生成的ID,而增加一个用户势必会去增加该用户的角色,而增加角色 就势必会涉及到id的使用,所以增加用户的核心在于当我插入了该数据后,如何得到该项的ID值,(在不涉及到其他关于dao层框架之外)我个人认为有两种方法,一个是执行update后 在执行query操作,但是这样做,势必会导致二次操作数据库,降低性能,并且这种操作理因涉及事务的处理,第二种在dao层使用spring提供的jdbctemplate模版之外 再通过一个原生的jdbc模版进行操作
2.2.4.2具体增加操作的实现
2.2.4.2.1 增加的Controller层实现
@RequestMapping("/save")
public String saveUser(User user,Long[] roleIds){
/**
* System.out.println(user);
* User{id=null, username='zhangsan', email='1434857520@qq.com', password='123', phoneNum='12345678000',
* roleList=null}
* 0
* 1
*/
//将传过来的user保存到user表中 并把自动生成的ID返回回来
Long userId = userService.saveUser(user);
//返回的userID+roleIds存到表中
/*for (int i = 0; i < roleIds.length; i++) {
System.out.println(i);
}*/
userService.saveUserRoleId(userId,roleIds);
return "redirect:/user/findAll";
}
2.2.4.2.2 增加的Service层实现
@Override
public Long saveUser(User user) {
return userDao.saveUser(user);
}
@Override
public void saveUserRoleId(Long userId, Long[] roleIds) {
userDao.saveUserRoleId(userId,roleIds);
}
2.2.4.2.3 增加的Dao层实现
**
* 用原生JDBC进行操作
* @param user
* @return
*/
@Override
public Long saveUser(final User user) {
//处理SQL
PreparedStatementCreator creator = new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
PreparedStatement preparedStatement = connection.prepareStatement("insert into sys_user values(?,?,?,?,?)", PreparedStatement.RETURN_GENERATED_KEYS);
preparedStatement.setObject(1,null);
preparedStatement.setString(2,user.getUsername());
preparedStatement.setString(3,user.getEmail());
preparedStatement.setString(4,user.getPassword());
preparedStatement.setString(5,user.getPhoneNum());
return preparedStatement;
}
};
//获取自动生成的ID
GeneratedKeyHolder keyHolder = new GeneratedKeyHolder();
jdbcTemplate.update(creator,keyHolder);
long userId = keyHolder.getKey().longValue();
return userId;
}
/**
* 存储关系user-role关系
* @param userId
* @param roleIds
*/
@Override
public void saveUserRoleId(Long userId, Long[] roleIds) {
for (Long roleId : roleIds) {
jdbcTemplate.update("insert into sys_user_role values (?,?)",userId,roleId);
}
}