一、设置状态码

@WebServlet(name = "Servlet3",
        urlPatterns = {"/servlet3"}
)
public class Servlet3 extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //手动设置http响应中的状态码
        response.setStatus(302);

    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}

运行结果:

response获取状态码和内容 response设置状态码_客户端

二、设置响应头

@WebServlet(name = "Servlet3",
        urlPatterns = {"/servlet3"}
)
public class Servlet3 extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.addHeader("name","naruto");
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}

运行结果:

response获取状态码和内容 response设置状态码_客户端_02

三、重定向

特点:访问服务器两次,地址栏的地址发生变化
重定向:状态码302
响应头:Location,代表的是重定向的地址

@WebServlet(name = "Servlet3",
        urlPatterns = {"/Servlet3"}
)
public class Servlet3 extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //没有响应资源,告知客户端去重定向的Servlet2
        //1、设置状态码302
        response.setStatus(302);
        //2、设置响应头Location
        response.setHeader("Location","/Servlet4");
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}

运行结果:

response获取状态码和内容 response设置状态码_Response_03


Java将这些封装成重定向的方法sendRedirect(url),所以要重定向我们也可以直接使用:

response.sendRedirect(“/Servlet4”);实现重定向

定时刷新

@WebServlet(name = "Servlet3",
        urlPatterns = {"/Servlet3"}
)
public class Servlet3 extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置定时刷新的头
        response.setHeader("refresh","5,url=http://www.baidu.com");
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}

运行结果:5秒中之后,自动跳转到baidu页面去了

response获取状态码和内容 response设置状态码_javaweb_04

四、使用js完成页面定时跳转

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <script type="text/javascript">
            window.onload = function(){
                var time = 5;
                var secondEle = document.getElementById("second");
                var timer = setInterval(function(){
                    secondEle.innerHTML = time;
                    time--;
                    if(time == 0){
                        clearInterval(timer);
                        location.href="http://www.baidu.com";
                    }
                },1000);
            }
        </script>
    </head>
    <body>
        恭喜你,注册成功,<span style="color: red" id="second">5</span>秒钟后跳转,如不跳转点击<a href="http://www.baidu.com">这里!
    </body>
</html>

五、使用response的writer

@WebServlet(name = "Servlet3",
        urlPatterns = {"/Servlet3"}
)
public class Servlet3 extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter writer = response.getWriter();
        writer.write("hello response");

    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}

运行结果:输出hello response
但是当我们使用:

PrintWriter writer = response.getWriter();
writer.write("中国");

输出的是两个问号!
所以先要设置response查询的码表和客户端解码的码表:

@WebServlet(name = "Servlet3",
        urlPatterns = {"/Servlet3"}
)
public class Servlet3 extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置response查询的码表
        response.setCharacterEncoding("UTF-8");
        //通过头Contend-Type告知客户端使用何种码表进行解码
        response.setHeader("Content-Type","text/html;charset=UTF-8");
        PrintWriter writer = response.getWriter();
        writer.write("中国");

    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}

运行结果:

response获取状态码和内容 response设置状态码_java_05


实际开发中,写response.setHeader(“Content-Type”,”text/html;charset=UTF-8”);就可以了,因为检测到这句代码之后,tomcat会自动将response查询的码表改成UTF-8的。

Java也为这句话封装了一个方法:

response.setContentType(“text/html;charset=UTF-8”);实现上述功能

六、使用response的outputstream

@WebServlet(name = "Servlet3",
        urlPatterns = {"/Servlet3"}
)
public class Servlet3 extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //使用response获得字节输出流
        ServletOutputStream out = response.getOutputStream();
        //获得服务器上的图片
        String realPath = this.getServletContext().getRealPath("6.jpg");
        InputStream in = new FileInputStream(realPath);
        int len;
        byte[] buffer = new byte[1024];
        while((len=in.read(buffer))>0){
            out.write(buffer,0,len);
        }
        in.close();
        out.close();
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}

