spring + spring mvc + mybatis + mysql8.0
vue + vuex + element-ui
1、用户登录(包括自动登录)、退出、权限拦截
2、学生报道登记管理(列表、新增、编辑、删除、按条件查询、文件上传)
前端
前端还是使用较为经典的 vue2 项目,通过 vue-cli 搭建。
后端
搭建时,注意还是搭建maven的web项目,这样才能建立后端服务,也尝试搭建过maven的普通Java项目,但是后边发现把它放在tomcat服务器里边无法为前端提供服务。
跨域问题是因为浏览器的同源策略引起的,所谓同源是指"协议+域名+端口"三者相同,即便两个不同的域名指向同一个 ip 地址,也非同源。同源策略/SOP(Same origin policy)是一种约定,由 Netscape 公司 1995 年引入浏览器,它是浏览器最核心也最基本的安全功能,现在所有支持 JavaScript 的浏览器都会使用这个策略。如果缺少了同源策略,浏览器很容易受到 XSS、 CSFR 等攻击。
前端项目如果是vue项目,可以在vue的全局配置文件vue.config.js 中进行配置,将需要访问的后端地址进行代理,从安全方面考虑,推荐这样做,具体配置如下:
const define = require("./src/util/define")
// define是自己定义的一些全局配置变量,便于管理
module.exports = {
// 去除代码规范
lintOnSave: false,
devServer: {
proxy: {
"/api": {
target: define.APIURL, // define.APIURL就是你后端服务的地址
ws: true,
changeOrigin: true,
pathRewrite: {
'^/api': ''
}
}
}
}
}
后端我使用的 spring 版本是 4.0 以上的,所以配置跨域很简单,只需要在相应的控制器或方法上加上注解 @CrossOrigin(origins = {"http://localhost:8080"})。
你也可以直接使用 @CrossOrgin 来进行配置,但是这样所有的访问地址都可以访问到你的服务,不安全。同时,这个注解也可以放在方法上,表示这个方法单独可以被访问。
关于后端解决跨域的方式还有其他途径,比如全局配置拦截器,这里再不做细讲。
<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.0modelVersion>
<groupId>com.cxswgroupId>
<artifactId>rmsServiceartifactId>
<version>1.0version>
<packaging>warpackaging>
<name>rmsServicename>
<url>http://localhost:3000url>
<properties>
<project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
<maven.compiler.source>1.7maven.compiler.source>
<maven.compiler.target>1.7maven.compiler.target>
properties>
<dependencies>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.13.2version>
<scope>testscope>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-testartifactId>
<version>5.3.22version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-contextartifactId>
<version>5.3.22version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>5.3.22version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-jdbcartifactId>
<version>5.3.22version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-txartifactId>
<version>5.3.22version>
dependency>
<dependency>
<groupId>org.aspectjgroupId>
<artifactId>aspectjweaverartifactId>
<version>1.9.9.1version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.5.10version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>8.0.30version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druidartifactId>
<version>1.1.20version>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<version>1.18.24version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatis-springartifactId>
<version>2.0.7version>
dependency>
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-coreartifactId>
<version>2.13.3version>
dependency>
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-databindartifactId>
<version>2.13.3version>
dependency>
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-annotationsartifactId>
<version>2.13.3version>
dependency>
<dependency>
<groupId>commons-fileuploadgroupId>
<artifactId>commons-fileuploadartifactId>
<version>1.4version>
dependency>
<dependency>
<groupId>commons-iogroupId>
<artifactId>commons-ioartifactId>
<version>2.11.0version>
dependency>
<dependency>
<groupId>org.slf4jgroupId>
<artifactId>slf4j-log4j12artifactId>
<version>1.7.36version>
dependency>
dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.tomcat.mavengroupId>
<artifactId>tomcat7-maven-pluginartifactId>
<version>2.2version>
<configuration>
<port>3000port>
<path>/path>
configuration>
plugin>
plugins>
build>
project>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
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/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">
<context:component-scan base-package="com.cxsw.rms">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
context:component-scan>
<context:property-placeholder location="classpath:jdbc.properties"/>
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${druid.jdbc.driver}"/>
<property name="url" value="${druid.jdbc.url}"/>
<property name="username" value="${druid.jdbc.username}"/>
<property name="password" value="${druid.jdbc.password}"/>
bean>
<bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="classpath:mybatis.xml"/>
<property name="mapperLocations" value="classpath:/mappers/*.xml"/>
bean>
<bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg ref="sqlSessionFactoryBean"/>
bean>
<bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.cxsw.rms.repository"/>
bean>
<bean id="dataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
bean>
<tx:advice id="txAdvice" transaction-manager="dataSourceTransactionManager">
<tx:attributes>
<tx:method name="insert*"/>
<tx:method name="delete*"/>
<tx:method name="update*"/>
tx:attributes>
tx:advice>
<aop:config>
<aop:pointcut id="pointCut" expression="execution(* com.cxsw.rms.service.impl.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="pointCut"/>
aop:config>
beans>
<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">
<context:component-scan base-package="com.cxsw.rms.controller" />
<mvc:annotation-driven />
<bean id="dateConverter" class="com.cxsw.rms.convert.DateConverter" />
<bean class="org.springframework.context.support.ConversionServiceFactoryBean" id="conversionService">
<property name="converters" ref="dateConverter" />
bean>
<mvc:annotation-driven conversion-service="conversionService"/>
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="52128800" />
<property name="maxUploadSizePerFile" value="52128800"/>
<property name="defaultEncoding" value="UTF-8"/>
bean>
<mvc:default-servlet-handler />
beans>
DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<typeAliases>
<typeAlias type="com.cxsw.rms.entity.User" alias="user"/>
<typeAlias type="com.cxsw.rms.entity.Student" alias="student"/>
typeAliases>
configuration>
druid.jdbc.driver=com.mysql.cj.jdbc.Driver
druid.jdbc.url=jdbc:mysql://localhost:3306/rms?useUnicode=true&characterEncoding=utf-8
druid.jdbc.username=root
druid.jdbc.password=wb7446032001
DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.cxsw.rms.repository.StudentMapper">
<resultMap id="studentMap" type="student">
<id property="sid" column="SID" />
<result property="name" column="NAME" />
<result property="nation" column="NATION" />
<result property="idCard" column="ID_CARD" />
<result property="region" column="REGION" />
<result property="education" column="EDUCATION" />
<result property="school" column="SCHOOL" />
<result property="major" column="MAJOR" />
<result property="educationType" column="EDUCATION_TYPE" />
<result property="email" column="EMAIL" />
<result property="phone" column="PHONE" />
<result property="employeeUnit" column="EMPLOYEE_UNIT" />
<result property="registerBook" column="REGISTER_BOOK" />
<result property="diploma" column="DIPLOMA" />
<result property="creatTime" column="CREAT_TIME" />
resultMap>
<insert id="insertStudent" parameterType="student">
INSERT INTO STUDENTS (`SID`, `NAME`, NATION, ID_CARD, REGION, EDUCATION, SCHOOL, MAJOR, EDUCATION_TYPE,
EMAIL, PHONE, EMPLOYEE_UNIT, REGISTER_BOOK, DIPLOMA, CREAT_TIME) VALUE
(
#{sid}, #{name}, #{nation}, #{idCard}, #{region}, #{education}, #{school}, #{major},
#{educationType}, #{email}, #{phone}, #{employeeUnit}, #{registerBook}, #{diploma},
#{creatTime}
)
insert>
mapper>
映射数据库字段的实体个人建议使用Lombok代码生成器,这样你在修改字段的时候就不用来回手动生成get set tostring …… 等方法了。
用法如下:
org.projectlombok
lombok
1.18.24
@NoArgsConstructor 生成无参数的构造方法
通过上图就可以发现,在单独写了实体字段的情况下,通过注解就可以自动生成代码。
持久层的接口:这里以新增数据的某个接口示例
/**
* 信息登记数据层
* @author zhangsan
* @date 2022-08-25
*/
public interface StudentMapper {
/**
* 新增信息登记
* @param student 信息登记对象
* @return 0 代表新增失败 反之成功
*/
int insertStudent(Student student);
}
对应的mapper(由于新增字段有点多,没有使用mybatis的注解来写sql)
DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.cxsw.rms.repository.StudentMapper">
<insert id="insertStudent" parameterType="student">
INSERT INTO STUDENTS (`SID`, `NAME`, NATION, ID_CARD, REGION, EDUCATION, SCHOOL, MAJOR, EDUCATION_TYPE,
EMAIL, PHONE, EMPLOYEE_UNIT, REGISTER_BOOK, DIPLOMA, CREAT_TIME) VALUE
(
#{sid}, #{name}, #{nation}, #{idCard}, #{region}, #{education}, #{school}, #{major},
#{educationType}, #{email}, #{phone}, #{employeeUnit}, #{registerBook}, #{diploma},
#{creatTime}
)
insert>
mapper>
/**
*信息填报接口业务逻辑层
*@author zhangsan
*@date 2022-08-26
*/
public interface StudentService {
/**
* 新增信息登记
* @param student 信息登记对象
* @return 0代表新增失败 反之成功
*/
String insertStudent(Student student);
}
实现类:
/**
* 信息填报业务层实现
* @author zhangsan
* @date 2022-08-26
*/
@Service
public class StudentServiceImpl implements StudentService {
@Resource
private StudentMapper studentMapper;
/**
* 新增信息登记
* @param student信息登记对象
* @return 0代表新增失败 反之成功
*/
@Override
public String insertStudent(Student student) {
Date date = new Date(new java.util.Date(System.currentTimeMillis()).getTime());
student.setCreatTime(date);
studentMapper.insertStudent(student);
List<Student> students = studentMapper.listStudents(student.getName(), "");
User user = new User();
user.setUsername(student.getName());
user.setSid(students.get(0).getSid());
int res = userMapper.updateUserForeignKey(user);
if(res == 0){
return "新增失败";
}else{
return "新增成功";
}
}
}
/**
* 信息填报接口
* @author zhangsan
* date 2022-08-26
*/
@RestController
@RequestMapping(value = "/student")
public class StudentController {
@Resource
private StudentService studentService;
/**
* 新增信息填报接口
* @param student 学生对象
* @return result 对象
*/
@PostMapping
public Result createStudentList(@RequestBody Student student){
if(student == null){
return new Result(500, "上报信息不全", null);
}else{
String msg = studentService.insertStudent(student);
return new Result(200, "操作成功", msg);
}
}
}
import axios from "axios";
// message 是自己对element-ui总的消息提示框进行的封装,防止其重复弹出
import { message } from "@/util/message"
// 拦截响应
axios.interceptors.response.use(
response => {
if (!response?.data) return;
const res = response.data;
if (res.code !== 200) {
message({
message: res.msg || '请求出错,请重试',
type: "error",
duration: 1500,
onClose: () => {
// 消息框退出时需要处理的逻辑
}
})
} else {
return res;
}
},
error => {
message({
message: "请求出错,请重试",
type: "error",
duration: 1500
})
// 返回错误
return Promise.reject(error)
}
)
// 封装请求
const request = async ({ url, method, data, headers }) => {
const type = method.toLocaleUpperCase();
if (type === 'GET') {
return await new Promise((res, rej) => {
getRequest(url, data, res, rej)
})
} else if (type === 'POST') {
return await new Promise((res, rej) => {
postRequest(url, data, headers, res, rej)
})
} else if (type === 'PUT') {
return await new Promise((res, rej) => {
putReqeust(url, data, res, rej)
})
} else {
return await new Promise((res, rej) => {
deleteRequest(url, res, rej)
})
}
}
// get 请求
const getRequest = (url, datas, res, rej) => {
axios.get(url, { params: datas }).then((data) => {
res(data)
}).catch((error) => {
rej(error)
})
}
// put 请求
const putReqeust = (url, datas, res, rej) => {
axios.put(url, datas).then((data) => {
res(data)
}).catch((error) => {
rej(error)
})
}
// delete 请求
const deleteRequest = (url, res, rej) => {
axios.delete(url).then((data) => {
res(data)
}).catch((error) => {
rej(error)
})
}
// post请求
const postRequest = (url, datas, headers, res, rej) => {
axios.post(url, datas, headers).then((data) => {
res(data)
}).catch((error) => {
rej(error)
})
}
export default request;
message的封装如下:
import { Message } from 'element-ui'
let messageInstance = null;
// 防止重复弹出消息提示
const resetMessage = (options) => {
if (messageInstance) {
messageInstance.close()
}
messageInstance = Message(options)
};
let tipType = ["error", "info", "success", "warning"];
tipType.forEach(type => {
resetMessage[type] = options => {
if (typeof options === "string") {
options = {
message: options
}
}
options.type = type
return resetMessage(options)
}
})
export const message = resetMessage
在 src 下构建目录 api 用于统一管理接口:
import request from "@/util/request";
// * 新增信息登记
export const addStudnetMsg = (data) => {
return request({
url: "/api/student",
method: "POST",
data
})
}
在相应的页面中调用接口:
// 导入 api
import { updateStudentMsg, addStudnetMsg } from "@/api/student"
// 表单提交方法
submitForm(formName) {
this.$refs[formName].validate((valid) => {
if (valid) {
// 根据你实际的页面 调用接口
const formMethod = this.ruleForm.sid ? updateStudentMsg : addStudnetMsg;
this.ruleForm.region = this.ruleForm.region[0] + "-" + this.ruleForm.region[1] + "-" + this.ruleForm.region[2]
formMethod(this.ruleForm).then((data) => {
if (data?.code === 200) {
message({
type: "success",
message: data.msg,
duration: 1500,
onClose: () => {
this.ruleForm.registerBook = ''
this.ruleForm.diploma = ''
this.$router.push("/");
// 更新用户信息
if (!this.ruleForm.sid) {
let params = { username: sessionUtils.get('token').username };
listUsers(params).then((data) => {
if (data?.code === 200) {
data.data[0].password = "";
sessionUtils.set("token", data.data[0], 1000 * 60 * 60 * 6)
// 将数据存储到vuex中
this.$store.dispatch("userInfo/getUserInfo", data.data[0]);
}
})
}
}
})
}
})
} else {
return false;
}
});
至此,一个接口通了。
前端gitee地址:https://gitee.com/wenjingxin/rms.git
后端gitee地址:https://gitee.com/wenjingxin/ssm.git