How to solve the garbled Chinese characters returned when jsp requests servlet addresses ?, Jspservlet
When jsp requests the servlet address, garbled Chinese characters are returned. First, the encoding format in my database is UTF-8, including jsp, myeclipse, and servlet, cainiao xiaobian finally Baidu to the solution, directly on the code.
Jsp
Package application. admin. servlet. cate; import java. io. *; import javax. servlet. *; import javax. servlet. annotation. webServlet; import javax. servlet. http. *; import org. json. JSONArray; import application. admin. cate. cate; import common. api. commonApi; @ WebServlet ("/CateListServlet") public class CateListServlet extends HttpServlet {private String json_data; public void init () throws ServletException {} public void doGet (HttpServletRequest request, response) throws ServletException, IOException {request. setCharacterEncoding ("UTF-8"); response. setCharacterEncoding ("UTF-8"); response. setContentType ("text/html; charset = UTF-8"); response. setHeader ("Content-Type", "text/html; charset = UTF-8"); JSONArray book_cate_list; String user_id = request. getParameter ("user_id"); String state = request. getParameter ("state"); Cate cate = new Cate (); try {book_cate_list = cate. book_cate_list (); // obtain all book categories int count_cate = cate. count_cate (); // counts the number of book categories. json_data = CommonApi. return_json (book_cate_list, count_cate); // assemble and return data} catch (Exception e) {// TODO Auto-generated catch block e. printStackTrace ();} response. getOutputStream (). write (json_data.getBytes ("UTF-8");} public void destroy () {// do nothing }}
Servlet
Package application. admin. servlet. cate; import java. io. *; import javax. servlet. *; import javax. servlet. annotation. webServlet; import javax. servlet. http. *; import org. json. JSONArray; import application. admin. cate. cate; import common. api. commonApi; @ WebServlet ("/CateListServlet") public class CateListServlet extends HttpServlet {private String json_data; public void init () throws ServletException {} public void doGet (HttpServletRequest request, response) throws ServletException, IOException {request. setCharacterEncoding ("UTF-8"); response. setCharacterEncoding ("UTF-8"); response. setContentType ("text/html; charset = UTF-8"); response. setHeader ("Content-Type", "text/html; charset = UTF-8"); JSONArray book_cate_list; String user_id = request. getParameter ("user_id"); String state = request. getParameter ("state"); Cate cate = new Cate (); try {book_cate_list = cate. book_cate_list (); // obtain all book categories int count_cate = cate. count_cate (); // counts the number of book categories. json_data = CommonApi. return_json (book_cate_list, count_cate); // assemble and return data} catch (Exception e) {// TODO Auto-generated catch block e. printStackTrace ();} response. getOutputStream (). write (json_data.getBytes ("UTF-8");} public void destroy () {// do nothing }}