运行结果:将图片从服务器读出来,然后到客户端显示。

response获取状态码和内容 response设置状态码_javaweb_06

七、文件下载

问题:
1)什么情况下会有文件下载?
浏览器不能解析的文件就下载。
2)什么情况情况下需要在服务端编写文件下载的代码?
理论上,浏览器可以解析的代码需要编写文件下载代码,实际开发中,只要是下载的文件都编写文件下载代码。
html代码:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
          <h1>使用服务器端编码的方式实现文件下载</h1><br>
          <a href="/Servlet4?filename=6.jpg">6.jpg</a>
    </body>
</html>

Servlet代码:

package com.servlet;

@WebServlet(name = "Servlet4",
        urlPatterns = {"/Servlet4"})
public class Servlet4 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获得要下载的文件的名称
        String filename = request.getParameter("filename");
        //要下载的这个文件的类型--客户端通过文件的MIME类型去区分类型
        response.setContentType(this.getServletContext().getMimeType(filename));
        //告诉客户端该文件不能直接解析,而是以附件形式打开(下载)
        response.setHeader("Content-Disposition","attachment;filename="+filename);
        //获得该文件的绝对路径
        String path = this.getServletContext().getRealPath(filename);
        System.out.println(path);
        //获得该文件的输入流
        FileInputStream in = new FileInputStream(path);
        //获得输出流--通过response获得的输出流,用于向客户端写内容
        ServletOutputStream out = response.getOutputStream();
        //文件拷贝模版代码
        int len;
        byte[] buffer = new byte[1024];
        while((len=in.read(buffer))>0){
            out.write(buffer,0,len);
        }
        in.close();
        out.close();
    }
}

运行结果:

response获取状态码和内容 response设置状态码_response获取状态码和内容_07


中文名乱码问题:

package com.itheima.content;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import sun.misc.BASE64Encoder;

public class DownLoadServlet2 extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //*******文件名称是中文的下载*******
        //获得要下载的文件的名称
        String filename = request.getParameter("filename");//????.jpg
        //解决获得中文参数的乱码----下节课讲
        filename = new String(filename.getBytes("ISO8859-1"),"UTF-8");//美女.jpg

        //获得请求头中的User-Agent
        String agent = request.getHeader("User-Agent");
        //根据不同浏览器进行不同的编码
        String filenameEncoder = "";
        if (agent.contains("MSIE")) {
            // IE浏览器
            filenameEncoder = URLEncoder.encode(filename, "utf-8");
            filenameEncoder = filenameEncoder.replace("+", " ");
        } else if (agent.contains("Firefox")) {
            // 火狐浏览器
            BASE64Encoder base64Encoder = new BASE64Encoder();
            filenameEncoder = "=?utf-8?B?"
                    + base64Encoder.encode(filename.getBytes("utf-8")) + "?=";
        } else {
            // 其它浏览器
            filenameEncoder = URLEncoder.encode(filename, "utf-8");             
        }

        //要下载的这个文件的类型-----客户端通过文件的MIME类型去区分类型
        response.setContentType(this.getServletContext().getMimeType(filename));
        //告诉客户端该文件不是直接解析 而是以附件形式打开(下载)----filename="+filename 客户端默认对名字进行解码
        response.setHeader("Content-Disposition", "attachment;filename="+filenameEncoder);

        //获取文件的绝对路径
        String path = this.getServletContext().getRealPath("download/"+filename);
        //获得该文件的输入流
        InputStream in = new FileInputStream(path);
        //获得输出流---通过response获得的输出流 用于向客户端写内容
        ServletOutputStream out = response.getOutputStream();
        //文件拷贝的模板代码
        int len = 0;
        byte[] buffer = new byte[1024];
        while((len=in.read(buffer))>0){
            out.write(buffer, 0, len);
        }
        in.close();
        //out.close();

    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }
}

reponse细节点:
1)response获得的流不需要手动关闭,Tomcat容器会帮助我们关闭
2)getWriter和getOutputStream不能同时调用