javaweb之request获取referer请求头实现防盗链

package test.request;

import java.io.IOException;

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

//利用referer请求头实现防盗链
public class RequestDemo8 extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 获取请求是从哪里来的
		String referer = request.getHeader("referer");
		// 如果是直接输入的地址,或者不是从本网站访问的重定向到本网站的首页
		if (referer == null || !referer.startsWith("http://localhost")) {
			response.sendRedirect("/day06/index.jsp");
			// 然后return,不要输出后面的内容了
			return;
		}
		String date = "日记";
		response.getWriter().write(date);
	}

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

}

你可能感兴趣的:(自己用)