前后台传中文乱码问题改成UTF-8

来源:互联网 发布:数据库 id冗余名称 编辑:程序博客网 时间:2024/05/18 03:59

post方式提交:

页面:<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>

servlet::response.setContentType("text/html;charset=utf-8");
request.setCharacterEncoding("utf-8");

tomcat的server.xml: 加上 URIEncoding="utf-8"

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

URIEncoding="utf-8"
              xmlns="default namespace"/>


get方式:需要进行编码与解码

页面:为何编码两次,原因未知

<input  type="button" value="查询" onclick="search1();"  />

<script>

function search1(){
//get 方式提交,编码
location.href=uri + "/bookServlet?action=searchByNum"+"&queryNum="+ encodeURI(encodeURI(num));
}

</script>

servlet:String queryNum =  java.net.URLDecoder.decode(request.getParameter("queryNum"), "UTF-8");


--------文件上传时---郁闷了好久---------------------------

jsp页面form 添加 enctype="multipart/form-data"

<form action="upload.do" method="post" enctype="multipart/form-data">
  <input type="text" name="filename"/>
  <input type="file" name="pic"/>
  <input type="submit" value="上传" />
   </form>

servlet端 需要进行改码   new String(item.getString().getBytes("ISO-8859-1"), "UTF-8")


DiskFileItemFactory factory = new DiskFileItemFactory();

factory.setSizeThreshold(1024); // yourMaxMemorySize

ServletFileUpload upload = new ServletFileUpload(factory);

List<?> items = null;
try {
items = upload.parseRequest(request);
} catch (FileUploadException e1) {

e1.printStackTrace();
}

Iterator<?> iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();

// 整个表单的所有域都会被解析,要先判断一下是普通表单域还是文件上传域
if (item.isFormField()) {
//表单文本域
System.out.println("form field:"+item.getFieldName()+"="+new String(item.getString().getBytes("ISO-8859-1"), "UTF-8"));
String name = item.getFieldName();
String value = new String(item.getString().getBytes("ISO-8859-1"), "UTF-8");
System.out.println(name + ":" + value);
} else {
//文件上传域
String fieldName = item.getFieldName();

String fileName = item.getName();


int start = fileName.indexOf('.');
String extName = fileName.substring(start);
System.out.println(extName);
String contentType = item.getContentType();
boolean isInMem = item.isInMemory();
long sizeInBytes = item.getSize();
System.out.println(fieldName + ":" + fileName);
System.out.println("类型:" + contentType);
System.out.println("内存是否存在:" + isInMem);
System.out.println("文件大小" + sizeInBytes);


File uploadedFile = new File("d:\\temp\\" + fileName);
try {
item.write(uploadedFile);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


做项目时遇到,亲测有效

0 0