package newpackage; 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 NewServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); String userInput = new String(request.getParameter("userInput").getBytes("UTF-8")); out.print(userInput); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); out.print("哈囉"); } }不管是POST還是GET第一行都要先放response.setContentType("text/html;charset=UTF-8");這行
如果是GET,要先把在網址列取得的參數用getBytes取得並轉成UTF-8,之後才輸出。可以上方的程式碼。
最近又發生亂碼的情況了,看來還有別的會亂碼的情況我沒注意到
就是我從jsp送post請求給servlet,servlet再把這個從jsp送來的參數顯示到另一個jsp
我在servlet用System.out.println()查看這個參數,才發現進到servlet時就亂碼了,所以應該不是jsp的問題
後來我在servlet的doPost的第二行加入request.setCharacterEncoding("UTF-8");
就解決了
原本以為
沒有留言:
張貼留言