Chapter 11 - PowerPoint PPT Presentation

1 / 38
About This Presentation
Title:

Chapter 11

Description:

Includes headers and cookies. SSL. Handle all errors. Keep servers patched and audit them. Tomcat Realms. JDBC, JNDI, Memory. Web Development ... – PowerPoint PPT presentation

Number of Views:34
Avg rating:3.0/5.0
Slides: 39
Provided by: brian171
Category:
Tags: chapter | patched

less

Transcript and Presenter's Notes

Title: Chapter 11


1
Chapter 11 12 Review
  • WAR files
  • Protect JSPs in WEB-INF
  • Security
  • Use tools system source code scanners
  • Validate/Scrub all user input
  • Includes headers and cookies
  • SSL
  • Handle all errors
  • Keep servers patched and audit them
  • Tomcat Realms
  • JDBC, JNDI, Memory

2
Filters
  • Apply to any resource (JSP/Servlet)
  • Prior to the request
  • After the response (prior to client receipt)
  • Lots of choices with filters
  • Invoke the resource normally
  • Modify the request then invoke
  • Invoke the resource but modify the response
  • Block the resource invocation
  • Redirect to a different resource
  • Return a status code
  • Generate its own output

3
Filter Steps
  • Implement the filter interface
  • doFilter(), init(), destroy()
  • Call doFilter() on the filter chain
  • Register the filter in web.xml

