1. 统一异常处理
不管是controller层还是service,dao层,都有可能报异常,如果是预料中的异常,可以直接捕获处理,如果是意料之外的异常,需要统一进行处理,进行记录,并给用户提示相对比较友好的信息。
@ControllerAdvice
public class AllExceptionHandler {
//进行异常处理,处理Exception.class的异常
@ExceptionHandler(Exception.class)
@ResponseBody //返回json数据
public Result doException(Exception ex){
ex.printStackTrace();
return Result.fail(-9999,"系统异常");
}
}
2. 首页-最热文章
2.1 接口说明
- 接口url:/articles/hot
- 请求方式:POST
- 请求参数:无参数
2.2 Controller
@PostMapping("hot")
public Result hotArticle(){
return articleService.hotArticle(5);
}
2.3 Service
public Result hotArticle(int limit) {
QueryWrapper<Article> queryWrapper = new QueryWrapper<>();
queryWrapper.select("id","title");
queryWrapper.orderByDesc("view_counts");
queryWrapper.last("limit " + limit); //此处有一个空格
List<Article> articles = articleMapper.selectList(queryWrapper);
return Result.success(copyList(articles,false,false));
}
3. 首页-最新文章
3.1 接口说明
- 接口url:/articles/new
- 请求方式:POST
- 请求参数:无参数
3.2 Controller
@PostMapping("/new")
public Result newArticle(){
return articleService.newArticle(5);
}
3.3 Service
public Result newArticle(int limit) {
QueryWrapper<Article> queryWrapper = new QueryWrapper<>();
queryWrapper.select("id","title");
queryWrapper.orderByDesc("create_date");
queryWrapper.last("limit " + limit);
List<Article> articles = articleMapper.selectList(queryWrapper);
return Result.success(copyList(articles,false,false));
}
4. 首页-文章归档
4.1接口说明
- 接口url:/articles/listArchives
- 请求方式:POST
- 请求参数:无参数
4.2 Controller
@PostMapping("/listArchives")
public Result listArchives(){
return articleService.listArchives();
}
4.3 Service
public Result listArchives() {
List<Article> articles = articleMapper.listArchives();
return Result.success(articles);
}
4.4 Dao
@Repository
public interface ArticleMapper extends BaseMapper<Article> {
List<Article> listArchives();
}
<mapper namespace="com.mszl.dao.mapper.ArticleMapper">
<select id="listArchives" resultType="com.mszl.dao.dos.Archives">
select year(from_unixtime(create_date/1000)) as year,month(from_unixtime(create_date/1000)) as month,count(*) as count
from ms_article group by year,month
order by year desc ,month desc ;
</select>
</mapper>