首页 文章

如何防止servlet直接通过浏览器调用

提问于
浏览
3

我正在使用java servlet和jsp页面开发一个web项目 . 在其中一个servlet中,我们有RequestDispatcher方法,它正在调用另一个servlet .

@WebServlet("/Demo")
public class DemoServlet extends HttpServlet {  

    public void doGet(HttpServletRequest req, HttpServletResponse res)  
            throws ServletException, IOException {  
        res.sendRedirect("testing"); //calling other servlet 
    }  
}
@WebServlet("/testing")
    public class TestingServlet extends HttpServlet {  

        public void doGet(HttpServletRequest req, HttpServletResponse res)  
                throws ServletException, IOException {  
                response.setContentType("text/html;charset=UTF-8");  
                PrintWriter out = response.getWriter();
                out.println("Hello World");

        }  
    }

所以,现在我想防止直接从浏览器调用contextRoot / testing,而只是让它从其他servlet(Demo)调用

如果有任何办法,请建议我 .

3 回答

  • 4

    存在几种技术:

    • 看看编写HTTP请求过滤器 . 然后,如果模式与您不希望直接调用的servlet路径匹配,则可以检查传入的请求和url并拒绝它 .

    • 另一种机制是使用web.xml中的安全性约束来允许仅对授权用户/角色访问应用程序中的各种路径 . 查看 web.xml 中的 <security-constraint> 标签

  • 0

    “Romin”给出的答案是正确的 . 您必须使用过滤器 . 您可以做的是,您可以在访问“/ Demo”URL时设置新的会话变量,并在过滤器中检查会话存在的条件,如果存在则允许url或者抛出错误 . 你可以做类似的事情 . 在“Demo”servlet中

    @WebServlet("/Demo")
    public class DemoServlet extends HttpServlet {  
    
        public void doGet(HttpServletRequest req, HttpServletResponse res)  
                throws ServletException, IOException {  
            HttpSession session = request.getSession() //get new session
            res.sendRedirect("testing"); //calling other servlet 
        }  
    }
    

    在Filter类中添加以下代码

    @WebFilter("/login")
     public class MyFilter implements Filter{  
    
        public void init(FilterConfig arg0) throws ServletException {}  
    
        public void doFilter(ServletRequest req, ServletResponse resp,  
            FilterChain chain) throws IOException, ServletException {  
    
            HttpRequest request = (HttpRequest) req;
            HttpResponse respone = (HttpResponse) res;
    
            HttpSession session = request.getSession(false) //get the existing session object
            if(null != session) {
             chain.doFilter(req, resp);
            } else {
               "redirect to some error page or home page"
            }  
        }
            public void destroy() {}  
    }
    
  • 1

    一种方法是使用ServletRequest.getRemoteAddr()检查呼叫者的ip,如果没有在本地调用则拒绝它

    public void doGet(HttpServletRequest req, HttpServletResponse res)  
                throws ServletException, IOException {  
      if(!req.getRemoteAddr().equals("127.0.0.1")) { // reject }
    }
    

    但是这种方法不起作用合法调用者(例如:proxy)也使用相同的ip .

相关问题