The method setCharacterEncoding(String) is undefined for the type HttpServletResponse

本文介绍了在不同版本的Servlet环境中如何正确设置字符集编码的方法。对于Servlet 2.4及更高版本,可以直接使用response.setCharacterEncoding('gb2312');而对于2.4以下版本,则需采用response.setContentType('text/html;charset=gb2312')的方式。

本文参考:http://zhidao.baidu.com/question/212618937.html


response.setCharacterEncoding("gb2312"); 在Servlet2.3中是不行的,至少要2.4版本才可以,如果低于2.4版本,可以用如下办法: 

response.setContentType("text/html;charset=gb2312");
package com.taobao.servlet; import java.io.IOException; import java.sql.*; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.gson.Gson; import com.taobao.util.DBUtil; @WebServlet("/rebuyPrediction") public class RebuyPredictionServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setCharacterEncoding("UTF-8"); response.setContentType("application/json;charset=UTF-8"); List<Map<String, Object>> predictions = new ArrayList<>(); String sql = "SELECT userId, probability FROM rebuy_prediction LIMIT 50"; try (Connection conn = DBUtil.getConnection(); PreparedStatement pstmt = conn.prepareStatement(sql); ResultSet rs = pstmt.executeQuery()) { while (rs.next()) { Map<String, Object> prediction = new HashMap<>(); prediction.put("userId", rs.getString("userId")); prediction.put("probability", rs.getDouble("probability")); predictions.add(prediction); } response.getWriter().write(new Gson().toJson(predictions)); } catch (SQLException e) { e.printStackTrace(); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); response.getWriter().write(new Gson().toJson(Map.of("error", "数据库查询失败"))); } } }he method of(String, String) is undefined for the type Map改正确代码
最新发布
06-17
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值