request对象和response对象(3)
来源:未知 责任编辑:责任编辑 发表时间:2014-05-10 12:18 点击:次
p> response.setCharacterEncoding("UTF-8");
p> response.setContentType("text/html;charset=UTF-8");
p> PrintWriter out = response.getWriter();
p> out.write(s);
p> }
p> //字符流输出中文数据
p> private void test3(HttpServletResponse response) throws IOException{
p> String s = "你好!三";
p> response.setContentType("text/html;charset=UTF-8");
p> PrintWriter out = response.getWriter();
p> out.write(s);
p> }
p>
p>
p> public void doPost(HttpServletRequest request, HttpServletResponse response)
p> throws ServletException, IOException {
p> doGet(request,response);
p> }
p>}
p>复制代码
p>分析:
p>
p>乱码原因:以默认编码发送数据 ISO-8859-1(没有中国二字编码),此时会发生乱码
p>
p>解决办法:
p>
p>1)
p>
p>setCharacterEncoding(“UTF-8”);//更改编码为UTF-8
p>
p>response.setHead(“Context-type”,”text/html;charset=UTF-8”);//告诉客户端编码方式
p>
p>2)response.setContentType("text/html;charset=utf-8");
p>
p>在字符流输出中文数据时:
p>
p>response.setContentType("text/html;charset=utf-8");有两个作用:
p>
p>通知字符流以UTF-8编码输出
p>
p>通知客户端以UTF-8解码显示
p>
p>3.输出随机验证码
p>
p>复制代码
p>package cn.lsl.response;
p>
p>import java.awt.Color;
p>import java.awt.Font;
p>import java.awt.Graphics;
p>import java.awt.image.BufferedImage;
p>import java.io.IOException;
p>import java.util.Random;
p>import javax.imageio.ImageIO;
p>import javax.servlet.ServletException;
p>import javax.servlet.http.HttpServlet;
p>import javax.servlet.http.HttpServletRequest;
p>import javax.servlet.http.HttpServletResponse;
p>
p>public class ResponseDemo3 extends HttpServlet {
p>
p> public void doGet(HttpServletRequest request, HttpServletResponse response)
p> throws ServletException, IOException {
p> //通知浏览器不要缓存
p> response.setHeader("Expires", "-1");
p> response.setHeader("Cache-Control", "no-cache");
p> response.setHeader("Pragma", "no-cache");
p>
p> int width = 120;
p> int height = 25;
p> //创建一副内存图像BufferedImage
相关新闻>>
最新推荐更多>>>
- 发表评论
-
- 最新评论 更多>>