Get請求編碼

來源:互聯網
上載者:User

標籤:

遇到get請求中文編碼的時候,有的人會採用在Tomcat/conf/server.xml中的如下添加一句:

<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" />

即:URIEncoding="utf-8"

但是這種方法不可採取!!!

為什麼那?原因是:我們寫的代碼客戶用的時候,不一定用Tomcat伺服器,可能用webLogic等伺服器,所以不可能讓客戶修改伺服器,這是不可取的方法,牢記!!!

一般採用如下的方法:

String name=response.getParameter("username");

//因為伺服器是iso編碼格式的,所以我們反編譯回來

byte[] bytes=name.getBytes("ISO-8859-1");

name=new String(bytes,"utf-8");

完整例子如下:

(1)form.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>My JSP ‘form.jsp‘ starting page</title>

<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->

</head>

<body>
</br>
<form action="OneServlet" method="post">
姓名:<input type="text" name="username" value="張三"/></br>
<input type="submit" name="提交"/><br/>
</form>
<a href="OneServlet?username=李四">點擊</a>
</body>
</html>

(2)OneServlet如下:

package com.shujia;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class OneServlet extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String name=request.getParameter("username");
byte[] bytes=name.getBytes("iso-8859-1");
name=new String(bytes,"utf-8");
System.out.println("get name:"+name );
}


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

//首先request.setCharacterEncoding("utf-8");防止中文亂碼必須要在擷取值之前添加
request.setCharacterEncoding("utf-8");
String name=request.getParameter("username");
System.out.println("name:"+name);
}

}

Get請求編碼

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.