开发者

What is a right way to use servlets?

I'm studying EJB3.

I have a session bean which provides services to create/update customer accounts.

This session bean offers services on the lines of:

public void addCustomer(Customer c);
public void updateCustomer(Customer c);

Ideally I'd like to have a single servlet: CustomerServlet and it would invoke the session beans that I have listed above.

Problem is that I have two JSPs: UpdateAccount.jsp and CreateAccount.jsp. Both of these JSPs have a form with a method POST and action "CustomerServlet".

How can I distinguish in a customer servle开发者_JAVA百科t which operation I should carry out: createAccount or updateAccount?

I guess the alternative is to have a separate servlet for each operation...

Thank you


I'm not really certain about the best practice for this but I have a couple of suggestions that might work:

  1. If your form is being submitted using a submit button, you could distinguish the request on the basis of the value of the <button-name> parameter. So if your buttons had the values Update and Create and were named account-submit, by checking the value you get with request.getParameter('account-submit'), you'd be able to tell which button was clicked to generate this request. If you named them differently, you could also just check which of the two parameters was not null and you'd know which form submit you were handling.

    Note that if you have only a single text field in your form and the user hits Enter instead of clicking the button, you'll get a null in your servlet! See my blog post about this behaviour.

  2. Check the Referer header - I wouldn't really recommend this since you wouldn't always know the context of the deployed app, this value may not always be present and it can be easily spoofed.

  3. Add another mapping for your servlet so that it's accessible at both http://myapp.example.com/context/create and http://myapp.example.com/context/update. You can then check the ServletPath (request.getServletPath()) to see what 'servlet' the request came in for. I'd probably go with this one since it seems the most robust to me but you might also want to add the other two checks just to make sure. In your web.xml, you'd want something like

    <servlet>
        <servlet-name>CreateUpdateServlet</servlet-name>
        <servlet-class>my.package.CustomerServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>CreateUpdateServlet</servlet-name>
        <url-pattern>/create</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>CreateUpdateServlet</servlet-name>
        <url-pattern>/update</url-pattern>
    </servlet-mapping>


JSPs are Servlets, just in a different source code form, there is no reason to POST to a different Servlet, you can just POST back to the same JSP.


You don't need the servlet. JSPs (or Facelets) can talk directly to the beans via EL.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