首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > Java Web开发 >

servlet传汉字出现有关问题

2012-12-16 
servlet传汉字出现问题本帖最后由 itelly 于 2012-11-27 13:16:12 编辑在index.jsp页面上用表单上传一个文

servlet传汉字出现问题
本帖最后由 itelly 于 2012-11-27 13:16:12 编辑 在index.jsp页面上用表单上传一个文件,然后再servle中获得输入的汉字


index.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 'index.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>
  <form action="/Upload/servlet/Upload" method="post" enctype="multipart/form-data">
  商品<input type="text" name="product"><br>
  图片<input type="file" name="myFile"/><br>
  <input type="submit" value="提交"/>
  </form>
  </body>
</html>


package com.haolly;

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;

import com.jspsmart.upload.File;
import com.jspsmart.upload.Request;
import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;

public class Upload extends HttpServlet
{

/**
 * Constructor of the object.
 */
public Upload()
{
super();
}

/**
 * Destruction of the servlet. <br>
 */
public void destroy()
{
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}

/**
 * The doGet method of the servlet. <br>
 *
 * This method is called when a form has its tag value method equals to get.
 * 
 * @param request the request send by the client to the server
 * @param response the response send by the server to the client
 * @throws ServletException if an error occurred
 * @throws IOException if an error occurred
 */
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{

doPost(request, response);
}

/**
 * The doPost method of the servlet. <br>


 *
 * This method is called when a form has its tag value method equals to post.
 * 
 * @param request the request send by the client to the server
 * @param response the response send by the server to the client
 * @throws ServletException if an error occurred
 * @throws IOException if an error occurred
 */
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
//request.setCharacterEncoding("utf-8");//这里设置后不管用
//创建smartupload
SmartUpload upload=new SmartUpload();
//初始化
upload.initialize(this.getServletConfig(), request, response);
//限定上传数据的长度10M
upload.setTotalMaxFileSize(1024*1024*10);
//限定上传文件格式
upload.setAllowedFilesList("jpg,JPG,gif");
try
{
//调用上传
upload.upload();
//将上传的文件放在指定目录
upload.save("/upload");
//获得文件参数
File file=upload.getFiles().getFile(0);
String filename=file.getFileName();
String fileExt=file.getFileExt();
//获得form表单的参数
Request req=upload.getRequest();
String name=req.getParameter("product");
String n=new String(name.getBytes("ISO-8859-1"),"UTF-8");//换成这样也不行,GBK,GB2312都不行
System.out.println(n);
} catch (SmartUploadException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}

}

/**
 * Initialization of the servlet. <br>
 *
 * @throws ServletException if an error occurs
 */
public void init() throws ServletException
{
// Put your code here
}

}



但是我重新新建一个工程,提交表单,设置编码后能够获得汉字,我怀疑是不是那个smartupload有问题呢?
[最优解释]
设置编码为utf-8 表单提交应该就不会出乱码吧

ajax就会出问题
[其他解释]
看下你编译器设置的格式  项目右击》》JAVA Editor 看下Text file eccoding 的Other 选的是不是UTF-8 
[其他解释]
Request req=upload.getRequest();
req.setCharacterEncoding("UTF-8");
String name=req.getParameter("product");
试试
[其他解释]

先检查jsp,servlet编码格式是否统一,然后这样
request.getParameter("product");
product = new String(product.getBytes("UTF-8"));
[其他解释]
初级财年也在学习中!
[其他解释]
你确定能获取汉字么,我记得这种情况会无法获取text参数的啊,结果是null

为了传文件你设置了enctype="multipart/form-data"
好像这样会使上传的参数失效,即使在调试器中看到报头中添加了参数但是获取的结果也为null

如果获取null的话解决方法是使用两个表单,或者重写onsubmit方法,使用Ajax先传文字参数,再传图片,总之是要用两个Servlet
如果是这种情况
[其他解释]
引用:
你确定能获取汉字么,我记得这种情况会无法获取text参数的啊,结果是null

为了传文件你设置了enctype="multipart/form-data"
好像这样会使上传的参数失效,即使在调试器中看到报头中添加了参数但是获取的结果也为null

如果获取null的话解决方法是使用两个表单,或者重写onsubmit方法,使用Ajax先传文字参数,再传图片,总之……


结果为null 是由汉字乱码引起的。

[其他解释]
引用:
引用:你确定能获取汉字么,我记得这种情况会无法获取text参数的啊,结果是null

为了传文件你设置了enctype="multipart/form-data"
好像这样会使上传的参数失效,即使在调试器中看到报头中添加了参数但是获取的结果也为null

如果获取null的话解决方法是使用两个表单,或者重写onsubmit……


呃……是么,英文也为null啊
[其他解释]
引用:
引用:引用:你确定能获取汉字么,我记得这种情况会无法获取text参数的啊,结果是null

为了传文件你设置了enctype="multipart/form-data"
好像这样会使上传的参数失效,即使在调试器中看到报头中添加了参数但是获取的结果也为null

如果获取null的……


 只要是request请求 或者 请求在request作用域内 getParameter都是可以取到值的
[其他解释]
index.html

<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<form action="Test" method="post" enctype="multipart/form-data">
  goods:<input type="text" name="product">
  picture:<input type="file" name="myFile"/>
  <input type="submit" value="submit"/>
  </form>
</body>
</html>


Test.java

/*
 * To change this template, choose Tools 
[其他解释]
 Templates
 * and open the template in the editor.
 */

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author lisanhu-v570
 */
@WebServlet(name = "Test", urlPatterns = {"/Test"})
public class Test extends HttpServlet {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            String str=request.getParameter("product");


            System.out.println(str);
            out.println(str);
        } finally {            
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}



在windows tomcat7 netbeansIDE
结果为null
[其他解释]
引用:
看下你编译器设置的格式  项目右击》》JAVA Editor 看下Text file eccoding 的Other 选的是不是UTF-8


文件编码是UTF-8的
------其他解决方案--------------------


引用:
Request req=upload.getRequest();
req.setCharacterEncoding("UTF-8");
String name=req.getParameter("product");
试试

req.setCharacterEncoding("UTF-8");这个方法没有定义
[其他解释]
引用:
index.html
XML/HTML code?123456789101112131415<!DOCTYPE HTML><html lang="en-US"><head>    <meta charset="UTF-8">    <title></title></head><body>    <form action="Test" method="post" enct……


英文是可以获得的,汉字出现乱码
[其他解释]
[quote=引用:]
在windows tomcat7 netbeansIDE
结果为null ......
[quote]

是的,为null才算正常,原因是:
<form action="Test" method="post" enctype="multipart/form-data">
表明该表单的数据为二进制数据,二进制数据必须用流(java.io.InputStream)的方式才能接收,
request.getParameter(String param); 该方法返回的是String,接收不到流,

结果为null 并非乱码引起的,你的编码貌似没什么问题,问题在于你取值的方式!
如果你用了commons-fileupload-x.jar,就好办了,请看代码:


List fileItems = upload.parseRequest(request);// 表单中的所有二进制数据   
            Iterator iter = fileItems.iterator();   
            while (iter.hasNext()) {   
                FileItem item = (FileItem) iter.next();
                if (!item.isFormField()) {
                      //文件流,把文件保存到服务器,代码就不贴了,你懂的
                }else{
                       //非文件流 
                 String value=item.getString();
                    value = new String(value.getBytes("ISO-8859-1"),"UTF-8");// 这行代码根据服务器的编码格式来定
                   
                } 

热点排行
Bad Request.