15年进入大学,虽然不敢说什么一眼万年,但是我转眼也有三年多了。目前正在实习中。毕设题目已经选好。选了我的数据库老师(本来是不打算涉及到后台部分的,只是打算前端显示的炫酷一些,因为想法中都是使用网上的公开 API 实现)
老师和我说到时候会问数据库的问题,所以一定要有工作量,再加上我一直有些后悔大学上课没有好好学习后台开发,当然学校的知识你们都懂的。所以正好逼自己一下,比较彻底的了解后台的基本开发和入门。
这里我要很感谢一个为了爱从宁波跑到广西的老哥,他在我学习中给予了非常大的帮助,每次我问他问题都会耐心的解答。
话不多说,先介绍一下我的环境:
- window 10
- Idea 2018
- tomcat 7,8 都有使用(我装了两个)
- AndroidStudio 3.2.1
- gradle 4.6
- maven 负责 jar 包管理
后台使用框架技术:SSM,App 端请求:RxJava + Retrofit 实现简单网络的访问。
一:后台的搭建
1)新建 maven 项目
这里大家可以有两个选择,一个是新建 maven 空项目,一个是新建 maven web 项目都可以。不过我好像看过一篇文章说新建 maven 空项目的好处,不过不管了,这里我使用的是 新建 maven web 项目。
字写的比较丑,,,见谅,接下来点击 next
这里的名字随便写,没什么影响,点击 next
因为我单独装过 maven 3.6 版本,这样会便于管理,因为路径和配置什么的方便查找,如果你是用第二个也没啥关系,那是系统自带的,其实对于一般使用来说没什么区别。
点击 next
这里点击 auto-import 即可。其他的一些基础系统会自动帮你配置,你只需要等待就 ok 了。
当看到出现这几个打字,尤其是 finish 之后就说明基本项目新建好了。接下来就是配置 SSM 了。
下面我会列出我的配置信息
这是项目刚新建好的目录结构
这是项目搭建完成后的目录,下面是配置信息。
大家新建项目的时候可以按照这个来操作
不同的资源文件夹有不同的颜色,大家对号入座就行
- 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.jiwenjie</groupId>
<artifactId>Gratuation_example</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>Gratuation_example Maven Webapp</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
</dependencies>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!--补全项目依赖-->
<!--1.日志 java日志有:slf4j, log4j, logback, common-logging
slf4j:是规范/接口
日志实现:log4j,logback,common-logging
使用:slf4j + logback-->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.12</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>1.1.1</version>
</dependency>
<!--1.数据库相关依赖-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.36</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<!-- 框架:MyBatis 依赖-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.1</version>
</dependency>
<!--mybatis 自身实现的 spring 整合依赖-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.0</version>
</dependency>
<!--3.Servlet web 相关依赖-->
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!--<dependency>-->
<!--<groupId>com.fasterxml.jackson.core</groupId>-->
<!--<artifactId>jackson-databind</artifactId>-->
<!--<version>2.5.4</version>-->
<!--</dependency>-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.8.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.1</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<!--4:spring 依赖-->
<!--1)spring 核心依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.1.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.1.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.1.7.RELEASE</version>
</dependency>
<!--2) dao 层依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.1.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>4.1.7.RELEASE</version>
</dependency>
<!--3)spring web 相关依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.1.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.1.7.RELEASE</version>
</dependency>
<!--4)spring test 相关依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.1.7.RELEASE</version>
</dependency>
<!-- 文件上传 -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.2.1</version>
</dependency>
</dependencies>
<build>
<finalName>Gratuation_example</finalName>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.2</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
这里是 maven 包的自动导入,大家把这些导入后等待就 ok 了。
- jdbc.properties 文件
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/douban_movie?useUnicode=true&characterEncoding=utf-8&useSSL=false
jdbc.username=root
jdbc.password=root
jdbc.initialPoolSize=10
jdbc.maxPoolSize=30
jdbc.minPoolSize=10
jdbc.checkoutTimeout=1000
jdbc.acquireRetryAttempts=2
jdbc.idleConnectionTestPeriod=60
jdbc.maxIdleTime=240
jdbc.acquireIncrement=5
jdbc.maxConnectionAge=3000
jdbc.maxStatements=0
- log4j.porperties 文件
log4j.logger.org.mybatis=TRACE
log4j.logger.com.suny.dao=TRACE
log4j.rootLogger=WARN, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n
log4j.appender.logfile=org.apache.log4j.FileAppender
log4j.appender.logfile.File=target/spring.log
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - %m%n
- mybatis-config.xml 文件
<?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>
<!--配置全局属性-->
<settings>
<!-- 使用JDBC 获取数据库自增 -->
<setting name="useGeneratedKeys" value="true"/>
<!-- 使用列别名替换列名 默认是true-->
<setting name="useColumnLabel" value="true"/>
<!--开启驼峰命名转换-->
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
</configuration>
- logback.xml 文件
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<!-- encoders are assigned the type
ch.qos.logback.classic.encoder.PatternLayoutEncoder by default -->
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<root level="debug">
<appender-ref ref="STDOUT"/>
</root>
</configuration>
- spring-dao.xml 文件
<?xml version="1.0" encoding="UTF-8"?>
<!--suppress ALL -->
<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">
<!-- 启动 SpringMVC 的注解功能,它会自动注册 HandlerMapping、HandlerAdapter、ExceptionResolver -->
<mvc:annotation-driven/>
<mvc:default-servlet-handler/>
<context:component-scan base-package="com.jiwenjie.dao"/>
<!-- 配置整合mybatis-->
<!-- 配置数据库-->
<context:property-placeholder ignore-unresolvable="true" location="classpath:jdbc.properties"/>
<!--2.数据库连接池-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<!--配置连接池属性-->
<property name="driverClass" value="${jdbc.driver}"/>
<!-- 基本属性 url、user、password -->
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<!-- c3p0私有属性 -->
<property name="maxPoolSize" value="${jdbc.maxPoolSize}"/>
<property name="minPoolSize" value="${jdbc.minPoolSize}"/>
<property name="initialPoolSize" value="${jdbc.initialPoolSize}"/>
<!-- 关闭连接后不自动 commit -->
<property name="autoCommitOnClose" value="false"/>
<property name="breakAfterAcquireFailure" value="false"/>
<!-- 获取连接超时时间 -->
<property name="checkoutTimeout" value="${jdbc.checkoutTimeout}"/>
<!-- 当获取连接失败重试次数 -->
<property name="acquireRetryAttempts" value="${jdbc.acquireRetryAttempts}"/>
<property name="acquireIncrement" value="${jdbc.acquireIncrement}"/>
<property name="maxConnectionAge" value="${jdbc.maxConnectionAge}"/>
<property name="maxIdleTime" value="${jdbc.maxIdleTime}"/>
<property name="idleConnectionTestPeriod" value="${jdbc.idleConnectionTestPeriod}"/>
<property name="maxStatements" value="${jdbc.maxStatements}"/>
</bean>
<!-- 3.配置 SqlSessionFactory 对象 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--注入数据库连接池-->
<property name="dataSource" ref="dataSource"/>
<!--配置 mybatis 全局配置文件: mybatis-config.xml -->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<!--com.kuky.entity 包,使用别名,多个用;隔开-->
<property name="typeAliasesPackage" value="com.jiwenjie.entity"/>
<!-- 扫描 sql 配置文件:mapper 需要的 xml 文件 -->
<property name="mapperLocations" value="classpath:mapper/*.xml"/>
</bean>
<!-- 4.配置扫描 Dao 接口包,动态实现 Dao 接口,注入到 Spring 容器 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 注入 SqlSessionFactory -->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!-- 给出需要扫描的 Dao 接口 -->
<property name="basePackage" value="com.jiwenjie.dao"/>
</bean>
<mvc:interceptors>
<!-- 国际化操作拦截器 如果采用基于(请求/Session/Cookie)则必需配置-->
<bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"/>
<!-- 登录权限拦截器 -->
<bean class="com.jiwenjie.common.interceptor.AuthorizationInterceptor"/>
<!-- 管理员权限拦截器 -->
<!--<bean class="com.kuky.common.interceptor.AdminInterceptor"/>-->
</mvc:interceptors>
</beans>
- spring-service.xml 文件
<?xml version="1.0" encoding="UTF-8"?>
<!--suppress ALL -->
<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: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/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<!--扫描 service 包下所有使用注解的类型-->
<context:component-scan base-package="com.jiwenjie.service"/>
<!--配置事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--注入数据库连接池-->
<property name="dataSource" ref="dataSource"/>
</bean>
<bean id="date" class="java.util.Date"/>
<!--配置基于注解的声明式事务,默认使用注解来管理事务行为-->
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
- spring-web.xml 文件
<?xml version="1.0" encoding="UTF-8"?>
<!--suppress ALL -->
<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">
<!--配置spring mvc-->
<!--1,开启 springmvc 注解模式
a.自动注册 DefaultAnnotationHandlerMapping,AnnotationMethodHandlerAdapter
b.默认提供一系列的功能:数据绑定,数字和日期的 format@NumberFormat,@DateTimeFormat
c:xml,json 的默认读写支持-->
<mvc:annotation-driven/>
<!--2.静态资源默认 servlet 配置-->
<!--
1).加入对静态资源处理:js,gif,png
2).允许使用 "/" 做整体映射
-->
<mvc:default-servlet-handler/>
<!--3:配置JSP 显示ViewResolver-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/pages/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!-- 上传文件 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8"/>
</bean>
<!--4:扫描 web 相关的 bean-->
<context:component-scan base-package="com.jiwenjie.controller"/>
</beans>
- web.xml 文件
<!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 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_3_1.xsd"
version="3.1"
metadata-complete="true">
<display-name>Archetype Created Web Application</display-name>
<!-- 配置欢迎页 -->
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<!-- 为 Servlet 命名 -->
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<!-- DispatcherServlet主要负责流程的控制 -->
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- contextConfigLocation配置 mvc-dispatcher 加载的配置文件(配置处理器映射器、适配器等等)
若不配置,默认加载WEB-INF/servlet名称-servlet(mvc-dispatcher-servlet.xml) -->
<!-- 在 servlet 中能够调用 getServletConfig().getInitParameter("param1") 获得参数名对应的值 -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/spring-*.xml</param-value>
</init-param>
<!-- 表示启动容器时初始化该Servlet -->
<load-on-startup>1</load-on-startup>
</servlet>
<!-- 为 Servlet 定制 URL -->
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<!-- 表示哪些请求交给 Spring Web MVC 处理, “/” 是用来定义默认 servlet 映射的。也可以如 “*.html” 表示拦截所有以 html 为扩展名的请求。 -->
<!--
第一种:*.action, 访问以.action结尾,由 DispatcherServlet 进行解析
第二种:/, 所有访问的地址由 DispatcherServlet 进行解析,对静态文件的解析需要配置不让 DispatcherServlet 进行解析,
使用此种方式和实现 RESTful 风格的 url
第三种:/*, 这样配置不对,使用这种配置,最终要转发到一个 jsp 页面时,仍然会由 DispatcherServlet 解析 jsp 地址,
不能根据 jsp 页面找到 handler 会报错
-->
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
到此基本配置结束,接下来就是代码的部分
- User 实体类
package com.example.entity;
import com.fasterxml.jackson.annotation.JsonInclude;
/**
* author: Jiwenjie
* email: Jiwenjie97@gmail.com
* time: 2018-12-22
* desc:
*/
@JsonInclude(JsonInclude.Include.NON_NULL) // 去除返回接口值为 null 的字段
public class User {
private Integer id;
private String username;
private String phone;
private int isAdmin;
private String avatar;
private String password;
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", phone='" + phone + '\'' +
", isAdmin=" + isAdmin +
", avatar='" + avatar + '\'' +
", 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 getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getAvatar() {
return avatar;
}
public void setAvatar(String avatar) {
this.avatar = avatar;
}
public int getIsAdmin() {
return isAdmin;
}
public void setIsAdmin(int isAdmin) {
this.isAdmin = isAdmin;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
- UserDao 接口
package com.example.dao;
import com.example.entity.User;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
/**
* author: Jiwenjie
* email: Jiwenjie97@gmail.com
* time: 2018-12-22
* desc:
*/
@Repository
public interface UserDao {
void registerUser(@Param("username") String username, @Param("password") String password, @Param("phone") String phone);
User userLogin(@Param("username") String username, @Param("password") String password);
User findUserByName(@Param("username") String username);
User findUserByPhone(@Param("phone") String phone);
}
- UserDao.xml 文件,名字要与 UserDao 完全一致才可以匹配对应
<?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.example.dao.UserDao">
<!-- 配置数据库字段名和实体类对应 -->
<resultMap id="user" type="com.example.entity.User">
<result property="isAdmin" column="is_admin"/>
</resultMap>
<insert id="registerUser" parameterType="java.lang.String">
INSERT INTO users (username, password, phone) VALUES (#{username}, #{password}, #{phone})
</insert>
<select id="userLogin" parameterType="java.lang.String" resultType="user">
SELECT id, username, phone, avatar, is_admin FROM users WHERE username = #{username} AND password = #{password}
</select>
<select id="findUserByName" parameterType="java.lang.String" resultType="user">
SELECT id, username, phone, avatar, is_admin FROM users WHERE username=#{username}
</select>
<select id="findUserByPhone" parameterType="java.lang.String" resultType="user">
SELECT id, username, phone, avatar, is_admin FROM users WHERE phone = #{phone}
</select>
</mapper>
- UserService 接口
package com.example.service;
import com.example.entity.User;
/**
* author: Jiwenjie
* email: Jiwenjie97@gmail.com
* time: 2018-12-22
* desc:
*/
public interface UserService {
void registerUser(String username, String password, String phone);
User userLogin(String username, String password);
User findUserByName(String username);
User findUserByPhone(String phone);
}
- service 的实现类
package com.example.service.impl;
import com.example.dao.UserDao;
import com.example.entity.User;
import com.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* author: Jiwenjie
* email: Jiwenjie97@gmail.com
* time: 2018-12-22
* desc:
*/
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
@Override
public void registerUser(String username, String password, String phone) {
userDao.registerUser(username, password, phone);
}
@Override
public User userLogin(String username, String password) {
return userDao.userLogin(username, password);
}
@Override
public User findUserByName(String username) {
return userDao.findUserByName(username);
}
@Override
public User findUserByPhone(String phone) {
return userDao.findUserByPhone(phone);
}
}
- UserController 实现类
package com.example.controller;
import com.example.common.Constant;
import com.example.entity.User;
import com.example.service.UserService;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
/**
* author: Jiwenjie
* email: Jiwenjie97@gmail.com
* time: 2018-12-22
* desc:
*/
@Controller
@RequestMapping(value = "/user")
public class UserController {
@Autowired
private UserService userService;
@Autowired
private HttpSession session;
/**
* 注册用户接口
* @param username 用户名
* @param password 密码
* @param phone 手机号
* @return 注册结果
*/
@RequestMapping(value = "/register", method = RequestMethod.POST)
@ResponseBody
public Map<String, Object> registerUser(@RequestParam String username, @RequestParam String password, @RequestParam String phone) {
Map<String, Object> map = new HashMap<>();
System.out.println("进入注册响应");
System.out.println("用户名:" + username);
System.out.println("密码:" + password);
System.out.println("手机号:" + phone);
/**
* 是否存在相同用户名用户
*/
User nUser = userService.findUserByName(username);
User pUser = userService.findUserByPhone(phone);
if (nUser != null) {
map.put("message", "the username has been register");
map.put("code", HttpStatus.BAD_REQUEST.value());
} else if (pUser != null) {
map.put("message", "the phone number has been register");
map.put("code", HttpStatus.BAD_REQUEST.value());
} else {
try {
userService.registerUser(username, password, phone);
map.put("message", "succeed");
map.put("code", HttpStatus.OK.value());
} catch (Exception e) {
map.put("message", "failed");
map.put("code", HttpStatus.BAD_REQUEST.value());
e.printStackTrace();
}
}
return map;
}
/**
* 用户登录接口
*
* @param username 用户名
* @param password 密码
* @return 登录结果
*/
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
@RequestMapping(value = "/login", method = RequestMethod.POST)
@ResponseBody
public Map<String, Object> userLogin(@RequestParam String username, @RequestParam String password) {
Map<String, Object> map = new HashMap<>();
System.out.println("进入登陆接口");
System.out.println("用户名:" + username);
System.out.println("密码:" + password);
User user = userService.userLogin(username, password);
if (user != null) {
session.setAttribute(Constant.SESSION_USER, user);
map.put("user", user);
map.put("code", HttpStatus.OK.value());
map.put("message", "succeed");
System.out.println("登陆成功");
} else {
map.put("message", "not register");
map.put("code", HttpStatus.NOT_FOUND.value());
System.out.println("登陆失败");
}
return map;
}
}
- AuthorizationInterceptor 权限校验
package com.jiwenjie.common.interceptor;
import com.jiwenjie.common.Constant;
import com.jiwenjie.common.auth.AuthPassport;
import com.jiwenjie.entity.User;
import org.springframework.http.HttpStatus;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
/**
* author: Jiwenjie
* email: Jiwenjie97@gmail.com
* time: 2018-12-13
* desc:
*/
public class AuthorizationInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler) throws Exception {
if (handler.getClass().isAssignableFrom(HandlerMethod.class)) {
AuthPassport authPassport = ((HandlerMethod) handler).getMethodAnnotation(AuthPassport.class);
if (authPassport == null) {
System.out.println(httpServletRequest.getRequestURL().toString());
return true;
} else {
User user = (User) httpServletRequest.getSession().getAttribute(Constant.SESSION_USER);
if (user == null) {
httpServletResponse.setStatus(HttpStatus.FORBIDDEN.value());
PrintWriter pw = httpServletResponse.getWriter();
pw.write("{\"code\" : 403, \"message\" : \"Need Login\"}");
pw.flush();
pw.close();
return false;
} else
return true;
}
}
return false;
}
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
System.out.println("AuthorizationInterceptor: postHandle -->");
}
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
System.out.println("AuthorizationInterceptor: afterCompletion -->");
}
}
自定义接口
package com.jiwenjie.common.auth;
import java.lang.annotation.*;
/**
* author: Jiwenjie
* email: Jiwenjie97@gmail.com
* time: 2018-12-13
* desc:
*/
@Documented
@Inherited
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface AdminPassport {
}
package com.jiwenjie.common.auth;
import java.lang.annotation.*;
/**
* author: Jiwenjie
* email: Jiwenjie97@gmail.com
* time: 2018-12-13
* desc:
*/
@Documented
@Inherited
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface AuthPassport {
}
public class Constant {
public static final String SESSION_USER = "session_user";
}
所有的代码文件到此基本完成。接下来来看下配置 tomcat
好,接下来就是运行就可以证明后台搭建成功了。
这是点击按钮后运行成功的结果,点击提交我们再看
是不是发现一个很神奇的事,返回的是 json 数据而不是网页,这里大家可以去看看源码,其实 json 的底层就是 hashMap。再次说明了基础知识的重要。
好了后台的搭建就到这里,我会在写一篇文章来继续描述。
源码会在整理有编辑放出。
这里做了修改,进行了简化处理,只有登陆和注册,确保我们的主要目的就是打通前后台
github 代码
https://github.com/jiwenjie/RearDemo