The below is inspired by the Beer Selector from Head First Java.

3.1 Code a controller using a servlet

package com.example.web;
 
import com.example.model.BeerExpert;
 
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.List;
 
public class BeerSelect extends HttpServlet {
    public void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws IOException, ServletException {
 
        String c = request.getParameter("color");
        BeerExpert be = new BeerExpert();
        List<String> result = be.getBrands(c);
 
        request.setAttribute("styles", result);
        RequestDispatcher view = request.getRequestDispatcher("result.jsp");
        view.forward(request, response);
    }
}

In web.xml:

  <servlet>
    <servlet-name>Ch3 Beer</servlet-name>
    <servlet-class>com.example.web.BeerSelectServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>Ch3 Beer</servlet-name>
    <url-pattern>/SelectBeer.do</url-pattern>
  </servlet-mapping>



3.2 Code a view using a JSP

<%@ page import="java.util.*" %>
<html>
<body>
<h1>Beer Recommendations JSP</h1>
<p>
<%
    List<String> styles = (List<String>)request.getAttribute("styles");
 
    for(String style: styles) {
        out.print("<br>try: " + style);
    }
%>
</body>
</html>



3.3 Forward control from a servlet to a JSP

See servlet above. The relevant part is:

        request.setAttribute("styles", result);
        RequestDispatcher view = request.getRequestDispatcher("result.jsp");
        view.forward(request, response);



3.4 Understand fundamentals of EL

See also:

  • Expression Language (EL) works on beans and collections. This is important to keep in mind, especially for method invocation and indexing.
  • ${expression} performs immediate evaluation on expression. #{} is for deferred evaluation.
  • There are 2 types of expression: value expression and method expression
  • There are 2 types of notation: . or []

Beans and maps

${customer.name} <%-- calls getName() --%>
${customer.member} <%-- calls isMember() --%>
${customer["name"]}

Arrays and Lists

${customer.orders[1]}



3.5 Implement a simple MVC system

The model is below, and the view and controller above.

package com.example.model;
import java.util.*;
 
public class BeerExpert {
    public List<String> getBrands(String color) {
        List<String> brands = new ArrayList<>();
        if (color.equals("amber")) {
            brands.add("Jack Amber");
            brands.add("Red Moose");
        }
        else {
            brands.add("Jail Pale Ale");
            brands.add("Gout Stout");
        }
        return(brands);
    }
}






Comments

If you have questions, corrections, information or examples to add, please comment below.

Add a New Comment