SSM整合: http://t.csdnimg.cn/0lgfl
响应格式统一
我们要保证一个项目中所有接口返回的数据格式的统一。这样无论是前端还是移动端开发获取到我们的数据后都能更方便的进行统一处理。
所以我们定义以下结果封装类
/**
* 在将Java对象转换为JSON格式时,只有非null属性才会被包含在生成的JSON对象中。
* 这对于减少JSON数据大小,以及避免由于不必要的null值导致的问题非常有用。
*
* @JsonInclude(JsonInclude.Include.NON_NULL)
*/
@JsonInclude(JsonInclude.Include.NON_NULL)
public class ResponseResult<T> {
/**
* 状态码
*/
private Integer code;
/**
* 提示信息,如果有错误时,前端可以获取该字段进行提示
*/
private String msg;
/**
* 查询到的结果数据,
*/
private T data;
public ResponseResult(Integer code, String msg) {
this.code = code;
this.msg = msg;
}
public ResponseResult(Integer code, T data) {
this.code = code;
this.data = data;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public ResponseResult(Integer code, String msg, T data) {
this.code = code;
this.msg = msg;
this.data = data;
}
}
修改接口
@RestController
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/user/{id}")
public ResponseResult findById(@PathVariable("id") Integer id) {
User user = userService.findById(id);
if (user == null) {
//说明没有对应的用户
return new ResponseResult(500, "没有该用户");
}
return new ResponseResult(200, "操作成功", user);
}
}
查询所有用户
UserMapper接口
List<User> findAll();
UserMapper.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.yu.dao.UserMapper">
<select id="findAll" resultType="com.yu.pojo.User">
select * from user
</select>
</mapper>
UserService接口
List<User> findAll();
UserServiceImpl实现类
public List<User> findAll() {
return userMapper.findAll();
}
controller
@GetMapping("/user")
public ResponseResult findAll(){
List<User> list = userService.findAll();
return new ResponseResult(200,"操作成功",list);
}
分页查询用户
分页查询的结果除了要包含查到的用户数据外还要有当前页数,每页条数,总记录数这些分页数据。
分页数据封装类
public class PageResult<T> {
private Integer currentPage;
private Integer pageSize;
private Integer total;
private List<T> data;
public PageResult(Integer currentPage, Integer pageSize, Integer total, List<T> data) {
this.currentPage = currentPage;
this.pageSize = pageSize;
this.total = total;
this.data = data;
}
public Integer getCurrentPage() {
return currentPage;
}
public void setCurrentPage(Integer currentPage) {
this.currentPage = currentPage;
}
public Integer getPageSize() {
return pageSize;
}
public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
}
public Integer getTotal() {
return total;
}
public void setTotal(Integer total) {
this.total = total;
}
public List<T> getData() {
return data;
}
public void setData(List<T> data) {
this.data = data;
}
}
UserService接口
PageResult findByPage(Integer pageSize, Integer pageNum);
UserServiceImpl实现类
public PageResult findByPage(Integer pageSize, Integer pageNum) {
PageHelper.startPage(pageNum,pageSize);
List<User> list = userMapper.findAll();
PageInfo pageInfo = new PageInfo(list);
PageResult pageResult = new PageResult(pageInfo.getPageNum(),pageInfo.getPageSize(), (int) pageInfo.getTotal(),list);
return pageResult;
}
Controller
@GetMapping("/user/{pageSize}/{pageNum}")
public ResponseResult findByPage(@PathVariable("pageSize") Integer pageSize,@PathVariable("pageNum") Integer pageNum){
PageResult pageResult = userService.findByPage(pageSize,pageNum);
return new ResponseResult(200,"操作成功",pageResult);
}
插入用户
UserMapper接口
void insertUser(User user);
mapper.xml映射文件
<insert id="insertUser">
insert into user values(null,#{username},#{age},#{address})
</insert>
UserService接口
void insertUser(User user);
UserServiceImpl实现类
public void insertUser(User user) {
userMapper.insertUser(user);
}
Controller
@PostMapping("/insertUser")
public ResponseResult insertUser(@RequestBody User user){
userService.insertUser(user);
return new ResponseResult(200,"操作成功");
}
}
{
"username":"奇遇少年666",
"age":20,
"address":"星球"
}
删除用户
UserMapper接口
void deleteUser(Integer id);
mapper.xml映射文件
<delete id="deleteUser">
delete from user where id = #{id}
</delete>
UserService接口
void deleteUser(Integer id);
UserServiceImpl实现类
public void deleteUser(Integer id) {
userMapper.deleteUser(id);
}
Controller
@DeleteMapping("/user/{id}")
public ResponseResult deleteUser(@PathVariable("id") Integer id){
userService.deleteUser(id);
return new ResponseResult(200,"操作成功");
}
更新用户
UserMapper接口
void updateUser(User user);
mapper.xml映射文件
<update id="updateUser">
update user set username = #{username},age = #{age},address = #{address} where id = #{id}
</update>
UserService接口
void updateUser(User user);
UserServiceImpl实现类
public void updateUser(User user) {
userMapper.updateUser(user);
}
Controller
@PutMapping("/user")
public ResponseResult updateUser(@RequestBody User user){
userService.updateUser(user);
return new ResponseResult(200,"操作成功");
}
{
"id":1,
"username":"奇遇少年",
"age":20,
"address":"星球"
}
异常统一处理
我们可以使用@ControllerAdvice实现对异常的统一处理。让异常出现时也能返回响应一个JSON。
代码如下
@ControllerAdvice
public class GlobalControllerAdvice {
@ExceptionHandler(Exception.class)
@ResponseBody
public ResponseResult handleException(Exception e){
return new ResponseResult(500,e.getMessage());
}
}
拦截器
public class YuHandlerInterceptor implements HandlerInterceptor {
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("preHandle");
return true;
}
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("postHandle");
}
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("afterCompletion");
}
}
spring-mvc.xml
<!--配置拦截器-->
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**"/>
<!--配置排除拦截的路径-->
<!--<mvc:exclude-mapping path="/"/>-->
<!--配置拦截器对象注入容器-->
<bean class="com.yu.interceptor.YuHandlerInterceptor"></bean>
</mvc:interceptor>
</mvc:interceptors>
声明式事务
已经做好了相应的配置,只要在service方法上加上注解即可
@Transactional
public void testAddUser() {
userMapper.insertUser(new User(null,"奇遇少年",18,"长沙"));
// System.out.println(1/0);
userMapper.insertUser(new User(null,"奇遇少女",18,"长沙"));
}
AOP
注意,自己去使用AOP进行增强时,应该是对Service进行增强。不能对Controller进行增强,因为切面类会被放入父容器,而我们的Controller是在子容器中的。父容器不能访问子容器。
并且我们如果需要对Controller进行增强,使用拦截器也会更加的好用。
@Aspect
@Component
public class YuAspect {
//定义切点
@Pointcut("execution(* com.yu.service..*.*(..))")
public void pt(){
}
//进行增强
@Before("pt()")
public void before(){
System.out.println("before");
}
}