jsp中文显示乱码的解决办法

表单提交时,获取输入的中文参数时,浏览器会出现中文乱码,这时在表单响应的jsp文件中加入request.setCharacterEncoding("utf-8");即可解决。相关代码如下:


附:表单提交的jsp文件内容:

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

<%

String path = request.getContextPath();

String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

%>


<html>

  <head>

    <META http-equiv="Content-Type" content="text/html; charset=utf-8">

    <title>测试JSP内置对象</title>

  </head>

  

  <body>

 <form action="internalObjResult.jsp" method="post">

  uname:<input type="text" name="uname"><br/>

  pwd:<input type="password" name="pwd"><br/>

  hobbies:<input type="text" name="hobby">&nbsp;

  <input type="text" name="hobby"><br/>

  submit:<input type="submit" name="submit"/>

 </form>

  </body>

</html>

表单响应的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>

  <META http-equiv="Content-Type" content="text/html; charset=utf-8">

    <title>My JSP 'internalObjResult.jsp' starting page</title>

  </head>

  

  <body>

  <%request.setCharacterEncoding("utf-8");//不加此句,浏览器端中文会显示乱码

  String uname=request.getParameter("uname");

  out.println(uname+"<br>");

  Enumeration<?> e=request.getParameterNames();//不加<?>会有警告

  while(e.hasMoreElements()){

  out.println(e.nextElement()+"<br>");

  }

  out.println("所有values:"+"<br>");

  String[] s=request.getParameterValues("hobby");

  for(String temp:s){

  out.println(temp+"<br>");

  }

  %>

  

  </body>

</html>


你可能感兴趣的:(jsp中文显示乱码的解决办法)