博客项目目录: 请戳这里
准备
需求:用户登录后,点击发表新帖,会进入如下界面,选择专栏,输入标题和内容,即可发表博客,并且后台post表会新增一条记录
当出现异常时,会跳转到统一的错误界面,并输出异常信息
1.添加edit.ftl
将\fly-3.0\html\jie下的add.html添加到post包下,并且重命名为edit.ftl,提取出container部分,套在模板里面,保留“jie”的js
2.PostController添加edit方法
@GetMapping("/post/edit")
public String edit(){
return "/post/edit";
}
在header-panel.ftl修改对应链接:
测试:
3.完善edit方法
首先获取id,如果id不为空,则获取对应文章。如果文章为空,则断定“帖子已被删除”;如果文章对应的用户id不等于当前账户id,则断定“没有权限”。最后将文章和分类注入到前端。
@GetMapping("/post/edit")
public String edit(){
String id=req.getParameter("id");
if(!StringUtils.isEmpty(id)){
Post post=postService.getById(id);
Assert.isTrue(post!=null,"该帖子已被删除");
Assert.isTrue(post.getUserId().longValue()==getProfileId().longValue(),"没有权限操作此文章");
req.setAttribute("post",post);
}
req.setAttribute("categories", categoryService.list());
return "/post/edit";
}
4.异常问题
修改detail.ftl对应链接
登录用户,点击非当前用户的帖子,进入详情页后,点击编辑此贴,发现错误页面很难看,看日志发现是“没有权限”
5.自定义全局异常处理
- 在common包下新建exception包,定义如下异常方法。如果是ajax,则通过对应处理获取错误信息;如果是web,则获取ModelAndView,通过它将错误信息message注入到前端。
@Slf4j
@ControllerAdvice
public class GlobalExcepitonHandler {
@ExceptionHandler(value = Exception.class)
public ModelAndView handler(HttpServletRequest req, HttpServletResponse resp, Exception e) throws IOException {
// ajax 处理
String header = req.getHeader("X-Requested-With");
if(header != null && "XMLHttpRequest".equals(header)) {
resp.setContentType("application/json;charset=UTF-8");
resp.getWriter().print(JSONUtil.toJsonStr(Result.fail(e.getMessage())));
return null;
}
if(e instanceof NullPointerException) {
// ...
}
// web处理
ModelAndView modelAndView = new ModelAndView("error");
modelAndView.addObject("message", e.getMessage());
return modelAndView;
}
}
- 从\fly-3.0\html\other下引入tips.html错误页面,重命名为error.ftl
- 测试
发现错误页面已经改成我们定义的样子
5.PostController添加submit方法
- 在Post类添加如下注解
- 添加submit方法
首先通过ValidationUtil工具验证文章是否有效,然后进行判断。如果文章为空,则表示新增文章,修改对应属性,保存即可;如果文章不为空,则表示编辑文章,还是先声明是否有权限,然后修改对应属性,跟新文章。
@ResponseBody
@PostMapping("/post/submit")
public Result submit(Post post){
ValidationUtil.ValidResult validResult = ValidationUtil.validateBean(post);
if(validResult.hasErrors()) {
return Result.fail(validResult.getErrors());
}
if(post.getId() == null) {
post.setUserId(getProfileId());
post.setModified(new Date());
post.setCreated(new Date());
post.setCommentCount(0);
post.setEditMode(null);
post.setLevel(0);
post.setRecommend(false);
post.setViewCount(0);
post.setVoteDown(0);
post.setVoteUp(0);
postService.save(post);
} else {
Post tempPost = postService.getById(post.getId());
Assert.isTrue(tempPost.getUserId().longValue() == getProfileId().longValue(), "无权限编辑此文章!");
tempPost.setTitle(post.getTitle());
tempPost.setContent(post.getContent());
tempPost.setCategoryId(post.getCategoryId());
postService.updateById(tempPost);
}
return Result.success().action("/post/" + post.getId());
}
6.测试
发表新博客:
7.问题解决
最后有一个小问题,表情符号没有被渲染出来,在detail.ftl添加如下js
效果:
参考资料:
https://github.com/MarkerHub/eblog