1.浏览器向服务器发送消息:request,使用过滤器为所有请求:设置 request.setCharacterEncoding(“utf-8”);
此时不修改编码格式的话,tomcat默认是按照编码的,不是utf-8,这样的数据写进数据库就是乱码啦呱~
//浏览器发来服务器消息进行重新编码的编码。
request.setCharacterEncoding("utf-8");
1.1EncodingFilter.java代码
@WebFilter("/*")
public class EncodingFilter implements Filter {@Overridepublic void init(FilterConfig filterConfig) throws ServletException {}@Overridepublic void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {HttpServletRequest request =(HttpServletRequest) servletRequest;request.setCharacterEncoding("utf-8");filterChain.doFilter(request,servletResponse);}@Overridepublic void destroy() {}
}
2.服务器向浏览器发送消息:response,使用BaseController进行判断方法是否被自定义注解修饰:设置resp.setContentType(“text/html;charset=utf-8”);
//对服务器发送浏览器消息:用于定义网络文件bai的类型和网页的编码,决定浏览器du将以什么zhi形式、什么编码读取这个文件
resp.setContentType("text/html;charset=utf-8");
2.1自定义注解ContentType 代码
//详情请见:
https://blog.csdn.net/qq_39773004/article/details/108661464?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522160048748919725247415269%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fblog.%2522%257D&request_id=160048748919725247415269&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~blog~first_rank_v2~rank_blog_default-1-108661464.pc_v2_rank_blog_default&utm_term=%E8%87%AA%E5%AE%9A%E4%B9%89%E6%B3%A8%E8%A7%A3&spm=1018.2118.3001.4187
@Retention(RetentionPolicy.RUNTIME) //被反射读取到 class
@Target(ElementType.METHOD) //应用到方法上public @interface ContentType {String value();int id() default 1;String name() default "Ellie";
}
2.2BaseController代码
public class BaseController extends HttpServlet {@Overrideprotected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {if (method.isAnnotationPresent(ContentType.class)){ContentType contentType = method.getAnnotation(ContentType.class);String type = contentType.value();//image/jpeg application/json;charset=utf-8resp.setContentType(type);}else{resp.setContentType("text/html;charset=utf-8");}}
}