0% found this document useful (0 votes)
90 views31 pages

Struts

This document provides an overview and summary of a presentation on web development using the Struts API. The presentation covers background on servlets and JSPs, the MVC pattern, and an introduction to the Struts framework. It outlines the key components of Struts including the controller, actions, forms, and views. It also summarizes the typical request flow and how each component fits together.
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
90 views31 pages

Struts

This document provides an overview and summary of a presentation on web development using the Struts API. The presentation covers background on servlets and JSPs, the MVC pattern, and an introduction to the Struts framework. It outlines the key components of Struts including the controller, actions, forms, and views. It also summarizes the typical request flow and how each component fits together.
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 31

Welcome To PhillyJUG

6:30 - 7:00 pm - Network, eat, find a seat


7:00 - 7:15 pm - Brief announcements
7:15 - 8:30 pm - Tom Janofsky's presentation
Web Development With
The Struts API

Tom Janofsky
Outline
Background (Servlets and JSPs)
JSP Design
MVC and JSP Model 2
Struts
Into the Future
Java Web Development

HTTP Request

HTTP Response

Browser Web Server


Java Servlets
execute quickly
portable
integrate well with Java back-end
use familiar CGI style and Java API
difficult to maintain
Java Servlets
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class SimpleServlet extends HttpServlet {

public void doGet (HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException
{
PrintWriter out;
String title = "Simple Servlet Output";

// set content type and other response header fields first


response.setContentType("text/html");

// then write the data of the response


out = response.getWriter();
out.println("<HTML><HEAD><TITLE>");
out.println(title);
out.println("</TITLE></HEAD><BODY>");
out.println("<P>This is the output from SimpleServlet.");
out.println("</BODY></HTML>");
out.close();
}
}
Java Server Pages

JSP file

Generated
Pre-processed Servlet

Servlet
Compiled .class file
JSP
Snippets of Java in HTML
Processed into servlets
Display easier to maintain
Much like ASP
"JSP technology should be viewed as
the norm while the use of servlets will
most likely be the exception." (Sun in
1999)
JSP
<%@ page info="Books" errorPage="error.jsp" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html><head><title>Book Page</title></head><body>
<h1>Book Form</h1>
<jsp:useBean id="bookBean" class="BookForm" scope="request"/>
<table>
<tr><td>Title:</td>
<td><input name="title" type="text" value='<jsp:getProperty name="bookBean" property="title"/>'</td></tr>
<tr><td>Author:</td>
<td><input name="author" type="text" value='<jsp:getProperty name="bookBean" property="author"/>'></td></tr>
<tr><td>Publisher:</td>
<td><input name="publisher" type="text" value='<jsp:getProperty name="bookBean" property="publisher"/>'></td></tr>
<tr><td>Year:</td>
<td><input name="year" type="text" value='<jsp:getProperty name="bookBean" property="year"/>'></td></tr>
<tr><td>URL:</td>
<td><input name="url" type="text" value='<jsp:getProperty name="bookBean" property="url"/>'></td>
</table>
<A HREF="/clearBook.jsp">Clear form</A><BR>

Problems with JSP
Mixing of code and display still not easy
to maintain
Tempting to put too much Java code in
the JSP (tightly coupled)
Embedded logic flow
Difficult to debug
Still no framework for designing a web
application
JSP Model I
JSP page processes request and
returns response to client
Separates content from presentation
using JavaBeans
Forms are submitted to the pages that
create them
JSP Model I

Request

HTTP JSP page

Response
Browser
JavaBean Datastore

JSP/Servlet Container
Problems with JSP
Model I
Uses much scriplet code in JSP
Pages can be large and complicated
Still embeds navigation in page
Boundaries of responsibility are still
unclear.
Can lead to spaghetti code
Tends not to be modular
JSP Model II
Implements an MVC approach to web
development
Separates presentation from processing
from data
Clearly delineates responsibility
Change layout without changing code
What is MVC?
A design pattern used to separate business
logic from user interface, from program flow
View
 How data is presented to the user
Model
 Data or state within the system
Controller
 Connects the model and the view. Handles
program flow.
MVC

JSP (View) Model

Response

Request Controller Datastore

Browser
Struts
Open source implementation of an MVC framework
by the Apache group (jakarta.apache.org)
Contains
 Controller (servlet)
 “Action” classes
 Custom JSP tag libs
 Utility classes for XML processing and JavaBean
