包结构maven
src/main/java -----存放java文件
com.niugang.
aop
------ ControllerAop.java web层aop
bean
------ UserQuery.java mybatis查询实体
controller
------ IndexController.java
dao
------ UserDao.java
entity
------ User.java
exception
------ CheckException.java 自定义异常
service
------ UserService.java
utils
------ CodeConstant.java 常量类
------ Page.java 分页对象,封装常用具体参数
------ PageResultBean.java web层返回统一的分页查询对象
------ Result.java web层返回标示性接口
------ ResultBean.java web层返回统一对象
Application.java ---springboot启动类
src/main/test -----存放测试类文件
src/main/resources-----存放配置文件
mapper mybatis xml文件
User.xml
static 静态文件
----script js文件
----themes cs文件
tempaltes
----error
error.html 覆盖springboot默认的错误文件
----view
add.html
detail.html
index.html
login.html
application-jdbc.properties
application.properties
logback-boot.xml 日志
pom.xml
4.0.0
springboot
testSpringBoot
0.0.1-SNAPSHOT
war
2_SpringBoot_FreemarkerMyBatis
http://maven.apache.org
UTF-8
org.springframework.boot
spring-boot-starter-parent
1.5.2.RELEASE
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-jdbc
org.mybatis.spring.boot
mybatis-spring-boot-starter
1.2.0
mysql
mysql-connector-java
com.alibaba
druid
1.0.25
org.apache.commons
commons-lang3
3.2
org.springframework.boot
spring-boot-starter-freemarker
org.springframework.boot
spring-boot-starter-aop
com.alibaba
fastjson
1.2.44
org.springframework.boot
spring-boot-starter-test
junit
junit
test
org.springframework.boot
spring-boot-maven-plugin
maven-compiler-plugin
1.7
org.apache.tomcat.maven
tomcat7-maven-plugin
2.2
application-jdbc.properties
# 驱动配置信息
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.url = jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=utf-8
spring.datasource.username = root
spring.datasource.password = 123456
spring.datasource.driverClassName = com.mysql.jdbc.Driver
#连接池的配置信息
## 初始化大小,最小,最大
spring.druid.initialSize=5
spring.druid.minIdle=5
spring.druid.maxActive=20
## 配置获取连接等待超时的时间
spring.druid.maxWait=60000
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
spring.druid.timeBetweenEvictionRunsMillis=60000
# 配置一个连接在池中最小生存的时间,单位是毫秒
spring.druid.minEvictableIdleTimeMillis=300000
spring.druid.validationQuery=SELECT 1 FROM DUAL
spring.druid.testWhileIdle=true
spring.druid.testOnBorrow=false
spring.druid.testOnReturn=false
spring.druid.poolPreparedStatements=true
spring.druid.maxPoolPreparedStatementPerConnectionSize=20
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
spring.druid.filters=stat,wall,log4j
# 通过connectProperties属性来打开mergeSql功能;慢SQL记录
spring.druid.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
application.properties
#web项目名称
server.contextPath=/myweb
#配置freemaker
#模板地址默认从classpath:templates下面加载
#spring.freemarker.template-loader-path=/WEB-INF/view
spring.freemarker.cache=false
spring.freemarker.charset=UTF-8
spring.freemarker.check-template-location=true
spring.freemarker.content-type=text/html
spring.freemarker.expose-request-attributes=true
spring.freemarker.expose-session-attributes=true
spring.freemarker.request-context-attribute=request
spring.freemarker.suffix=.html
#引入jdbc相关配置
spring.profiles.active=jdbc
#mybatis.config = mybatis 配置文件名称
#mybatis.mapperLocations = mapper xml 文件地址
#mybatis.typeAliasesPackage = 实体类包路径
#mybatis.typeHandlersPackage = type handlers 处理器包路径
#mybatis.check-config-location = 检查 mybatis 配置是否存在,一般命名为 mybatis-config.xml
#mybatis.executorType = 执行模式。默认是 SIMPLE
## Mybatis 配置
mybatis.typeAliasesPackage=com.niugang.entity
mybatis.mapperLocations=classpath:mapper/*.xml
#logback配置
#===================================== log =============================
logging.config=classpath:logback-boot.xml
#修改默认HTTP编码,之前是在web.xml中过滤的
spring.http.enconding.charset=UTF-8
logback-boot.xml
%d %p (%file:%line\)- %m%n
UTF-8
d:/springbootlog/springboot.log
log/springboot.%d.%i.log
30
1KB
%d %p (%file:%line\)- %m%n
UTF-8
ControllerAop.java
package com.niugang.aop;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import com.niugang.exception.CheckException;
import com.niugang.utils.CodeConstant;
import com.niugang.utils.PageResultBean;
import com.niugang.utils.Result;
import com.niugang.utils.ResultBean;
@Aspect
@Component
public class ControllerAop {
private Logger logger = LoggerFactory.getLogger(ControllerAop.class);
@Around("execution(public * com.niugang.controller..*.*(..))")
public Object aroundAdvice(ProceedingJoinPoint pjp) throws Throwable {
long startTime = System.currentTimeMillis();
Result result;
try {
Object proceed = pjp.proceed();
// 对于页面的处理
if (proceed instanceof String) {
logger.info("result request page address");
return proceed;
} else if (proceed instanceof ResultBean) { //对于查询单个对象
result = (ResultBean>) proceed;
} else {
result = (PageResultBean>) proceed; //对于分页查询
}
// 如果需要打印入参,可以从这里取出打印
// Object[] args = pjp.getArgs();
// 本次操作用时(毫秒)
long elapsedTime = System.currentTimeMillis() - startTime;
logger.info("[{}] use time: {}", pjp.getSignature(), elapsedTime);
} catch (Throwable e) {
result = handlerException(pjp, e);
}
return result;
}
@SuppressWarnings("rawtypes")
private ResultBean> handlerException(ProceedingJoinPoint pjp, Throwable e) {
//TODO pjp返回类型待判断
ResultBean> result = new ResultBean();
// 已知异常【注意:已知异常不要打印堆栈,否则会干扰日志】
// 校验出错,参数非法
if (e instanceof CheckException || e instanceof IllegalArgumentException) {
result.setResultMessage(e.getLocalizedMessage());
result.setResultCode(CodeConstant.CHECK_FAIL);
} else {
logger.error(pjp.getSignature() + " error ", e);
// TODO 未知的异常,应该格外注意,可以发送邮件通知等
result.setResultMessage("未知异常");
result.setResultCode(CodeConstant.UNKNOWN_EXCEPTION);
}
return result;
}
}
UserQuery.java
package com.niugang.bean;
import com.niugang.entity.User;
import com.niugang.utils.CodeConstant;
/**
* 封装实体类 查询对象
* @author niugang
*
*/
public class UserQuery extends User {
/**
* 页码
*/
private int pageNumber = CodeConstant.DEFAULT_PAGE_NUMBER;
/**
* 页面大小
*/
private int pageSize = CodeConstant.DEFAULT_PAGE_SIZE;
/**
* mysql分页查询 limit startRows,pageSize;
*/
private int startRows;
public int getPageNumber() {
return pageNumber;
}
public void setPageNumber(int pageNumber) {
this.pageNumber = pageNumber;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public int getStartRows() {
return (pageNumber-1)*pageSize;
}
public void setStartRows(int startRows) {
this.startRows = startRows;
}
}
IndexController.java
package com.niugang.controller;
import java.util.List;
import javax.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.niugang.bean.UserQuery;
import com.niugang.entity.User;
import com.niugang.service.UserService;
import com.niugang.utils.PageResultBean;
import com.niugang.utils.ResultBean;
/**
*
* @author niugang spring boot helloWrold
*/
public class IndexController {
@Resource
private UserService userService;
/**
* 跳转到登录页面
*
* @param map
* @return
*/
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String toLogin(ModelMap map) {
return "view/login";
}
/**
* 登录信息校验
*
* @param map
* @return
*/
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String login(ModelMap map, String name, String password) {
if (StringUtils.isNotBlank(name) && !name.equals("admin") && StringUtils.isNotBlank(password)
&& !password.equals("123456")) {
map.put("errorMessage", "用户名或密码错误");
return "login";
}
return "redirect:index";
}
@RequestMapping(value = "/index", method = RequestMethod.GET)
public String toIndex() {
return "view/index";
}
/**
* 分页查询
*
* @return
*/
@RequestMapping(value = "/index", method = RequestMethod.POST)
@ResponseBody
public PageResultBean index(UserQuery query) {
List list = userService.queryListByPage(query);
int queryCount = userService.queryCount(query);
PageResultBean pageResultBean = new PageResultBean();
pageResultBean.setData(list);
pageResultBean.setPageNumber(query.getPageNumber());
pageResultBean.setPageSize(query.getPageSize());
pageResultBean.setTotalCount(queryCount);
return pageResultBean;
}
/**
* 跳转到详情页面
*
* @return
*/
@RequestMapping(value = "/detail", method = RequestMethod.GET)
public String toDetail() {
return "view/detail";
}
/**
* 详情信息
*
* @param id
* @param map
* @return
*/
@RequestMapping(value = "/detail/{id}", method = RequestMethod.POST)
@ResponseBody
public ResultBean detail(@PathVariable(value = "id") Integer id) {
User user = userService.get(id);
ResultBean resultBean = new ResultBean();
resultBean.setData(user);
return resultBean;
}
/**
* 删除
*
* @param id
* @return
*/
@RequestMapping(value = "/delete/{id}", method = RequestMethod.POST)
public ResultBean delete(@PathVariable(value = "id") Integer id) {
userService.delete(id);
ResultBean resultBean = new ResultBean();
return resultBean;
}
/**
* 跳转到添加页面
*
* @param map
* @return
*/
@RequestMapping(value = "/save", method = RequestMethod.GET)
public String toSave(ModelMap map) {
return "view/add";
}
/**
* 保存添加信息
* 按照正常的逻辑,添加完用户信息,要将id返回
*
* @param user
* @return
*/
@RequestMapping(value = "/save", method = RequestMethod.POST)
@ResponseBody
public ResultBean save(User user) {
userService.save(user);
ResultBean resultBean = new ResultBean();
return resultBean;
}
}
UserDao.java
package com.niugang.dao;
import java.util.List;
import org.springframework.stereotype.Repository;
import com.niugang.bean.UserQuery;
import com.niugang.entity.User;
@Repository
public interface UserDao {
List queryListByPage(UserQuery user);
User get(Integer id);
void save(User user);
void delete(Integer id);
int queryCount(UserQuery user);
}
User.java
package com.niugang.entity;
public class User {
private Integer id;
private String name;
private Integer age;
private String phone;
private String password;
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
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 String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", age=" + age + ", phone=" + phone + ", password=" + password
+ "]";
}
}
CheckException.java
package com.niugang.exception;
/**
* 检测异常
* @author niugang
* 只能继承RuntimeException spring aop只能捕获RuntimeException异常
*
*/
public class CheckException extends RuntimeException {
private static final long serialVersionUID = 1L;
public CheckException() {
}
public CheckException(String message) {
super(message);
}
public CheckException(Throwable cause) {
super(cause);
}
public CheckException(String message, Throwable cause) {
super(message, cause);
}
public CheckException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
UserService.java
package com.niugang.service;
import java.util.List;
import javax.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.niugang.bean.UserQuery;
import com.niugang.dao.UserDao;
import com.niugang.entity.User;
import com.niugang.exception.CheckException;
@Service
public class UserService {
private static Logger logger = LoggerFactory.getLogger(UserService.class);
@Resource
private UserDao userDao;
public List queryListByPage(UserQuery user) {
logger.info("access queryListByPage method params is:{}", user.toString());
return userDao.queryListByPage(user);
}
@Transactional
public void save(User user) {
logger.info("access get method params is:{}", user.toString());
if (StringUtils.isBlank(user.getName())) {
throw new CheckException("用户名不能为空");
}
if (user.getAge() == null) {
throw new CheckException("年龄不能为空");
}
if (StringUtils.isBlank(user.getPhone())) {
throw new CheckException("电话不能为空");
}
user.setPassword("123456");
userDao.save(user);
//为了验证事务
//throw new CheckException("添加数据错误");
}
public User get(Integer id) {
logger.info("access get method param is:{}", id);
return userDao.get(id);
}
public void delete(Integer id) {
logger.info("access delete method param is:{}", id);
userDao.delete(id);
}
public int queryCount(UserQuery user) {
logger.info("access queryCount method param is:{}", user.toString());
return userDao.queryCount(user);
}
}
CodeConstant.java
package com.niugang.utils;
/**
* 常量表
* @author niugang
*
*/
public class CodeConstant {
/**
* 没有登录
*/
public static final int NO_LOGIN = -1;
/**
* 成功
*/
public static final int SUCCESS = 0;
/**
* 检查
*/
public static final int CHECK_FAIL = 1;
/**
* 没有权限
*/
public static final int NO_PERMISSION = 2;
/**
* 位置异常
*/
public static final int UNKNOWN_EXCEPTION = -99;
/**
* 默认页码
*/
public static final int DEFAULT_PAGE_NUMBER=1;
/**
* 默认页面大小
*/
public static final int DEFAULT_PAGE_SIZE=5;
}
Page.java
package com.niugang.utils;
/**
* 页面对象
*
* @author niugang
*
*/
public class Page {
/**
* 页码
*/
private int pageNumber = CodeConstant.DEFAULT_PAGE_NUMBER;
/**
* 页面大小
*/
private int pageSize = CodeConstant.DEFAULT_PAGE_SIZE;
/**
* 总页数
*/
private int totalPage;
/**
* 总记录数
*/
private int totalCount;
public int getPageNumber() {
return pageNumber;
}
public void setPageNumber(int pageNumber) {
this.pageNumber = pageNumber;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public int getTotalPage() {
if (totalCount % pageSize == 0) {
return totalCount / pageSize;
}
return totalCount / pageSize + 1;
}
public void setTotalPage(int totalPage) {
this.totalPage = totalPage;
}
public int getTotalCount() {
return totalCount;
}
public void setTotalCount(int totalCount) {
this.totalCount = totalCount;
}
}
PageResultBean.java
package com.niugang.utils;
import java.io.Serializable;
import java.util.List;
/**
* controller层返回带分页对象
* @author niugang
*
*/
public class PageResultBean extends Page implements Serializable,Result{
private static final long serialVersionUID = 1L;
/**
* 返回的信息
*/
private String resultMessage = "success";
/**
* 返回码
*/
private Integer resultCode=CodeConstant.SUCCESS;
/**
* 返回的数据
*/
private List data;
public PageResultBean() {
super();
}
public PageResultBean(String resultMessage, Integer resultCode, List data) {
super();
this.resultMessage = resultMessage;
this.resultCode = resultCode;
this.data = data;
}
public String getResultMessage() {
return resultMessage;
}
public void setResultMessage(String resultMessage) {
this.resultMessage = resultMessage;
}
public Integer getResultCode() {
return resultCode;
}
public void setResultCode(Integer resultCode) {
this.resultCode = resultCode;
}
public List getData() {
return data;
}
public void setData(List data) {
this.data = data;
}
}
Result.java
package com.niugang.utils;
/**
* 标示性接口
* @author niugang
*
*/
public interface Result{
}
ResultBean.java
package com.niugang.utils;
import java.io.Serializable;
/**
* controller层返回对象
* @author niugang
*
* @param
*/
public class ResultBean implements Serializable,Result{
private static final long serialVersionUID = 1L;
/**
* 放回的信息
*/
private String resultMessage = "success";
/**
* 返回码
*/
private Integer resultCode=CodeConstant.SUCCESS;
/**
* 返回的数据
*/
private T data;
public ResultBean() {
super();
}
public ResultBean(String resultMessage, Integer resultCode, T data) {
super();
this.resultMessage = resultMessage;
this.resultCode = resultCode;
this.data = data;
}
public String getResultMessage() {
return resultMessage;
}
public void setResultMessage(String resultMessage) {
this.resultMessage = resultMessage;
}
public Integer getResultCode() {
return resultCode;
}
public void setResultCode(Integer resultCode) {
this.resultCode = resultCode;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}
Application.java
package com.niugang;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.support.SpringBootServletInitializer;
//解决包tomcat冲突
//@EnableAutoConfiguration(exclude={WebMvcAutoConfiguration.class})
//组件扫描,会自动扫描springboot启动类包及其子包下的注解文件
//@ComponentScan("com.niugang.controller")
//springboot注解
//springboot1.2+之后用@SpringBootApplication替代了三个注解
@SpringBootApplication
//mapper 接口类扫描包配置
@MapperScan(value={"com.niugang.dao"})
public class Application extends SpringBootServletInitializer{
public static void main(String[] args) {
SpringApplication.run(Application.class,args);
}
}
User.xml
id, name, age,phone
and id=#{id}
and name=#{name}
and age=#{age}
and phone=#{phone}
insert into user (name,password,age,phone)
values(#{name},#{password},#{age},#{phone})
delete from user where id
=#{id}
error.html
Insert title here
未知异常
add.html
Document
index.html
Insert title here
用户名
年龄
电话
操作
detail.html
Document
详情页面
用户名:
年龄:
电话:
login.html
Insert title here
spring boot
<#if errorMessage??>
${errorMessage}
#if>
运行结果
这个错误就是从后天返回的,通过aop统一处理的
微信公众号:
JAVA程序猿成长之路
分享资源,记录程序猿成长点滴。专注于Java,Spring,SpringBoot,SpringCloud,分布式,微服务。