简体   繁体   English

仅使用一个servlet

[英]Using only one servlet

I'am making a web page with a login system and backoffice page. 我正在制作一个带有登录系统和后台页面的网页。 The problem is, both use the method "doPost" (the login use to autenticate and the backoffice use to insert data in db). 问题是,两者都使用方法“doPost”(登录用于autenticate,后台用于在db中插入数据)。 How can I use only one servlet for both? 我如何只为两者使用一个servlet? I'am asking this because both use doPost, so I made two servlet's. 我问这个因为两个都使用doPost,所以我制作了两个servlet。

In case you want to use a single servlet, you should implement Front Controller Pattern . 如果您想使用单个servlet,则应实现Front Controller Pattern For this, you will parse the request URL and decide which action should be performed: 为此,您将解析请求URL并决定应执行的操作:

public class MySingleServlet extends Servlet {
    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
        String url = request.getPathInfo();
        //returns the action to handle
        Action action = ActionFactory.getAction(url);
        action.process(request, response);
    }
}

This involves an Action interface/abstract class and an ActionFactory that will parse the URL and return the right implementation to handle the actions to do. 这涉及一个Action接口/抽象类和一个ActionFactory ,它将解析URL并返回正确的实现来处理要执行的操作。

Another more naive and harder-to-maintain implementation is by sending an action parameter. 另一个更天真,更难维护的实现是通过发送action参数。 This may be a problem because an attacker may use a proxy and change the action parameter before sending the request to the URL. 这可能是一个问题,因为攻击者可能会在将请求发送到URL之前使用代理并更改action参数。 If this is a recognized valid action , and the attacker knows what to send, then you're in trouble. 如果这是一个公认的有效action ,并且攻击者知道要发送什么,那么您就遇到了麻烦。

Note that there are MVC frameworks that already implement Front Controller Pattern like Spring MVC and JSF, so there's no need to reinvent the wheel unless it is for learning purposes (otherwise, you should use a library that already implements this). 请注意,有一些MVC框架已经实现了像Spring MVC和JSF这样的Front Controller模式,因此除非用于学习目的,否则不需要重新发明轮子(否则,您应该使用已经实现此功能的库)。

You could add an extra parameter (eg action ) in your post method 您可以在post方法中添加额外的参数(例如action

  • retrieved from a hidden form field, if you are using forms, or 如果您正在使用表单,则从隐藏的表单字段中检索
  • added with a simple &action='value' to your request if using xml http request 如果使用xml http请求,则为您的请求添加简单的&action='value'

and based on its value perform the appropriate actions: 并根据其值执行适当的操作:

if (action.equals("auth"))
{
     // authenticate
}
else if (action.equals("backoffice"))
{
    // db update
}

您可以根据路由请求从请求对象获取pathInfo。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM