设置传递格式:
request.setCharacterEncoding("utf-8");
中文字符解码:
import java.net.URLDecoder; String format = URLDecoder.decode(request.getParameter("format"), "utf-8");
中文字符加码:
import java.net.URLEncoder; String username = URLEncoder.encode(request.getParameter("username"), "UTF-8");
实例:
登陆后创建session:
<%@page import="java.net.*"%>
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Insert title here</title>
</head>
<body>
<%
request.setCharacterEncoding("UTF-8"); String username = URLEncoder.encode(request.getParameter("username"), "UTF-8");
String password =URLEncoder.encode(request.getParameter("password"),"UTF-8") ; Cookie usernameCookie = new Cookie("username",username);
Cookie passwordCookie = new Cookie("password",password); response.addCookie(usernameCookie);
response.addCookie(passwordCookie); request.getRequestDispatcher("login_success.jsp").forward(request, response);
%> </body>
</html>
表单提交包含中文字符显示:
<%@page import="java.net.URLDecoder"%>
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Insert title here</title>
</head>
<body> <%
request.setCharacterEncoding("UTF-8");
Cookie[] cookies = request.getCookies();
String username = "";
String password = ""; for(Cookie cookie : cookies) {
if("username".equals(cookie.getName()))
username =URLDecoder.decode(cookie.getValue(),"utf-8") ; if("password".equals(cookie.getName()))
password = cookie.getValue(); } %> <h1 align="center">恭喜<%=username %>登录成功</h1>
<hr>
<div style="border: solid 1px;">
<p> 用户名:<%=username %> </p>
<p> 密码: <%=password %> </p>
</div> </body>
</html>