我在 servlet(eap 6.1)上上传 xml 文件(带有 utf-8 字符)并且解析的数据不是 utf-8。尝试了很多教程,但没有运气。解析的数据打印到文件、控制台和数据库。一切都是 utf-8 配置的。所以代码:
@WebServlet(name = "penDataConsumer", urlPatterns = { "/pens" })
public class DigiPenServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private String path = "/Users/didar/";
@Inject
private Logger log;
@Inject
private Pens pens;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println("Hello World! Digital Pen");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
request.setCharacterEncoding("UTF-8");
processUpload(request, response);
} catch (Exception e) {
e.printStackTrace();
}
}
public void processUpload(HttpServletRequest request, HttpServletResponse response) throws Exception {
PrintWriter outResp = response.getWriter();
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(this.path + "log.txt", true)));
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
String sendfile = "";
try {
FileItemIterator iter = new ServletFileUpload(new DiskFileItemFactory()).getItemIterator(request);
while(iter.hasNext()){
FileItemStream item = iter.next();
if (item.getFieldName().equals("sendfile")) {
String filename = FilenameUtils.getName(item.getName());
InputStream filecontent = item.openStream();
// sendfile = Streams.asString(filecontent, "UTF-8");
PrintWriter outFile = new PrintWriter(new File(this.path + "files/" + filename));
Date date = new Date();
System.out.println("blanks/pens: " + dateFormat.format(date) + " - " + filename + ": ");
StringWriter writer = new StringWriter();
IOUtils.copy(filecontent, writer, Charset.forName("UTF-8"));
sendfile = writer.toString();
outFile.print(sendfile);
outFile.close();
}
out.flush();
}
System.out.println("Input file start-----------------------------------------------------------");
System.out.println(sendfile);
System.out.println("Input file end-------------------------------------------------------------");
outResp.print("done");
} catch (FileUploadException e) {
throw new ServletException("Cannot parse multipart request.", e);
} catch (Exception e) {
throw new ServletException("Other Exception", e);
} finally {
out.close();
outResp.close();
}
}
}
和html页面:
<html>
<body>
<form enctype="multipart/form-data" action="http://localhost:8080/blanks/pens" method="post">
File: <input type="file" name="sendfile">
<input type="submit" value="Submit">
</form>
</body>
</html>
版本:io.utils - 2.4 和 fileupload - 1.3