When the browser sends an http request to the web server, the server wraps the http request into a request object, which includes the referer, which means to tell the server where the request comes from. For example, if a hyperlink is inserted in a web page to link to other web pages, then when the hyperlink is clicked to link to another page, it is equivalent to the browser sending an http request to the web server, for another page. , this referer is the URL of the previous page, and for the way of directly entering the URL from the address bar or refreshing the web page, the referer = null, setting this referer can prevent the problem of hotlinking
Look at the following code, for example, I directly enter the address from the browser's address bar: http://localhost:8080/Servlet1/MainFrame, and then click the Enter key, it will output: illegal intrusion
- package com.mx.view;
- import java.io.IOException;
- import java.io.PrintWriter;
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- publicclass MainFrame extends HttpServlet {
- publicvoid doGet(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- response.setContentType("text/html;charset=utf-8");
- PrintWriter out = response.getWriter();
- String referer=response.getHeader("Referer");
- if(referer==null||!referer.startsWith("http://localhost:8080/Servlet1")){
- response.sendRedirect("/Servlet1/Error");
- }else{
- out.println( "Legal view!" );
- }
- response.setContentType("text/html;charset=utf-8");
- out.println( "<h1>Login interface</h1>" );
- }
- publicvoid doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- this.doGet(request, response);
- }
- }
- package com.mx.view;
- import java.io.IOException;
- import java.io.PrintWriter;
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- public class Error extends HttpServlet {
- public void doGet(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- response.setContentType("text/html;charset=utf-8");
- PrintWriter out = response.getWriter();
- out.println("非法入侵");
- }
- publicvoid doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- this.doGet(request, response);
- }
- }
Attached Servlet1 project directory map: