简体   繁体   中英

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). How can I use only one servlet for both? I'am asking this because both use doPost, so I made two servlet's.

In case you want to use a single servlet, you should implement Front Controller Pattern . For this, you will parse the request URL and decide which action should be performed:

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.

Another more naive and harder-to-maintain implementation is by sending an action parameter. This may be a problem because an attacker may use a proxy and change the action parameter before sending the request to the URL. If this is a recognized valid action , and the attacker knows what to send, then you're in trouble.

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).

You could add an extra parameter (eg action ) in your post method

  • 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

and based on its value perform the appropriate actions:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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