原理:判断http消息头中的referer是否为空或者是否不为localhost
代码放在:jsp文件引入,因为所有数据都是以jsp页面的形式展示出来的
<%@page import="com.qipai.referer_module.Request_referer" %> //引入包
<%
Request_referer Rr=new Request_referer();
Rr.Referer(request, response);
%>
代码:
//这个函数属于Request_referer 类
public void Referer(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
//设置浏览器以什么编码打开
response.setCharacterEncoding("utf-8");
response.setContentType("text/html;utf-8");
PrintWriter out=response.getWriter();
//获取请求头
String referer=request.getHeader("Referer");
//判断这个请求头是否为空,或者这个请求头是否不为localhost
if(referer == null || !referer.startsWith("http://localhost")){
out.println("请登录");
response.sendRedirect("http://localhost:8080/QiPaiProject/Login.jsp");
}
}