使用servlet+jsp实现简单的登录验证功能,成功与否都会在jsp页面打印出提示信息,但是页面显示的提示信息一直乱码
其中对于乱码有以下编码设置:
1、jsp页面头的设置
2、servlet类中编码设置
3、tomcat中servlet.xml文件中的设置
4、web项目中设置了一个编码格式过滤器
下面是对应代码:
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
servlet类中
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setHeader("content-type", "text/html;chatset=UTF-8");
String username=request.getParameter("username");
String password=request.getParameter("password");
Object[] params=new Object[]{username,password};
boolean result=loginService.regist(params);
PrintWriter writer=response.getWriter();
String str="";
if(result){
str="註冊成功!";
}else{
str="用戶名已存在,註冊失敗!";
}
System.out.print(str);
writer.print(new String(str.getBytes("iso-8859-1"),"utf-8"));
}
servlet.xml文件中
<Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443" URIEncoding="UTF-8"/>
web.xml
<filter>
<filter-name>SetCharacterEncodingFilter</filter-name>
<!-- 过滤器设置编码文件 -->
<filter-class>
util.SetCharacterEncodingFilter
</filter-class>
<init-param>
<!--
init-param元素定义了过滤器的初始化参数
-->
<description>给参数和值设置名称和编码类型</description>
<param-name>encode</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<!--
filter-mapping告诉容器所有与模式向匹配的请求都应该允许通过访问控制过滤器。
所有以.do结尾的访问都先通过过滤器文件过滤
-->
<filter-name>SetCharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
在servlet里面再加了一句response.setContentType("text/html; charset=utf-8");就好了