1

Alright what I do now is that I link DIRECTLY to the JSP page(so lets say index.jsp) and when I want to do a doPost I would link it to the Servlet in a form.

But I have been experimenting and I realized that I can link directly to the servlet and use .include() to put the jsp code in the servlet.

What is the best practice?

1 Answers1

3

It isn't a good practice to put JSP code directly into yours Servlets, once any requirement change will make you to alter also the Servlet, beside JSP's.

Assuming your jsp's will act as a view to the user (using the MVC pattern), you better to separate the responsibilities and make your code cleaner.

It's commonly used request.getRequestDispatcher("view.jsp").forward(); to dispatch the request to the JSP, then JSP can be THE VIEW, while your Servlet can be THE CONTROLLER. Alternatively, you can use the response.sendRedirect("view.jsp"); to do that.

What you have to understand is that, using the first one, the webcontainer will dispach the request without any change to the end user. Using the second one, the work for "redirect" is made with the user web browser, so he/she could notice tan URL change.

Andrew Ribeiro
  • 666
  • 1
  • 7
  • 18
  • This is really interesting! So what you are saying is that Servlet = Controller, JSP = view? – Ryan Susana Jun 23 '16 at 19:43
  • 1
    You can assume it! Thanks to the Java Web Structure, it's very simple to assume Servlet as a controller and JSP as a view in the MVC Design Pattern. – Andrew Ribeiro Jun 23 '16 at 19:46
  • I never thought of it like this! thank you kind sir! This just made my life a whole lot easier! On to the web! – Ryan Susana Jun 23 '16 at 19:48
  • When your application starts to grow up, you will see the problem that is to treat this structure in different way. Mix any view code to controller code is always a terrible idea. – Andrew Ribeiro Jun 23 '16 at 19:55