population
Version 1.0 released this spring
Under active development
Struts Components
Controller – The ActionServlet is responsible
for dispatching all requests. Mappings to
actions are defined in the struts-config.xml file
Action – Actions are defined by extending the
Action class. Actions perform actual work.
Model – The ActionForm can be extended to
provide a place to store request and response
data. It is a JavaBean (getters/settters)
View – JSP pages utilizing Struts tag libraries.
Struts UML
Struts Flow
HTTP Request

ActionServlet Action EJB/DB

reads
Browser struts-config.xml

JSP ActionForm

HTTP Response
The View
You can begin your Struts app by
creating the view in a JSP page
Use struts taglibs for form elements
Implement logic using built in equals,
present, notPresent, and iterate tags
View Example
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %>
<head>
<title>Page Title</title><html:base/></head>
<html:form action=“action.do">
<html:text property="name" size=“50" maxlength=“50"/>
<logic:equal name=“sampleForm" property="currentAction" value="Add">
<html:text property=“description" size="100" maxlength="100"/>
</logic:equal>
</table>
</html:form>
<logic:iterate id=“names" name=“sampleForm" property=“nameList">
<TR><TD><bean:write name=“names" property=“firstName" /></TD>
</TR>
</logic:iterate>
</body></html>
The Model
Beans should be location agnostic (I.e. they should not have
detailed knowledge of the screen on which they are used.
A field for every control on the page
Extending ActionForm gets you
 Automatic creation

 Automatic population

 Integration with JSP

JavaBean with property getters and setters


Forms can provide default validation by implementing the
validate() method
Model Example
import org.apache.struts.action.*;
import java.util.ArrayList;
public class ErrorMessageForm extends ActionForm {
private String name;
private String description;
private ArrayList names;

public String getName() {


return name;
}
[…]
public ArrayList getNames(){
return names;
}

public void setNames(ArrayList names){


this.names = names;
}

}
The Controller
Translates logical names for mappings via the
struts-config.xml
Controls flow of the application
 Load and instantiates proper beans
 Populates beans with values from requests
 Passes bean to appropriate action
 Uses ActionForward from the result to determine
destination
 Handles errors
 Forwards bean and control to appropriate view or
action (Mapping)
Add entry to struts-
config.xml
<form-beans>
<form-bean
name=“sampleForm"
type=“SampleForm"/>
</form-beans>

<action path="/SamplePage"
type=“SampleAction"
name=“sampleForm"
validate="false"
input="/sample.jsp">
<forward name="success" path="/sample.jsp"/>
</action>
The Action
Actions know where they will be used
They are invoked via their mapping in
the struts-config.xml
They can create ActionErrors on
failures, and return a forward to a
mapping
Action Sample
import org.apache.struts.action.*;
import javax.servlet.http.*;

public final class SampleAction extends Action {

public ActionForward perform( ActionMapping mapping, ActionForm form, HttpServletRequest request,


HttpServletResponse response) throws java.io.IOException, javax.servlet.ServletException {
//cast the form to the bean type
SampleForm sample = (SampleForm) form;
ActionErrors errors = new ActionErrors();
//do something, if there are problems, call errors.add(...);
if( !errors.empty() ) {
saveErrors(request,errors);
return new ActionForward(mapping.getInput());
} else {
sample.setCurrentAction("Add");
return mapping.findForward("success");
}}}
Struts Strengths
Integrates well with J2EE
Open Source
Good taglib support
Works with existing web apps
Easy to retain form state
Unified error handling (via ActionError)
Easily construct processes spanning multiple steps
Clear delineation of responsibility makes long term
maintenance easier (more modular)
Problems with Struts
Fair amount of overhead in learning and
maintaining (may not be suitable for small
projects)
Dynamic properties and client side validation
integration still in the works
Some integration headaches in non-Tomcat
environments
New class of security problems to be aware of
(automatic bean population)
Still fairly young
Into the Future
Java Server Faces (JSR 127)
 Standardize an MVC model
 Create standard GUI framework for tool
vendors
 Provide JavaBeans model for dispatching
client side events to server side code
 Recognizes Struts as resource
 Expert Group includes Craig McClanahan
(Struts originator)

You might also like