javaweb之request乱码解决(数据提交以post方式和get方式)

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>向RequestDemo4提交中文数据,解决乱码问题</title>
</head>

<body>
	<!--post方式提交-->
	<form action="/day06/servlet/RequestDemo4" method="post">
		用户名:<input type="text" name="username" /> <input type="submit"
			value="提交" />
	</form>
	<!--get方式提交-->
	<form action="/day06/servlet/RequestDemo4" method="get">
		用户名:<input type="text" name="username" /> <input type="submit"
			value="提交" />
	</form>
	<!-- 超链接方式提交的中文,服务器想不乱码,也只能手工处理(貌似超链接提交要经过url编码)-->
	<a href="/day06/servlet/RequestDemo4?username=中国">单击</a>
</body>
</html>


package test.request;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//request乱码解决,除了下面的解决方式,还可以改服务器配置,但不要用那种方式
public class RequestDemo4 extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		test2(request);
	}

	/*
	 * get方式提交:由于get方式提交request.setCharacterEncoding(arg0);无效,所以乱码只能手工处理,拿到乱码的数据后
	 * ,按照ISO8859-1进行解码,然后按照UTF-8进行编码。
	 */
	private void test2(HttpServletRequest request)
			throws UnsupportedEncodingException {
		String username = request.getParameter("username");
		// get方式解决乱码,先把乱码按照原来的编码解码,返回数据的表示数字,然后按照想要的码表编码
		username = new String(username.getBytes("ISO8859-1"), "UTF-8");
		System.out.println(username);
	}

	/*
	 * post方式提交:浏览器以当前页面的码表提交数据,当前页面的码表是程序员写程序时自己指定的。数据提交到request里面去,
	 * 但是当request往外面取数据时用的是ISO8859
	 * -1码表,就会产生乱码所以要在取数据之前指定request的码表。request.setCharacterEncoding
	 * (arg0);只对post方式起作用
	 */
	private void test1(HttpServletRequest request)
			throws UnsupportedEncodingException {
		// 设置request码表
		request.setCharacterEncoding("UTF-8");
		String username = request.getParameter("username");
		System.out.println(username);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值