- jsp 页面上写中文的必要条件
- 在<%@ page language=”java” contentType=”text/html; charset=UTF-8” pageEncoding=”UTF-8”%> 中的 charset 和 pageEncoding 的值必须一致。
- 在浏览器中的请求是后的编码和 jsp 的编码一致
在jsp 页面中获取中文参数值的条件
- 在请求的之前的时候设置好请求编码 request.setCharacterEncoding(“UTF-8”)就可以解决问题。(但是对GET请求是无效的)
GET的方式:
``` <% String name = request.getParameter("username"); String username = new String(name.getBytes("iso-8859-1"), "UTF-8"); out.print(username); %> ```
- 通用的方式:
- 修改tomcat的servlet.xml 文件:
通过添加全站编码的拦截器来设置编码:
``` import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.annotation.WebFilter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet Filter implementation class EncordFilter */ @WebFilter( filterName="oneFilter", urlPatterns = {"/*"} ) public class EncordFilter implements Filter { /** * Default constructor. */ public EncordFilter() { // TODO Auto-generated constructor stub } /** * @see Filter#destroy() */ public void destroy() { // TODO Auto-generated method stub } /** * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain) */ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest request2 = (HttpServletRequest)request; HttpServletResponse response2 = (HttpServletResponse)response; request2.setCharacterEncoding("UTF-8"); response2.setCharacterEncoding("UTF-8"); chain.doFilter(request, response); } /** * @see Filter#init(FilterConfig) */ public void init(FilterConfig fConfig) throws ServletException { // TODO Auto-generated method stub } } ```
JavaWEB-中文乱码
最新推荐文章于 2022-03-08 19:23:32 发布