Basic of J2EE Servlet

Let’s say I have a web application on server using servlet without any frameworks. I’m little confused about how the classes are produced based on HttpRequest. For example I have this servlet


public class WelcomeServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title> A very simple servlet example</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>"+ (int)(Math.random()*5) +"</h1>");
out.println("</body>");
out.println("</html>");
out.close();
}
}

Questions:

  1. if there are two/more clients access this servlet, Will they receive different instances of this class or only one class to be used by they two? will they get same number?

  2. Is it good idea to use static class on servlet? for example on class that holds constant number/String or SQL query?

  3. I store sensitive info on HttpSession, is it good?

Thanks.

Before you dive into servlets make sure you understand http itself. By its nature it is stateless and if you want to store any kind of state between multiple requests/responses then you need a mechanism to do so e.g. HttpSession.

  1. Each client will have its own instantiation of this servlet on its own thread within the servlet container.

  2. You can but then you’ll need to be aware of threading issues. If you want to share a database connection then it makes more sense to use a database pool and there are frameworks that’ll take care of that for you.

  3. Sure why not? The usual security precautions apply here too e.g. it’s better to store a salted password hash rather than the password itself, yada yada.

By default, for each class of servlets in the container there is only one instance which is used then for handling of all requests to an appropriate servlet. But, if the servlet implements interface SingleThreadModel the container can create several instances of this servlet.

  1. They might get different instances, they might not. You can never guarantee that you get the same servlet instance from request to request even on the same client, or that different clients will get different servlets. You can’t reliably keep state on a servlet for that reason.

  2. It’s not really a good idea. It will probably work on a single node, but it’s guaranteed to not work when clustering.

  3. The session is secure since it’s kept server-side, though if it’s super-sensitive, you’ll still want to ensure a secure connection and authentication before establishing the session you keep the secure data in.

Thanks for your all fast replies. Really help.

Currently I create common class for query, so each time a servlet need data from DB it will create new instance (new QueryClass()) and I leave it to GC after that. I’m storing a “boolean” on session to indicate if someone has logged in or not. No passsword on there so I think it’s safe. I invalidate the session when click logout. Here my last question (maybe not)

Which one better, create one servlet per use case or group it? For example User has 10 pages. Each of them has its own job such as do query, input data, show pre-calculate result etc. I think about two ways,

  • Create 10 servlet for each page to process data on them so they’ll be Page1Servlet.java, Page2Servlet.java etc.
  • Just one servlet with all method combined in one (/servlet/user?do=???) with switch case to manage what method to use and the directive

I think you should combine two these ways. This approach describes wellknown pattern “Model2”.
Roughly speaking, when you using this approach, you have one main servlet (for example ControllerServlet) and many other specific workers (for example, LoginServlet, LagoutServlet, ErrorServlet, RegistrationServlet etc…) and when ControllerServlet received request it must dispatch this request for one predefined servlet, if corresponding servlet doesn’t exist ControllerServler must forward request to ErrorServlet.

If to you is interesting I have uploaded the source codes of the my very old project which hosts on google app engine and used this approach:
https://github.com/cooker/moviebook

I hope, that it will help.

I wouldn’t use raw servlets, but a framework like wicket, stripes, play, or seam, which are all capable of mapping actions to methods on controllers without hardwiring switch/case logic into your servlet. Which one of these you choose is largely a matter of style: play seems to be the most friendly of these, while seam is the big “industrial strength” one.

@matvey:
thank you very much. I just want to know which one is work well in industry. I’m currently using method no.2 and quite enjoy it because it’s neater. So I just guess that I’m on right way now :smiley:

@sproingie:

[quote]Which one of these you choose is largely a matter of style:
[/quote]
I agree. But sometimes world wants otherwise, easy for me hard for you :wink: