一. 处理敏感词
拿淘宝的评论来说,如果用户的评论内容包含敏感词,比如傻xx,x你妈之类的话,则这些评论中的敏感词都会被屏蔽掉,以**显示,我们可以通过SpringMVC的拦截器来实现该功能。
test.jsp
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8" %> <!DOCTYPE html> <html> <head> <title>Title</title> </head> <body> ${requestScope.comment} </body> </html>
Controller
@Controller public class Test { @RequestMapping("/comment") public String comment(String comment,Model model) { model.addAttribute("comment",comment); System.out.println("hashCode" + model.hashCode()); return "test"; } }
Interceptor:
@Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println("Interceptor.postHandle"); Map<String, Object> model = modelAndView.getModel(); System.out.println("hashCode" + model.hashCode()); String comment = model.get("comment").toString(); String sb = comment.replaceAll("傻逼", "***"); model.put("comment",sb); }
此时访问http://localhost:8888/sm/comment?comment=孙著杰是傻逼,则页面显示孙著杰是***
而且Interceptor中的model和Controller中的model其实的同一个,hashCode相同,因为Model都会转换为ModelAndView
二. JSON字符串
在Controller中编写用于返回JSON字符串的方法如下:
@GetMapping(value="/json",produces = "application/json;charset=utf-8") public String json() { HashMap<String, Object> map = new HashMap<>(); map.put("bookId",1); map.put("name","Java开发"); map.put("price",19.9); return JSON.toJSONString(map); }
其中produces用于解决中文乱码,相当于resp.setContentType(“application/json; charset=utf-8”);
但是此时如果访问http://localhost:8888/sm/json,会404,因为springmvc将其处理成了:
/sm/WEB-INF/views/{"price":19.9,"name":"Java开发","bookId":1}.jsp
给json方法添加@ResponseBody注解即可解决该问题
@GetMapping(value="/json",produces = "application/json;charset=utf-8") @ResponseBody public String json() { HashMap<String, Object> map = new HashMap<>(); map.put("bookId",1); map.put("name","Java开发"); map.put("price",19.9); return JSON.toJSONString(map); }
此时访问http://localhost:8888/sm/json,页面显示如下:
{"price":19.9,"name":"Java??","bookId":1}
请登录之后再进行评论