欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Servlet之处理请求(七)

程序员文章站 2022-06-03 11:21:04
...

8.设置响应头
响应头Header是随响应数据一起发送到浏览器的附加信息;每个响应头通过“名/值”对的形式发送到客户端。
void setHeader(String name ,String value)
Void setlntHeader(String name,int value)
Void setDateHeader(String name,long date)
Servlet之处理请求(七)
下面的ShowTimeServlet通过设置Refresh响应头实现每5秒钟刷新一次页面;

package com.demo;

import java.io.IOException;
import java.io.PrintWriter;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class ShowTimeServlet
 */
@WebServlet("/show-time")
public class ShowTimeServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html/;charset=UTF-8");
		response.setHeader("refresh", "5");
		
		LocalTime now=LocalTime.now();//取得当前时间
		//将本地时间格式化成字符串
		DateTimeFormatter format=DateTimeFormatter.ofPattern("hh:mm:ss");//生成一个时分秒的格式化器
		String t =now.format(format);
		
		PrintWriter out=response.getWriter();
		out.println("<html><body>每五秒刷新一下本页面<br>");
		out.print("当前时间是:"+t+"<br>");
		out.println("</body></html>");
		
}

}

9.发送状态码
状态码是服务器向客户发送的响应的第一行,由HTTP版本、状态码和状态码的描述信息构成;
通常使用HttpServletResponse接口定义的常量;
Servlet之处理请求(七)
下面的Servlet如果发现客户无法访问其结果,它将调用sendError(HttpServletResponse.SC_UNAUTHORIZED)

package com.demo;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class StatusServlet
 */
@WebServlet("/StatusServlet")
public class StatusServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out=response.getWriter();
		
		String qq=request.getParameter("q");
		if(qq==null) {
			out.println("没有提供请求参数");
		}else if(qq.equals("0")) {
			out.println(response.getStatus()+"<br>");
		}
		else if(qq.equals("1")) {
			response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);//401
		}else if(qq.equals("2")) {
			response.setStatus(HttpServletResponse.SC_FORBIDDEN);//403
		}
		else {
			response.sendError(404, "resouce cannot founded");
		}
	}

}