只需要在对应的doGet或doPost方法中加上下面两行:
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
@WebServlet(name = "RegisterServlet", urlPatterns = "/com.servlet.RegisterServlet")
public class RegisterServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//设置编码格式
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
//就加上上面两行就够了
}
}
还需要注意的是这里设置了utf-8编码后,其对应的jsp(或html)文件中的编码也要改成utf-8,不然还是会乱码
我这里用的是jsp文件
代码如下:
<%@ 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>
</head>
<body>
</body>
</html>
上面代码中的charset的属性要改成utf-8,这样就解决了。
需要注意的是,request.setCharacterEncoding("utf-8");
只对post提交方式有效,如果是get方式的话,请看下面: