Learn Java for Web Development

(Tina Meador) #1
CHAPTER 3: Best Practices in Java EE Web Development 107

applications can be made reusable, maintainable, and extensible by using Java EE web tier patterns.
Next, the chapter shows how web frameworks relinquish you from using Java EE web tier patterns
by providing you out-of-the-box best-practice solutions.


Best-Practice Solutions: Using EL and JSTL


Sun released the Servlet specification in 1998. The sole purpose of servlets was to help the Java
web server generate dynamic content for the client. Listing 3-1 illustrates what the first servlet
looked like.


Listing 3-1. The First Servlet


1.import java.io.IOException;
2.import java.io.PrintWriter;
3.
4.import javax.servlet.ServletException;
5.import javax.servlet.http.HttpServlet;
6.import javax.servlet.http.HttpServletRequest;
7.import javax.servlet.http.HttpServletResponse;
8.public class Hello extends HttpServlet {
9.public void doGet(HttpServletRequest req, HttpServletResponse res)
10.throws ServletException, IOException {
11.res.setContentType ("text/html");
12.PrintWriter out = res.getWriter();
13.out.println("");
14.out.println("Hello World");
15.out.println("");
16.out.println("Hello World");
17.out.println("");
18.}
19.}


Servlets worked fine for dynamic content generation but had one big problem. The view was
hardwired into the servlet, as you can see in lines 13 to 17 in Listing 3-1. To solve this problem, JSP
was born. JSP removes the need of hardwiring the view code into the business logic code. This
separation of the view concern from the business-logic concern depends on the attributes shown in
Listing 3-2 and Listing 3-3.


Listing 3-2. Using Attributes for Separation of Presentation(View) from Business(Servlet) Code


1.public void doPost(HttpServletRequest request, HttpServletResponse response)
2.throws IOException, ServletException {
3.String name = request.getParameter("userName");
4.request.setAttribute("name", name);
5.RequestDispatcher view = request.getRequestDispatcher("/result.jsp");
6.view.forward(request, response);
7.}

Free download pdf