Server-Side Web Programming: Java Servlets and The Control-View Architecture
Server-Side Web Programming: Java Servlets and The Control-View Architecture
Web Programming
Lecture 5:
Java Servlets and the
Control-View Architecture
The Control-View Architecture
• Different user input might require different
response pages
– Different types of request
– Errors/missing field values, etc.
• Example: missing fields in Widget order
The Control-View Architecture
• Bad solution: single JSP with lots of conditions
JSP
converted Redirect to
to html appropriate
Response
response
html JSP page
The Control-View Architecture
• Servlets usually act as controls
– Categorize request based on the parameters and
possibly other factors (database info, etc.).
– Decide which JSP should be sent back as response.
– Forward control (and request data) to that JSP.
dispatcherObject.forward(request, response);
Transfer control
Both the request
using the
and response must
dispatcherObject
be passed so the
JSP has access to
parameters, etc.
Redirection Example
• index.jsp prompts for quantity, name, email
• Upon submit, invokes Validate.java servlet
• If all information present, forward to receipt page
• Otherwise forward to error page
Validate.java
servlet
Redirection Example
public class Validate extends HttpServlet {
protected void processRequest(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String url = ""; // url to forward to
// If any are empty, set the url to forward to to the error page.
// Otherwise, forward to the normal reciept
if (name.equals("") || email.equals("") || quantity.equals("")) {
url = "/error.jsp";
}
else {url = "/reciept.jsp";}
// Create the dispatcher from the url and perform the forward
RequestDispatcher dispatcher =
getServletContext().getRequestDispatcher(url);
dispatcher.forward(request, response);
}
Passing Information to the JSP
• Information can be passed from a servlet to the JSP it
forwards to
• Added to request object as an attribute
– Like a parameter, has name and a value
– Value can be any Java object (not just a string)
Request Request
parameter=value
parameter=value
servlet parameter=value JSP
parameter=value
… attribute=value
…
Passing Information to the JSP
• Adding attribute in servlet:
request.setAttribute(“name”, some object);
WidgetSite Validate
– Note: may not need sitename in NetBeans, but may not work
when deployed otherwise
– Often done for modular multistage redirection
JSP for
request Validation Error standard
servlet JSP configuration