SSM:Spring+SpringMVC+MyBatis(实现前后端分离)
程序员文章站
2022-07-10 17:38:19
...
背景介绍
前段时间开发涉及到了前后端分离思想,本人涉及到开发后端以及数据库连接处理部分,测试使用postman进行请求,之后对前端请求了解了一部分后完成了一个小的页面,现在分享并记录下来。
分享
话不多说,maven创建工程在之前的文章中已经存在:maven项目创建。创建好的项目结构如下所示:
目前功能只实现了登录注册以及权限的校验功能。接下来看一下各个文件的内容。
1、pom.xml
由于兼容性的问题,本项目采用的是Spring4.1.0.RELEASE、mybatis3.4.0,jdk1.8和Tomcat8.0。
<?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>we</groupId>
<artifactId>we</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>weMaven Webapp</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<properties>
<!-- spring版本号 -->
<spring.version>4.1.0.RELEASE</spring.version>
<!-- mybatis版本号 -->
<mybatis.version>3.4.0</mybatis.version>
<!-- log4j日志文件管理包版本 -->
<slf4j.version>1.7.7</slf4j.version>
<log4j.version>1.2.17</log4j.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<!-- 表示开发的时候引入,发布的时候不会加载此包 -->
<scope>test</scope>
</dependency>
<!-- spring核心包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</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-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-oxm</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-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- mybatis核心包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<!-- mybatis/spring包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.0</version>
</dependency>
<!-- 导入java ee jar 包 -->
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
</dependency>
<!-- 导入Mysql数据库链接jar包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.30</version>
</dependency>
<!-- 导入dbcp的jar包,用来在applicationContext.xml中配置数据库 -->
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.2.2</version>
</dependency>
<!-- JSTL标签类 -->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- 日志文件管理包 -->
<!-- log start -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<!-- 格式化对象,方便输出日志 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.1.41</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j.version}</version>
</dependency>
<!-- log end -->
<!-- 映入JSON -->
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.codehaus.jackson/jackson-core-asl -->
<!--<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
<version>1.9.13</version>
</dependency>-->
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.4</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.4</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.9</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis.generator/mybatis-generator-core -->
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.5</version>
</dependency>
<!-- 引入poi,解析workbook视图 -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.15</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.14</version>
</dependency>
<!-- 处理excel和上面功能是一样的-->
<dependency>
<groupId>net.sourceforge.jexcelapi</groupId>
<artifactId>jxl</artifactId>
<version>2.6.10</version>
</dependency>
<!-- 标签返回 -->
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>2.0.6</version>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-sts</artifactId>
<version>2.1.6</version>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-core</artifactId>
<version>2.1.7</version>
</dependency>
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1-rc1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.guava/guava -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>25.0-jre</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-codec/commons-codec -->
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.10</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.hadoop/hadoop-streaming -->
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-streaming</artifactId>
<version>2.6.0</version>
</dependency>
</dependencies>
<build>
<resources>
<!--编译之后包含xml-->
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
</project>
2、jdbc.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://xxx.xxx.xxx:3306/xxx
username=xxx
password=xxx
#定义初始连接数
initialSize=0
#定义最大连接数
maxActive=20
#定义最大空闲
maxIdle=20
#定义最小空闲
minIdle=1
#定义最长等待时间
maxWait=50000
2、log4j.properties
log4j管理日志文件比较方便,本人用的也不是很熟练,之后仔细了解后会在文章中会单独介绍一下。
log4j.rootLogger = info,stdout,D,E
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 = [%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File =D:\\home\\log\\lpf.log
log4j.appender.D.Append = true
log4j.appender.D.Threshold = DEBUG
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
log4j.appender.E = org.apache.log4j.DailyRollingFileAppender
log4j.appender.E.File =D:\\home\\log\\lpf1.log
log4j.appender.E.Append = true
log4j.appender.E.Threshold = ERROR
log4j.appender.E.layout = org.apache.log4j.PatternLayout
log4j.appender.E.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
3、spring-mvc.xml
springmvc使用了fastjson,并且为了接收请求时不使用@RequestBody。
<?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-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<!-- 自动扫描该包,使SpringMVC认为包下用了@Controller注解的类是控制器 -->
<context:component-scan base-package="com.lpf.controller" />
<mvc:default-servlet-handler />
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8</value>
<value>application/json</value>
</list>
</property>
<property name="features">
<list>
<!-- 输出key时是否使用双引号 -->
<value>QuoteFieldNames</value>
<!-- 是否输出值为null的字段 -->
<!-- <value>WriteMapNullValue</value> -->
<!-- 数值字段如果为null,输出为0,而非null -->
<value>WriteNullNumberAsZero</value>
<!-- List字段如果为null,输出为[],而非null -->
<value>WriteNullListAsEmpty</value>
<!-- 字符类型字段如果为null,输出为"",而非null -->
<value>WriteNullStringAsEmpty</value>
<!-- Boolean字段如果为null,输出为false,而非null -->
<value>WriteNullBooleanAsFalse</value>
<!-- null String不输出 -->
<value>WriteNullStringAsEmpty</value>
<!-- null String也要输出 -->
<!-- <value>WriteMapNullValue</value> -->
<!-- Date的日期转换器 -->
<value>WriteDateUseDateFormat</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<!-- 定义跳转的文件的前后缀 ,视图模式配置-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- controller最后返回的值xx,则页面即是webapp/jsp/xx.jsp -->
<property name="prefix" value="/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver"
p:defaultEncoding="UTF-8">
<property name="maxUploadSize">
<value>104857600</value>
</property>
<property name="maxInMemorySize">
<value>4096</value>
</property>
</bean>
</beans>
4、spring-mybatis.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:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:p="http://java.sun.com/jsf/composite"
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.lpf" />
<!-- 引入配置文件 -->
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:jdbc.properties" />
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${driver}" />
<property name="url" value="${url}" />
<property name="username" value="${username}" />
<property name="password" value="${password}" />
<!-- 初始化连接大小 -->
<property name="initialSize" value="${initialSize}"></property>
<!-- 连接池最大数量 -->
<property name="maxActive" value="${maxActive}"></property>
<!-- 连接池最大空闲 -->
<property name="maxIdle" value="${maxIdle}"></property>
<!-- 连接池最小空闲 -->
<property name="minIdle" value="${minIdle}"></property>
<!-- 获取连接最大等待时间 -->
<property name="maxWait" value="${maxWait}"></property>
</bean>
<!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!-- 自动扫描mapping.xml文件 -->
<property name="mapperLocations" value="classpath:com/lpf/mapping/**/*.xml"></property>
</bean>
<!-- DAO接口所在包名,Spring会自动查找其下的类 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.lpf.dao" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
</bean>
<!-- (事务管理)transaction manager, use JtaTransactionManager for global tx -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
</beans>
5、bean以及Mapper的生成
mybatis-generator-core-1.3.5.jar,如何自动生成之后讲解。
看一下生成后的文件:
UserDto.java
package com.lpf.dto;
import java.util.Date;
public class UserDto {
private String id;
private String account;
private String password;
private String name;
private String sex;
private String identityCardNumber;
private String mobile;
private String email;
private String avatar;
private String actor;
private String editor;
private Date createdTime;
private Date modifiedTime;
private Boolean deleted;
private String extendInfo;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id == null ? null : id.trim();
}
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account == null ? null : account.trim();
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password == null ? null : password.trim();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name == null ? null : name.trim();
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex == null ? null : sex.trim();
}
public String getIdentityCardNumber() {
return identityCardNumber;
}
public void setIdentityCardNumber(String identityCardNumber) {
this.identityCardNumber = identityCardNumber == null ? null : identityCardNumber.trim();
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile == null ? null : mobile.trim();
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email == null ? null : email.trim();
}
public String getAvatar() {
return avatar;
}
public void setAvatar(String avatar) {
this.avatar = avatar == null ? null : avatar.trim();
}
public String getActor() {
return actor;
}
public void setActor(String actor) {
this.actor = actor == null ? null : actor.trim();
}
public String getEditor() {
return editor;
}
public void setEditor(String editor) {
this.editor = editor == null ? null : editor.trim();
}
public Date getCreatedTime() {
return createdTime;
}
public void setCreatedTime(Date createdTime) {
this.createdTime = createdTime;
}
public Date getModifiedTime() {
return modifiedTime;
}
public void setModifiedTime(Date modifiedTime) {
this.modifiedTime = modifiedTime;
}
public Boolean getDeleted() {
return deleted;
}
public void setDeleted(Boolean deleted) {
this.deleted = deleted;
}
public String getExtendInfo() {
return extendInfo;
}
public void setExtendInfo(String extendInfo) {
this.extendInfo = extendInfo == null ? null : extendInfo.trim();
}
}
UserDtoMapper.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.lpf.dao.UserDao">
<resultMap id="BaseResultMap" type="com.lpf.dto.UserDto">
<id column="id" jdbcType="VARCHAR" property="id" />
<result column="account" jdbcType="VARCHAR" property="account" />
<result column="password" jdbcType="VARCHAR" property="password" />
<result column="name" jdbcType="VARCHAR" property="name" />
<result column="sex" jdbcType="VARCHAR" property="sex" />
<result column="identity_card_number" jdbcType="VARCHAR" property="identityCardNumber" />
<result column="mobile" jdbcType="VARCHAR" property="mobile" />
<result column="email" jdbcType="VARCHAR" property="email" />
<result column="avatar" jdbcType="VARCHAR" property="avatar" />
<result column="actor" jdbcType="VARCHAR" property="actor" />
<result column="editor" jdbcType="VARCHAR" property="editor" />
<result column="created_time" jdbcType="TIMESTAMP" property="createdTime" />
<result column="modified_time" jdbcType="TIMESTAMP" property="modifiedTime" />
<result column="deleted" jdbcType="BIT" property="deleted" />
</resultMap>
<resultMap extends="BaseResultMap" id="ResultMapWithBLOBs" type="com.lpf.dto.UserDto">
<result column="extend_info" jdbcType="LONGVARCHAR" property="extendInfo" />
</resultMap>
<sql id="Base_Column_List">
id, account, password, name, sex, identity_card_number, mobile, email, avatar, actor,
editor, created_time, modified_time, deleted
</sql>
<sql id="Blob_Column_List">
extend_info
</sql>
<select id="selectByPrimaryKey" parameterType="java.lang.String" resultMap="ResultMapWithBLOBs">
select
<include refid="Base_Column_List" />
,
<include refid="Blob_Column_List" />
from user
where id = #{id,jdbcType=VARCHAR}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.String">
delete from user
where id = #{id,jdbcType=VARCHAR}
</delete>
<insert id="insert" parameterType="com.lpf.dto.UserDto">
insert into user (id, account, password,
name, sex, identity_card_number,
mobile, email, avatar,
actor, editor, created_time,
modified_time, deleted, extend_info
)
values (#{id,jdbcType=VARCHAR}, #{account,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR},
#{name,jdbcType=VARCHAR}, #{sex,jdbcType=VARCHAR}, #{identityCardNumber,jdbcType=VARCHAR},
#{mobile,jdbcType=VARCHAR}, #{email,jdbcType=VARCHAR}, #{avatar,jdbcType=VARCHAR},
#{actor,jdbcType=VARCHAR}, #{editor,jdbcType=VARCHAR}, #{createdTime,jdbcType=TIMESTAMP},
#{modifiedTime,jdbcType=TIMESTAMP}, #{deleted,jdbcType=BIT}, #{extendInfo,jdbcType=LONGVARCHAR}
)
</insert>
<insert id="insertBatch" parameterType="java.util.List" >
insert into user (id, account, password,
name, sex, identity_card_number,
mobile, email,
avatar, actor, editor,
created_time, modified_time, deleted,
extend_info) values
<foreach collection="list" item="item" index="index" separator=",">
(#{item.id,jdbcType=VARCHAR}, #{item.account,jdbcType=VARCHAR}, #{item.password,jdbcType=VARCHAR},
#{item.name,jdbcType=VARCHAR}, #{item.sex,jdbcType=VARCHAR}, #{item.identityCardNumber,jdbcType=VARCHAR},
#{item.mobile,jdbcType=VARCHAR}, #{item.email,jdbcType=VARCHAR},
#{item.avatar,jdbcType=VARCHAR}, #{item.actor,jdbcType=VARCHAR}, #{item.editor,jdbcType=VARCHAR},
#{item.createdTime,jdbcType=TIMESTAMP}, #{item.modifiedTime,jdbcType=TIMESTAMP}, #{item.deleted,jdbcType=BIT},
#{item.extendInfo,jdbcType=LONGVARCHAR})
</foreach>
</insert>
<insert id="insertSelective" parameterType="com.lpf.dto.UserDto">
insert into user
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="id != null">
id,
</if>
<if test="account != null">
account,
</if>
<if test="password != null">
password,
</if>
<if test="name != null">
name,
</if>
<if test="sex != null">
sex,
</if>
<if test="identityCardNumber != null">
identity_card_number,
</if>
<if test="mobile != null">
mobile,
</if>
<if test="email != null">
email,
</if>
<if test="avatar != null">
avatar,
</if>
<if test="actor != null">
actor,
</if>
<if test="editor != null">
editor,
</if>
<if test="createdTime != null">
created_time,
</if>
<if test="modifiedTime != null">
modified_time,
</if>
<if test="deleted != null">
deleted,
</if>
<if test="extendInfo != null">
extend_info,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="id != null">
#{id,jdbcType=VARCHAR},
</if>
<if test="account != null">
#{account,jdbcType=VARCHAR},
</if>
<if test="password != null">
#{password,jdbcType=VARCHAR},
</if>
<if test="name != null">
#{name,jdbcType=VARCHAR},
</if>
<if test="sex != null">
#{sex,jdbcType=VARCHAR},
</if>
<if test="identityCardNumber != null">
#{identityCardNumber,jdbcType=VARCHAR},
</if>
<if test="mobile != null">
#{mobile,jdbcType=VARCHAR},
</if>
<if test="email != null">
#{email,jdbcType=VARCHAR},
</if>
<if test="avatar != null">
#{avatar,jdbcType=VARCHAR},
</if>
<if test="actor != null">
#{actor,jdbcType=VARCHAR},
</if>
<if test="editor != null">
#{editor,jdbcType=VARCHAR},
</if>
<if test="createdTime != null">
#{createdTime,jdbcType=TIMESTAMP},
</if>
<if test="modifiedTime != null">
#{modifiedTime,jdbcType=TIMESTAMP},
</if>
<if test="deleted != null">
#{deleted,jdbcType=BIT},
</if>
<if test="extendInfo != null">
#{extendInfo,jdbcType=LONGVARCHAR},
</if>
</trim>
</insert>
<update id="updateByPrimaryKeySelective" parameterType="com.lpf.dto.UserDto">
update user
<set>
<if test="account != null">
account = #{account,jdbcType=VARCHAR},
</if>
<if test="password != null">
password = #{password,jdbcType=VARCHAR},
</if>
<if test="name != null">
name = #{name,jdbcType=VARCHAR},
</if>
<if test="sex != null">
sex = #{sex,jdbcType=VARCHAR},
</if>
<if test="identityCardNumber != null">
identity_card_number = #{identityCardNumber,jdbcType=VARCHAR},
</if>
<if test="mobile != null">
mobile = #{mobile,jdbcType=VARCHAR},
</if>
<if test="email != null">
email = #{email,jdbcType=VARCHAR},
</if>
<if test="avatar != null">
avatar = #{avatar,jdbcType=VARCHAR},
</if>
<if test="actor != null">
actor = #{actor,jdbcType=VARCHAR},
</if>
<if test="editor != null">
editor = #{editor,jdbcType=VARCHAR},
</if>
<if test="createdTime != null">
created_time = #{createdTime,jdbcType=TIMESTAMP},
</if>
<if test="modifiedTime != null">
modified_time = #{modifiedTime,jdbcType=TIMESTAMP},
</if>
<if test="deleted != null">
deleted = #{deleted,jdbcType=BIT},
</if>
<if test="extendInfo != null">
extend_info = #{extendInfo,jdbcType=LONGVARCHAR},
</if>
</set>
where id = #{id,jdbcType=VARCHAR}
</update>
<update id="updateByPrimaryKeyWithBLOBs" parameterType="com.lpf.dto.UserDto">
update user
set account = #{account,jdbcType=VARCHAR},
password = #{password,jdbcType=VARCHAR},
name = #{name,jdbcType=VARCHAR},
sex = #{sex,jdbcType=VARCHAR},
identity_card_number = #{identityCardNumber,jdbcType=VARCHAR},
mobile = #{mobile,jdbcType=VARCHAR},
email = #{email,jdbcType=VARCHAR},
avatar = #{avatar,jdbcType=VARCHAR},
actor = #{actor,jdbcType=VARCHAR},
editor = #{editor,jdbcType=VARCHAR},
created_time = #{createdTime,jdbcType=TIMESTAMP},
modified_time = #{modifiedTime,jdbcType=TIMESTAMP},
deleted = #{deleted,jdbcType=BIT},
extend_info = #{extendInfo,jdbcType=LONGVARCHAR}
where id = #{id,jdbcType=VARCHAR}
</update>
<update id="updateByPrimaryKey" parameterType="com.lpf.dto.UserDto">
update user
set account = #{account,jdbcType=VARCHAR},
password = #{password,jdbcType=VARCHAR},
name = #{name,jdbcType=VARCHAR},
sex = #{sex,jdbcType=VARCHAR},
identity_card_number = #{identityCardNumber,jdbcType=VARCHAR},
mobile = #{mobile,jdbcType=VARCHAR},
email = #{email,jdbcType=VARCHAR},
avatar = #{avatar,jdbcType=VARCHAR},
actor = #{actor,jdbcType=VARCHAR},
editor = #{editor,jdbcType=VARCHAR},
created_time = #{createdTime,jdbcType=TIMESTAMP},
modified_time = #{modifiedTime,jdbcType=TIMESTAMP},
deleted = #{deleted,jdbcType=BIT}
where id = #{id,jdbcType=VARCHAR}
</update>
<select id="selectByAccount" resultMap="ResultMapWithBLOBs">
select
<include refid="Base_Column_List" />
,
<include refid="Blob_Column_List" />
from user
where account = #{account,jdbcType=VARCHAR}
and password = #{password,jdbcType=VARCHAR}
</select>
</mapper>
UserDao.java
其中添加了一个selectByAccount方法,进行登录校验
package com.lpf.dao;
import com.lpf.dto.UserDto;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface UserDao {
int deleteByPrimaryKey(String id);
int insert(UserDto userDto);
int insertBatch(List<UserDto> userDtos);
UserDto selectByAccount(@Param("account")String account,@Param("password")String password);
int insertSelective(UserDto userDto);
UserDto selectByPrimaryKey(String id);
int updateByPrimaryKeySelective(UserDto userDto);
int updateByPrimaryKeyWithBLOBs(UserDto userDto);
int updateByPrimaryKey(UserDto userDto);
}
UserService.java
package com.lpf.service;
import com.lpf.dto.UserDto;
import java.util.List;
/**
* Created by 59258 on 2017/12/28.
*/
public interface UserService {
/**
* 单笔数据插入
* @param record
* @return
*/
public int insert(UserDto record);
/**
* 数组插入
* @param userDtos
* @return
*/
public int insertBatch(List<UserDto> userDtos);
/**
* 清楚密码
* @param userDto
* @return
*/
public UserDto clearPassword(UserDto userDto);
public int insertSelective(UserDto record);
/**
* 主键查询 id
* @param id
* @return
*/
public UserDto selectByPrimaryKey(String id);
public UserDto selectByAccount(String account,String password);
/**
* 主键更新
* @param record
* @return
*/
public int updateByPrimaryKeySelective(UserDto record);
/**
*
* @param record
* @return
*/
public int updateByPrimaryKeyWithBLOBs(UserDto record);
/**
* 主键更新
* @param record
* @return
*/
public int updateByPrimaryKey(UserDto record);
/**
* 主键删除
* @param id
* @return
*/
public int deleteByPrimaryKey(String id);
}
UserServiceImpl.java
package com.lpf.service;
import javax.annotation.Resource;
import com.lpf.dao.UserDao;
import com.lpf.dto.UserDto;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
@Resource
private UserDao userDao;
public void setUserDao(com.lpf.dao.UserDao userDao) {
userDao = userDao;
}
/**
* 单笔数据插入
* @param userDto
* @return
*/
@Override
public int insert(UserDto userDto) {
int result = 0;
userDao.insert(userDto);
result=1;
return result;
}
/**
* 数组插入
* @param userDtos
* @return
*/
@Override
public int insertBatch(List<UserDto> userDtos) {
int result = 0;
userDao.insertBatch(userDtos);
result=1;
return result;
}
/**
* 清除密码
* @param userDto
* @return
*/
@Override
public UserDto clearPassword(UserDto userDto) {
userDto.setPassword("");
return userDto;
}
@Override
public int insertSelective(UserDto record) {
return 0;
}
/**
* 主键删除
* @param id
* @return
*/
@Override
public int deleteByPrimaryKey(String id) {
userDao.deleteByPrimaryKey(id);
return 0;
}
@Override
public int updateByPrimaryKey(UserDto userDto) {
userDao.updateByPrimaryKey(userDto);
return 0;
}
/**
* 主键查询 id
* @param id
* @return
*/
@Override
public UserDto selectByPrimaryKey(String id) {
return userDao.selectByPrimaryKey(id);
}
/**
* 用户名密码查询
* @param account,password
* @return
*/
public UserDto selectByAccount(String account,String password){
return userDao.selectByAccount(account, password);
}
/**
* 更新用户信息
* @param userDto
* @return
*/
@Override
public int updateByPrimaryKeySelective(UserDto userDto) {
int result = 0;
userDao.updateByPrimaryKeySelective(userDto);
result=1;
return result;
}
@Override
public int updateByPrimaryKeyWithBLOBs(UserDto record) {
return 0;
}
}
之后就可以编写Controller层了
UserController.java
package com.lpf.controller;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import com.lpf.model.ErrorCode;
import com.lpf.model.Result;
import com.lpf.dto.UserDto;
import com.lpf.service.UserPermissionService;
import com.lpf.service.UserService;
import org.apache.log4j.Logger;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;
import java.text.SimpleDateFormat;
import java.util.Date;
@Controller
@RequestMapping(value = "/user")
public class UserController {
private static Logger logger = Logger.getLogger(UserController.class);
public void setUserService(UserService userService) {
this.userService = userService;
}
@Resource(name = "userServiceImpl")
private UserService userService;
@Resource(name = "userPermissionServiceImpl")
private UserPermissionService userPermissionService;
public void setUserPermissionService(UserPermissionService userPermissionService) {
this.userPermissionService = userPermissionService;
}
/**
* 登录校验
* @param userDto
* @param session
* @return
*/
@RequestMapping(value = "/checkUser.json",method = RequestMethod.POST)
@ResponseBody
public Result checkUser(HttpServletRequest request,UserDto userDto,HttpSession session){
UserDto saUserDto=null;
try{
logger.info("用户登录:用户名:"+userDto.getAccount()+",密码:"+userDto.getPassword());
saUserDto=userService.selectByAccount(userDto.getAccount(), userDto.getPassword());
if (saUserDto!=null) {
saUserDto.setPassword(null);
saUserDto.setIdentityCardNumber(null);
session.setAttribute("userDto", saUserDto);
}else {
return Result.errorOf(ErrorCode.PASSWORD_ERROR);
}
}catch (Exception e){
e.printStackTrace();
return Result.errorOf(ErrorCode.SYSTEM_ERROR,e.getMessage());
}
return Result.successOf(saUserDto);
}
/**
* 查询个人信息使用session
* @param session
* @return
*/
@RequestMapping(value = "/selectOneUser.json",method = {RequestMethod.GET })
@ResponseBody
public Result selectOneUser(HttpSession session){
UserDto sessionUserDto=(UserDto)(session.getAttribute("userDto"));
UserDto spkUserDto = null;
try{
if (sessionUserDto!=null){
spkUserDto=userService.selectByPrimaryKey(sessionUserDto.getId());
if (spkUserDto==null) {
return Result.errorOf(ErrorCode.USERNOEXISTS_ERROR,"根据session信息无法查询到用户信息");
}
}else {
return Result.errorOf(ErrorCode.USERNOEXISTS_ERROR,"根据session信息无法查询到用户信息");
}
}catch (Exception e){
e.printStackTrace();
return Result.errorOf(ErrorCode.SYSTEM_ERROR,e.getMessage());
}
return Result.successOf(spkUserDto);
}
/**
* 更新个人信息
* @param userDto
* @param session
* @return
*/
@RequestMapping(value = "/updateOneUser.json",method = {RequestMethod.POST })
@ResponseBody
public Result updateOneUser(UserDto userDto, HttpSession session){
UserDto spkUserDto = null;
UserDto sessionUserDto=(UserDto)(session.getAttribute("userDto"));
int result=0;
Date now = new Date();
logger.info("修改个人信息:修改人:" + sessionUserDto.getAccount());
try{
if (userPermissionService.checkPermissionByType("user", sessionUserDto.getId())){
userDto.setModifiedTime(now);
userDto.setEditor(sessionUserDto.getId());
result = userService.updateByPrimaryKeySelective(userDto);
spkUserDto=userService.selectByPrimaryKey(sessionUserDto.getId());
}else {
if (sessionUserDto.getId().equals(userDto.getId())){
userDto.setModifiedTime(now);
userDto.setEditor(sessionUserDto.getId());
result = userService.updateByPrimaryKeySelective(userDto);
spkUserDto=userService.selectByPrimaryKey(userDto.getId());
}else {
return Result.errorOf(ErrorCode.PERMISSION_ERROR);
}
}
}catch (Exception e){
e.printStackTrace();
return Result.errorOf(ErrorCode.SYSTEM_ERROR,e.getMessage());
}
session.setAttribute("userDto",spkUserDto);
return Result.successOf(spkUserDto);
}
/**
* 删除用户信息
* @param userDto
* @param session
* @return
*/
@RequestMapping(value = "/deleteUser.json",method = {RequestMethod.POST })
@ResponseBody
public Result deleteUser(UserDto userDto, HttpSession session){
UserDto sessionUserDto = (UserDto)session.getAttribute("userDto");
int result=0;
logger.info("用户删除:id:" + userDto.getId() + ",操作人:" + sessionUserDto.getAccount());
try{
if (userPermissionService.checkPermissionByType("user", sessionUserDto.getId())){
result = userService.deleteByPrimaryKey(userDto.getId());
}else {
return Result.errorOf(ErrorCode.PERMISSION_ERROR,"没有权限删除用户");
}
}catch (Exception e){
e.printStackTrace();
return Result.errorOf(ErrorCode.SYSTEM_ERROR, e.getMessage());
}
return Result.successOf();
}
/**
* 注销信息
* @param session
* @return
*/
@RequestMapping(value = "/cancelUser.json",method = {RequestMethod.GET })
@ResponseBody
public Result cancelUser(HttpSession session){
session.setAttribute("userDto", null);
return Result.successOf();
}
/**
* 插入单个用户
* @param userDto
* @return
*/
@RequestMapping(value = "/insertUser.json",method = {RequestMethod.POST })
@ResponseBody
public Result insertUser(UserDto userDto, HttpSession session){
UserDto sessionUserDto = (UserDto)session.getAttribute("userDto");
int result=0;
// logger.info(userDto.getAccount()+":"+userDto.getPassword());
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date now = new Date();
logger.info("新增用户:操作员:" + sessionUserDto.getAccount() + ",新增用户:" + userDto.getAccount());
String id = userPermissionService.createId("user", sessionUserDto.getAccount());
try{
if (userPermissionService.checkPermissionByType("user", sessionUserDto.getId())){
userDto.setId(id);
userDto.setCreatedTime(now);
userDto.setModifiedTime(now);
userDto.setEditor(sessionUserDto.getId());
userDto.setActor(sessionUserDto.getId());
userDto.setDeleted(false);
result=userService.insert(userDto);
}else {
return Result.errorOf(ErrorCode.PERMISSION_ERROR);
}
}catch (Exception e){
e.printStackTrace();
return Result.errorOf(ErrorCode.SYSTEM_ERROR,e.getMessage());
}
return Result.successOf(id);
}
}
index.html
<html>
<head>
<title>WE</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" href="css/bootstrap.css">
<script src="/js/jquery-3.3.1.min.js"></script>
</head>
<body>
<form id="form1" name="form1" method="post" action="">
<br class="container-fluid" id="container">
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<div class="row">
<div class="col-xs-6 col-sm-4"></div>
<div class="col-xs-6 col-sm-4">
<div class="form-group">
<label for="account">UserCode</label>
<input type="text" name="account" class="form-control" id="account" placeholder="UserCode">
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" name="password" class="form-control" id="password" placeholder="Password">
</div>
<button type="button" onclick="sub()" class="btn btn-default">Submit</button>
</div>
<div class="col-xs-6 col-sm-4"></div>
</div>
</form>
</body>
<script language="JavaScript">
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
function sub() {
debugger;
var json1 = $('#form1').serializeObject();
$.ajax({
type: "POST",
url: "/user/checkUser.json",
dataType: "json",
data: json1,
traditional: true,
xhrFields: {
withCredentials: true //session id 保持不变
},
success: function (tt) {
debugger;
alert(tt.data.sex);
},
error: function (data) {
alert("查询失败");
}
});
}
</script>
</html>
分析
由于未贴出权限控制的代码,目前可以根据个人需求实现登录功能,用户的数据嘛,就先自己手动在数据库中导入,然后实验登录功能。
页面
弹窗
请求json
返回json
所遇到的问题
- 如何不使用@RequestBody?—-请求中不使用contentType且不使用Json.stringify方法。
- 输入域的参数如何快速的整理成json?—-formdata转json
- 返回对象为啥获取不到属性?—-function (tt) {tt.data.xx}
上一篇: SpringBoot访问静态资源
推荐阅读
-
vue+springboot前后端分离实现单点登录跨域问题解决方法
-
webuploader分片上传的实现代码(前后端分离)
-
Nginx实现前后端分离
-
详解利用 Vue.js 实现前后端分离的RBAC角色权限管理
-
SSM:Spring+SpringMVC+MyBatis(实现前后端分离)
-
前后端分离编写简单注册登录案例,并实现session存储持久化
-
Spring Boot + Vue前后端分离(三)实现登录功能
-
搭建spring-boot+vue前后端分离框架并实现登录功能
-
ASP .NET + Angular前后端分离实现简单投票系统(JWT登录用户认证)
-
Spring Boot 实现前后端分离