4
Logging Filter
  • package aacc
  • import java.io.
  • import javax.servlet.
  • import javax.servlet.http.
  • public class LogFilter implements Filter
  • private FilterConfig config
  • private ServletContext context
  • private String filterName
  • public void init(FilterConfig config) throws
    ServletException
  • this.config config
  • context config.getServletContext()
  • filterName config.getFilterName()
  • public void doFilter(SerlvetRequest request,
    ServletResponse response,
  • FilterChain chain) throws
    ServletException, IOException
  • HttpServletRequest req (HttpServletRequest)
    request
  • context.log(req.getRemoteHost() accessed
    req.getRequestURL()

5
Filter Notes
  • doFilter is not passed a HttpServletRequest
    HttpServletResponse object
  • Cast them if you need Http things
  • doFilter
  • Only pass the request and response
  • chain is a FilterChain object, not a Filter
  • Provides no access to ServletContext
  • Store the context in init() from the FilterConfig

6
web.xml
  • ltweb-appgt
  • ltfiltergt
  • ltfilter-namegtLoggerlt/filter-namegt
  • ltfilter-classgtaacc.LogFilterlt/filter-classgt
  • lt/filtergt
  • ltfilter-mappinggt
  • ltfilter-namegtLoggerlt/filter-namegt
  • lturl-patterngt/lt/url-patterngt
  • lt/filter-mappinggt
  • lt/web-appgt

7
Filter Initialization Parameters
  • Just like servlets
  • ltfiltergt
  • ltfilter-namegtLoggerlt/filter-namegt
  • ltfilter-classgtaacc.LogFilterlt/filter-classgt
  • ltinit-paramgt
  • ltparam-namegtmaxEntrieslt/param-namegt
  • ltparam-valuegt1000lt/param-valuegt
  • lt/init-paramgt
  • lt/filtergt
  • Accessing Init Params
  • public void init(FilterConfig config) throws
    ServletException
  • this.config config
  • context config.getServletContext()
  • filterName config.getFilterName()
  • maxEntries Integer.parseInt(config.getInitPa
    rameter(maxEntries))

8
Response Filters
  • Redirecting or Creating New Output (Easy)
  • public void doFilter(SerlvetRequest request,
    ServletResponse response,
  • FilterChain chain)
    throws ServletException, IOException
  • HttpServletResponse res
    (HttpServletResponse) response
  • if (checkForRedirect)
  • res.sendRedirect(http//www.yavel.c
    om/webprog)
  • else if (checkForError)
  • PrintWriter out res.getWriter()
  • out.println(lthtmlgtltbodygtlth1gtAn
    error occurred!lt/bodygtlt/htmlgt)
  • out.close()
  • else // Proceed as usual
  • chain.doFilter(request, response)
  • Modifying Servlet/JSP Output (Harder)

9
Filter Response Steps
  • Create a response wrapper
  • Extend HttpServletResponseWrapper
  • Buffer the output with a special PrintWriter
  • Pass the wrapper to the filter
  • Extract and modify the output
  • Send the modified output to the client

10
Reusable Response Wrapper
  • package aacc
  • import java.io.
  • import javax.servlet.
  • import javax.servlet.http.
  • public class CharArrayWrapper extends
    HttpServletResponseWrapper
  • private CharArrayWriter charWriter
  • public CharArrayWrapper(HttpServletResponse
    response)
  • super(response)
  • charWriter new CharArrayWriter()
  • public PrintWriter getWriter()
  • return(new PrintWriter(charWriter))
  • public String toString()
  • return(charWriter.toString())

11
Compression Filter
  • public void doFilter(SerlvetRequest request,
    ServletResponse response,
  • FilterChain chain) throws
    ServletException, IOException
  • HttpServletRequest req (HttpServletRequest)
    request
  • HttpServletResponse res (HttpServletResponse)
    response
  • if (!isGzipSupported(req))
  • chain.doFilter(request, response)
  • else
  • res.setHeader(Content-Encoding, gzip)
  • CharArrayWrapper responseWrapper new
    CharArrayWrapper(res)
  • chain.doFilter(request, responseWrapper)
  • char responseChars responseWrapper.toCharA
    rray()
  • ByteArrayOutputStream byteStream new
    ByteArrayOutputStream()
  • GZIPOutputStream zipOut new
    GZIPOutputStream(byteStream)
  • OutputStreamWriter tempOut new
    OutputStreamWriter(zipOut)
  • tempOut.write(responseChars)
  • tempOut.close()
  • res.setContentLength(byteStream.size())
  • OutputStream realOut res.getOutputStream()
  • byteStream.writeTo(realOut)

12
Enterprise Design Patterns
  • Business Delegate
  • Service Locator
  • Transfer Object
  • Intercepting Filter
  • Model, View, Controller (MVC)
  • Front Controller

13
Enterprise Design Patterns
  • Business Delegate
  • Hide the complexity of remote calls
  • A proxy
  • Handles remote protocols exceptions
  • Service Locator
  • Used by Business Delegates for lookups
  • Will cache previously obtained references
  • Handles remote changes (server/container)

14
Enterprise Design Patterns
  • Transfer Object
  • A java bean for bulk transfer
  • Minimize network traffic/calls
  • Intercepting Filter
  • Modify request prior to reaching the webapp
  • Modify response prior to reaching the client
  • Can be chained

15
Enterprise Design Patterns
  • Model, View, Controller (MVC)
  • Separate code into
  • Model The data
  • Hides complexities from the view controller
  • View The display
  • Can interchange for different views of the model
  • Independent of the controller
  • Controller
  • Easy to swap models/views in and out
  • Front Controller
  • Keeps request processing code together
  • Found in most frameworks (you dont usually write)

16
Struts
  • The Apache Struts Framework is a formal MVC
    approach to Servlets and JSP
  • http//struts.apache.org
  • Struts is composed of
  • A controller servlet
  • Beans, other Java classes
  • Configuration files to glue these things together
  • Tag libraries for presentation
  • A little complicated for simple web applications

17
Example
  • Well use a simple form with well known controls.
  • When the page is submitted it should redisplay
    itself without losing the data that was entered.

18
Download Install Struts
  • http//struts.apache.org/download.cgi
  • Unzip and copy all the .war files in the
    extracted apps subdirectory to the Tomcat webapps
    subdirectory
  • struts-blank-1.3.5.war, struts-examples-1.3.5.war,
    struts-mailreader-1.3.5.war,
  • Restart Tomcat and access the webapps
  • use localhost8080 if you are trying on your
    computer
  • http//localhost8080/struts-blank-1.3.5
  • http//localhost8080/struts-examples-1.3.5
  • you can guess the rest

19
Directories (struts-blank.war)
  • Contains meta information. Used by utilities etc.
  • This is where you place your Java classes.
  • Contains the messages (fixed texts) of the
    application.
  • Error messages are also put here.
  • Contains the Struts servlet, helper classes,
    taglib code etc.
  • The Struts tag libraries.
  • A Struts configuration file.
  • The usual configuration file for the servlet
    container.
  • The jsp-files (and html-files) may be placed in
    the root of
  • the application directory

20
A New Web Application
  • The easiest way to start a new Struts application
    is to take an existing application (struts-blank)
    and make a copy of it in the "webapps" directory.
  • Unzip struts-blank.war to ltTomcatgt/webapps/strutsD
    emo
  • Now well start modifying the contents of the
    files

21
web.xml (no need to modify)
  • http//vader.aacc.edu/bcl/samples/struts-web.xml
  • Notice!
  • The definition of the Struts servlet named
    "ActionServlet"
  • The URL mapping for the calls to this servlet
  • The definitions of the Struts tag libraries
  • The servlet will be called for all requests to
    the pattern ltsome-namegt.do
  • When submitting the form in our one-page sample
    application we'll use the action-name "submit.do"

22
Flow of Control
  • The Struts servlet will automatically transfer
    the data from a form into a JavaBean supplied by
    you.
  • This bean is called the ActionForm bean
  • The bean must extend the Struts "ActionForm"
    class.
  • You may think of this bean as a buffer between
    the browser and your data.
  • The ActionForm bean may also be used to
    initialize form controls and to validate the data
    entered by the user.

23
Flow of Control
  • Next the Struts servlet will call a class which
    you specify and it is referred to as the Action
    class.
  • This class may use the data in the ActionForm
    bean.
  • The Action class is where your application coding
    starts.
  • When your class finishes it returns control to
    the Struts servlet.

24
struts-config.xml
  • Maps the requests (ltsome-namegt.do) to a specific
    Action and ActionForm class
  • For our sample application well use a stripped
    down version
  • http//vader.aacc.edu/bcl/samples/struts-config.x
    ml
  • The form-beans section
  • Give the bean a logical name (referred to in the
    action-mapping) and specify the path for the
    class file.

25
struts-config.xml
  • The action-mappings
  • path - name of the request "submit.do". You
    don't enter the ".do"-part here.type - the path
    for the Action class filename - is the logical
    name of the form bean (from the form-bean
    section)input - validation errors should be
    shown on this pagescope - specifies how long the
    form bean should live. You may specify "session"
    instead.
  • The forward tag tells the servlet where to go if
    it receives either "success" or "failure" from
    the Action class.
  • In our simple case we always return to the same
    page.

26
Build the JSP
  • The ActionForm must use Struts' own tags for
    creating the HTML form and the controls in it
  • They are modeled after the "real" HTML-tags.
  • http//vader.aacc.edu/bcl/samples/submit.jsp
  • The 3 taglib lines define the Struts tag
    libraries
  • This jsp-file only uses the html-library.
  • The htmlerrors section is used to display
    validation errors
  • Most of the well-known HTML-attributes for the
    controls (for example JavaScript events) can also
    be used with Struts tags.
  • Note that Struts insists on using the word
    "property" instead of the more familiar "name".

27
ActionForm
  • http//vader.aacc.edu/bcl/samples/SubmitForm.java
  • This class is placed in
  • WEB-INF/classes/aacc/strutsDemo

28
Action Class
  • The Action class is the heart of the application.
  • Here you must decide how you'll separate your own
    application code .
  • Keep this class lightweight
  • Place business logic in other beans or even EJB's
    on other servers.

29
Action Class
  • The implementation of the Action class must
    contain a execute" method
  • It receives the request and response objects, the
    instance of the ActionForm bean and the action
    mapping information from the configuration file.
  • Well use a very simple Action class, which
    simply lets the request pass unaltered
  • http//vader.aacc.edu/bcl/samples/SubmitAction.ja
    va
  • Put the class in WEB-INF/classes/aacc/strutsDemo

30
Action Class
  • The manipulation of the "last name" value is only
    done to show how to access the form bean and how
    you might store data for use by other components
  • Well use it to later
  • "success is returned
  • Specified in the Struts config file it points to
    the submit.jsp file
  • Struts only creates a single instance of the
    Action class which is shared amongst all users of
    the application
  • Dont use member variables and if used make sure
    to synchronize

31
Testing the Sample
  • Restart Tomcat
  • Go to
  • http//localhost8080/strutsDemo/submit.jsp
  • Or see my version at http//vader.aacc.edu8080/st
    rutsDemo/submit.jsp
  • If it works, you'll see that "Last Name" is
    filled with Levay"
  • Means Struts has already created an instance of
    the ActionForm bean, and extracted the data from
    it.
  • Fill in the form and press "Submit".
  • Note that the URL changes to "submit.do", and
    that all data stays unchanged in the form.
  • Try the form with bad data
  • Like single and double quotes, or the "lt" and "gt"
    characters
  • Struts handles them correctly.
  • Use "view source"

32
Using the Struts taglibs
  • In the SubmitAction we stored the users last name
    in uppercase in the request object.
  • Lets display this name as a greeting to the
    user.
  • At the bottom of the submit.jsp file well add
  • ltlogicpresent name"lastName scope"request"gt
  • Hello
  • ltlogicequal name"submitForm" property"age"
    value"a"gt
  • young
  • lt/logicequalgt
  • ltlogicequal name"submitForm" property"age"
    value"c"gt
  • old
  • lt/logicequalgt
  • ltbeanwrite name"lastName" scope"request"/gt
  • lt/logicpresentgt

33
Using the Struts taglibs
  • ltlogicpresent name"lastName" scope"request"gt .
    . . lt/logicpresentgt
  • Only if the name "lastName" is present in the
    request object we'll evaluate what's inside the
    opening and closing tags.
  • Therefore nothing will show up until the
    execute" method is called.
  • ltlogicequal name"submitForm"  property"age"
     value"a"gt young lt/logicequalgt
  • If the property "age" in the ActionForm bean has
    the value "a" (age 0-19) the text "young" is sent
    to the browser.
  • ltbeanwrite name"lastName" scope"request"/gt
  • Sends the value of the "lastName" attribute in
    the request object to the browser.
  • http//vader.aacc.edu/bcl/samples/submitToo.jsp
  • http//localhost8080/strutsDemo/submitToo.jsp
  • Or see my version at http//vader.aacc.edu8080/st
    rutsDemo/submitToo.jsp

34
Input Validation
  • Force the user to enter their last name, address,
    sex and age.
  • Add a validate() method to the ActionForm bean
  • http//vader.aacc.edu/bcl/samples/SubmitForm.java
  • The servlet controller will check if the returned
    ActionErrors object is empty or not.
  • If not empty the controller will return to the
    page specified by the "input" parameter in the
    config file. In our example this is the
    submit.jsp page.

35
Input Validation
  • Define the error message text
  • The error messages are taken from the
    application.properties file. The messages are
    inserted in the jsp-page using the Struts tag
    lthtmlerrors/gt.
  • To format nicely it is best to define
    errors.header and errors.footer.
  • Put in WEB-INF\classes\MessageResources.properties
  • http//vader.aacc.edu/bcl/samples/MessageResource
    s.properties
  • Restart the servlet container.
  • Test the validations
  • http//localhost8080/strutsDemo/submit.jsp
  • Or see my version at http//vader.aacc.edu8080/st
    rutsDemo/submit.jsp

36
The Complete Picture
37
Struts Finale
  • There's a lot more to Struts
  • This example just shows the basic architecture
  • The architecture is loosely coupled
  • There are no hardcoded file names or class names
    in the controller or in the Action or ActionForm
    classes.
  • If all text is placed in the application.propertie
    s file, multi-lingual support is easier!

38
Other Frameworks
  • Spring
  • http//www.springframework.org/
  • Tapestry
  • http//tapestry.apache.org/
  • Wicket
  • http//wicket.sourceforge.net/
  • Java Server Faces
  • http//java.sun.com/javaee/javaserverfaces/
  • Shale
  • http//shale.apache.org/
Write a Comment
User Comments (0)
About PowerShow.com