项目结构
com.zyj.config.JdbcConfig
package com.zyj.config;
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import javax.sql.DataSource;
public class JdbcConfig {
//使用注入的形式,读取properties文件中的属性值,等同于<property name="*******" value="${jdbc.driver}"/>
@Value("${jdbc.driver}")
private String driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String userName;
@Value("${jdbc.password}")
private String password;
//定义dataSource的bean,等同于<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
@Bean("dataSource")
public DataSource getDataSource(){
//创建对象
DruidDataSource ds = new DruidDataSource();
//手工调用set方法,等同于set属性注入<property name="driverClassName" value="******"/>
ds.setDriverClassName(driver);
ds.setUrl(url);
ds.setUsername(userName);
ds.setPassword(password);
return ds;
}
}
com.zyj.config.MyBatisConfig
package com.zyj.config;
import com.github.pagehelper.PageInterceptor;
import org.apache.ibatis.plugin.Interceptor;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import javax.sql.DataSource;
import java.util.Properties;
public class MyBatisConfig {
//定义MyBatis的核心连接工厂bean,等同于<bean class="org.mybatis.spring.SqlSessionFactoryBean">
@Bean
//参数使用自动装配的形式加载dataSource,为set注入提供数据,dataSource来源于JdbcConfig中的配置
public SqlSessionFactoryBean getSqlSessionFactoryBean(@Autowired DataSource dataSource,@Autowired Interceptor interceptor){
SqlSessionFactoryBean ssfb = new SqlSessionFactoryBean();
//等同于<property name="typeAliasesPackage" value="com.zyj.entity"/>
ssfb.setTypeAliasesPackage("com.zyj.entity");
//等同于<property name="dataSource" ref="dataSource"/>
ssfb.setDataSource(dataSource);
// //等同于<bean class="com.github.pagehelper.PageInterceptor">
ssfb.setPlugins(interceptor);
return ssfb;
}
//定义MyBatis的映射扫描,等同于<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
@Bean
public MapperScannerConfigurer getMapperScannerConfigurer(){
MapperScannerConfigurer msc = new MapperScannerConfigurer();
//等同于<property name="basePackage" value="com.zyj.dao"/>
msc.setBasePackage("com.zyj.dao");
return msc;
}
@Bean("pageInterceptor")
public Interceptor getPageInterceptor(){
Interceptor interceptor = new PageInterceptor();
Properties properties = new Properties();
properties.setProperty("helperDialect","mysql");
properties.setProperty("reasonable","true");
//等同于<property name="properties">
interceptor.setProperties(properties);
return interceptor;
}
}
com.zyj.config.ServletContainersInitConfig
package com.zyj.config;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.support.AbstractDispatcherServletInitializer;
import javax.servlet.DispatcherType;
import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import java.util.EnumSet;
public class ServletContainersInitConfig extends AbstractDispatcherServletInitializer {
//创建Servlet容器时,使用注解的方式加载SPRINGMVC配置类中的信息,并加载成WEB专用的ApplicationContext对象
//该对象放入了ServletContext范围,后期在整个WEB容器中可以随时获取调用
@Override
protected WebApplicationContext createServletApplicationContext() {
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(SpringMvcConfig.class);
return ctx;
}
//注解配置映射地址方式,服务于SpringMVC的核心控制器DispatcherServlet
@Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
@Override
//基本等同于<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
protected WebApplicationContext createRootApplicationContext() {
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(SpringConfig.class);
return ctx;
}
//乱码处理作为过滤器,在servlet容器启动时进行配置,相关内容参看Servlet零配置相关课程
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
//触发父类的onStartup
super.onStartup(servletContext);
//1.创建字符集过滤器对象
CharacterEncodingFilter cef = new CharacterEncodingFilter();
//2.设置使用的字符集
cef.setEncoding("UTF-8");
//3.添加到容器(它不是ioc容器,而是ServletContainer)
FilterRegistration.Dynamic registration = servletContext.addFilter("characterEncodingFilter", cef);
//4.添加映射
registration.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.INCLUDE), false, "/*");
}
}
com.zyj.config.SpringConfig
package com.zyj.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.*;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.sql.DataSource;
@Configuration
//等同于<context:component-scan base-package="com.itheima">
@ComponentScan(value = "com.zyj",excludeFilters =
//等同于<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
@ComponentScan.Filter(type= FilterType.ANNOTATION,classes = {Controller.class}))
//等同于<context:property-placeholder location="classpath*:jdbc.properties"/>
@PropertySource("classpath:jdbc.properties")
//等同于<tx:annotation-driven />,bean的名称默认取transactionManager
@EnableTransactionManagement
@Import({MyBatisConfig.class,JdbcConfig.class})
public class SpringConfig {
//等同于<bean id="txManager"/>
@Bean("transactionManager")
//等同于<bean class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
public DataSourceTransactionManager getTxManager(@Autowired DataSource dataSource){
DataSourceTransactionManager tm = new DataSourceTransactionManager();
//等同于<property name="dataSource" ref="dataSource"/>
tm.setDataSource(dataSource);
return tm;
}
}
com.zyj.config.SpringMvcConfig
package com.zyj.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
@Configuration
//等同于<context:component-scan base-package="com.zyj.controller"/>
@ComponentScan("com.zyj.controller")
//等同于<mvc:annotation-driven/>,还不完全相同
@EnableWebMvc
public class SpringMvcConfig {
}
com.zyj.controller.interceptor.ProjectExceptionAdivce
package com.zyj.controller.interceptor;
import com.zyj.controller.results.Result;
import com.zyj.system.exception.BusinessException;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
@Component
@ControllerAdvice
public class ProjectExceptionAdivce {
@ExceptionHandler(BusinessException.class)
@ResponseBody
//对出现异常的情况进行拦截,并将其处理成统一的页面数据结果格式
public Result doBusinessException(BusinessException e){
return new Result(e.getCode(),e.getMessage());
}
}
com.zyj.controller.results.Code
package com.zyj.controller.results;
public class Code {
// 操作结果编码
public static final Integer SAVE_OK = 20011;
public static final Integer UPDATE_OK = 20021;
public static final Integer DELETE_OK = 20031;
public static final Integer GET_OK = 20041;
public static final Integer SAVE_ERROR = 20010;
public static final Integer UPDATE_ERROR = 20020;
public static final Integer DELETE_ERROR = 20030;
public static final Integer GET_ERROR = 20040;
// 系统错误编码
// 操作权限编码
// 校验结果编码
}
com.zyj.controller.results.Result
package com.zyj.controller.results;
public class Result {
// 操作结果编码
private Integer code;
// 操作数据结果
private Object data;
// 消息
private String message;
public Result(Integer code) {
this.code = code;
}
public Result(Integer code, Object data) {
this.code = code;
this.data = data;
}
@Override
public String toString() {
return "Result{" +
"code=" + code +
", data=" + data +
", message='" + message + '\'' +
'}';
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
com.zyj.controller.UserController
package com.zyj.controller;
import com.github.pagehelper.PageInfo;
import com.zyj.controller.results.Code;
import com.zyj.controller.results.Result;
import com.zyj.entity.Student;
import com.zyj.entity.User;
import com.zyj.service.UserService;
import com.zyj.system.exception.BusinessException;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
@RestController
@RequestMapping("/user")
public class UserController {
@Resource
private UserService userService;
@PostMapping
public Result save(User user) {
boolean flag = userService.save(user);
return new Result(flag ? Code.SAVE_OK : Code.SAVE_ERROR);
}
@PutMapping
public Result update(User user) {
boolean flag = userService.update(user);
return new Result(flag ? Code.UPDATE_OK : Code.UPDATE_ERROR);
}
@DeleteMapping("/{uuid}")
public Result delete(@PathVariable Integer uuid) {
boolean flag = userService.delete(uuid);
return new Result(flag ? Code.DELETE_OK : Code.DELETE_ERROR);
}
@GetMapping("/{uuid}")
public Result get(@PathVariable Integer uuid) {
User user = userService.get(uuid);
//模拟出现异常,使用条件控制,便于测试结果
if (uuid == 10) throw new BusinessException("查询出错啦,请重试!", Code.GET_ERROR);
return new Result(null != user ? Code.GET_OK : Code.GET_ERROR, user);
}
@GetMapping("/{page}/{size}")
public Result getAll(@PathVariable Integer page, @PathVariable Integer size) {
PageInfo<User> all = userService.getAll(page, size);
return new Result(null != all ? Code.GET_OK : Code.GET_ERROR, all);
}
/*查找全部用户详细信息,分页显示*/
@GetMapping("/{page}/{size}/status")
public Result getAllStatus(@PathVariable Integer page, @PathVariable Integer size) {
PageInfo<Student> all = userService.getAllStatus(page, size);
return new Result(null != all ? Code.GET_OK : Code.GET_ERROR, all);
}
@PostMapping("/login")
public Result login(String userName, String password) {
User user = userService.login(userName, password);
return new Result(null != user ? Code.GET_OK : Code.GET_ERROR, user);
}
}
com.zyj.dao.UserDao
package com.zyj.dao;
import com.zyj.entity.Student;
import com.zyj.entity.User;
import org.apache.ibatis.annotations.*;
import java.util.List;
public interface UserDao {
/**
* 添加用户
*
* @param user
* @return
*/
@Insert("insert into user(userName,password,realName,gender,birthday)values(#{userName},#{password},#{realName},#{gender},#{birthday})")
public boolean save(User user);
/**
* 修改用户
*
* @param user
* @return
*/
@Update("update user set userName=#{userName},password=#{password},realName=#{realName},gender=#{gender},birthday=#{birthday} where uuid=#{uuid}")
public boolean update(User user);
/**
* 删除用户
*
* @param uuid
* @return
*/
@Delete("delete from user where uuid = #{uuid}")
public boolean delete(Integer uuid);
/**
* 查询单个用户信息
*
* @param uuid
* @return
*/
@Select("select * from user where uuid = #{uuid}")
public User get(Integer uuid);
/**
* 查询全部用户信息
*
* @return
*/
@Select("select * from user")
public List<User> getAll();
/**
* 查询全部用户详细信息
*
* @return
*/
@Select("select * from student")
@Results({
@Result(column = "uuid", property = "uuid"),
@Result(column = "name", property = "name"),
@Result(column = "age", property = "age"),
@Result(
property = "users", //被包含对象的变量名
javaType = User.class, //被包含对象实际的类型
column = "uuid", //根据查询出的card表中的pid字段来查询person表
/*
one、@one 一对一固定写法
select属性:指定调用那个接口中的哪个方法
* */
one = @One(select = "com.zyj.dao.UserDao.getAllStatusByUser")
)
})
public List<Student> getAllStatus();
@Select("select * from user where uuid = #{uuid}")
public User getAllStatusByUser(Integer uuid);
/**
* 根据用户名密码查询个人信息
*
* @param userName 用户名
* @param password 密码信息
* @return
*/
@Select("select * from user where userName=#{userName} and password=#{password}")
//注意:数据层操作不要和业务层操作的名称混淆,通常数据层仅反映与数据库间的信息交换,不体现业务逻辑
public User getByUserNameAndPassword(@Param("userName") String userName, @Param("password") String password);
}
com.zyj.entity.Student
package com.zyj.entity;
public class Student {
private Integer uuid;
private String name;
private Integer age;
private User users;
public Student() {
}
public Student(Integer uuid, String name, Integer age, User users) {
this.uuid = uuid;
this.name = name;
this.age = age;
this.users = users;
}
public Integer getUuid() {
return uuid;
}
public void setUuid(Integer uuid) {
this.uuid = uuid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public User getUsers() {
return users;
}
public void setUsers(User users) {
this.users = users;
}
@Override
public String toString() {
return "Student{" +
"uuid=" + uuid +
", name='" + name + '\'' +
", age=" + age +
", users=" + users +
'}';
}
}
com.zyj.entity.User
package com.zyj.entity;
import java.io.Serializable;
import java.util.Date;
public class User implements Serializable {
private String userName;
private String password;
private String realName;
private Integer gender;
private Date birthday;
public User() {
}
public User(String userName, String password, String realName, Integer gender, Date birthday) {
this.userName = userName;
this.password = password;
this.realName = realName;
this.gender = gender;
this.birthday = birthday;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getRealName() {
return realName;
}
public void setRealName(String realName) {
this.realName = realName;
}
public Integer getGender() {
return gender;
}
public void setGender(Integer gender) {
this.gender = gender;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
@Override
public String toString() {
return "User{" +
"userName='" + userName + '\'' +
", password='" + password + '\'' +
", realName='" + realName + '\'' +
", gender=" + gender +
", birthday=" + birthday +
'}';
}
}
com.zyj.service.impl.UserServiceImpl
package com.zyj.service.impl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zyj.dao.UserDao;
import com.zyj.entity.Student;
import com.zyj.entity.User;
import com.zyj.service.UserService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
@Resource
private UserDao userDao;
@Override
public boolean save(User user) {
return userDao.save(user);
}
@Override
public boolean update(User user) {
return userDao.update(user);
}
@Override
public boolean delete(Integer uuid) {
return userDao.delete(uuid);
}
@Override
public User get(Integer uuid) {
return userDao.get(uuid);
}
@Override
public PageInfo<User> getAll(int page,int size) {
PageHelper.startPage(page,size);
List<User> all = userDao.getAll();
return new PageInfo<User>(all);
}
@Override
public PageInfo<Student> getAllStatus(int page, int size) {
PageHelper.startPage(page,size);
List<Student> all = userDao.getAllStatus();
return new PageInfo<Student>(all);
}
@Override
public User login(String userName, String password) {
return userDao.getByUserNameAndPassword(userName,password);
}
}
com.zyj.service.UserService
package com.zyj.service;
import com.github.pagehelper.PageInfo;
import com.zyj.entity.Student;
import com.zyj.entity.User;
import org.springframework.transaction.annotation.Transactional;
@Transactional(readOnly = true)
public interface UserService {
/**
* 添加用户
*
* @param user
* @return
*/
@Transactional(readOnly = false)
public boolean save(User user);
/**
* 修改用户
*
* @param user
* @return
*/
@Transactional(readOnly = false)
public boolean update(User user);
/**
* 删除用户
*
* @param uuid
* @return
*/
@Transactional(readOnly = false)
public boolean delete(Integer uuid);
/**
* 查询单个用户信息
*
* @param uuid
* @return
*/
public User get(Integer uuid);
/**
* 查询全部用户信息
*
* @return
*/
public PageInfo<User> getAll(int page, int size);
/**
* 查询全部用户详细信息
*
* @return
*/
public PageInfo<Student> getAllStatus(int page, int size);
/**
* 根据用户名密码进行登录
*
* @param userName
* @param password
* @return
*/
public User login(String userName, String password);
}
com.zyj.system.exception.BusinessException
package com.zyj.system.exception;
public class BusinessException extends RuntimeException {
//自定义异常中封装对应的错误编码,用于异常处理时获取对应的操作编码
private Integer code;
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public BusinessException(Integer code) {
this.code = code;
}
public BusinessException(String message, Integer code) {
super(message);
this.code = code;
}
public BusinessException(String message, Throwable cause,Integer code) {
super(message, cause);
this.code = code;
}
public BusinessException(Throwable cause,Integer code) {
super(cause);
this.code = code;
}
public BusinessException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace,Integer code) {
super(message, cause, enableSuppression, writableStackTrace);
this.code = code;
}
}
com.zyj.system.exception.SystemException
package com.zyj.system.exception;
public class SystemException extends RuntimeException {
public SystemException() {
}
public SystemException(String message) {
super(message);
}
public SystemException(String message, Throwable cause) {
super(message, cause);
}
public SystemException(Throwable cause) {
super(cause);
}
public SystemException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
src/main/resources/jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://192.168.1.188:3306/ssm_db
jdbc.username=root
jdbc.password=root
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.zyj</groupId>
<artifactId>unit_test</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>unit_test 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.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<!--spring环境-->
<!--spring环境-->
<!--spring环境-->
<!--<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>-->
<!--mybatis环境-->
<!--mybatis环境-->
<!--mybatis环境-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.3</version>
</dependency>
<!--mysql环境-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!--spring整合jdbc-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<!--spring整合mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.3</version>
</dependency>
<!--druid连接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.16</version>
</dependency>
<!--分页插件坐标-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.1.2</version>
</dependency>
<!--springmvc环境-->
<!--springmvc环境-->
<!--springmvc环境-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<!--jackson相关坐标3个-->
<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-core</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.0</version>
</dependency>-->
<!--servlet环境-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!--其他组件-->
<!--其他组件-->
<!--其他组件-->
<!--junit单元测试-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!--spring整合junit-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<!-- hadoop连接hdfs依赖包 -->
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-client</artifactId>
<version>2.6.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<!--设置插件-->
<plugins>
<!--具体的插件配置-->
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<hostName>localhost</hostName>
<port>80</port>
<path>/</path>
<uriEncoding>UTF-8</uriEncoding>
</configuration>
</plugin>
</plugins>
</build>
</project>