Jakarta Struts: Declarative Exception Handling

Similar documents
For live Java EE training, please see training courses at

The JSP page Directive: Structuring Generated Servlets

Volume 1: Core Technologies Marty Hall Larry Brown. Controlling the Structure of Generated Servlets: The JSP page Directive

Servlet and JSP Review

Struts interview questions

The Struts MVC Design. Sample Content

Jakarta Struts: An MVC Framework

Struts. P. O. Box Austin, TX Fax: +1 (801) (877) 866-JAVA

Integrating Servlets and JavaServer Pages Lecture 13

Generating the Server Response:

JSP Scripting Elements

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

JSF: Introduction, Installation, and Setup

Servlet Basics. Agenda

Integrating Servlets and JSP: The MVC Architecture

Building Web Applications With The Struts Framework

JSF Page Navigation. The first example we ll look at is available as jsf_ex2a.zip on your notes page.

Dynamic Struts Configuration Dipl.-Inf. Manfred Wolff January 2004

Simplifying GWT RPC with

Jakarta Struts: An MVC Framework

Strecks Java 5 Extensions

Servlets1. What are Servlets? Where are they? Their job. Servlet container. Only Http?

Session 8. Introduction to Servlets. Semester Project

Java Enterprise Edition. Java EE Oct Dec 2016 EFREI/M1 Jacques André Augustin Page 1

INTRODUCTION TO SERVLETS AND WEB CONTAINERS. Actions in Accord with All the Laws of Nature

Upon clicking Place Bid, the business logic of the web application uses a given

Session 9. Introduction to Servlets. Lecture Objectives

Advanced Web Technology - Java Server Faces

JavaEE Interview Prep

The Basic Web Server CGI. CGI: Illustration. Web based Applications, Tomcat and Servlets - Lab 3 - CMPUT 391 Database Management Systems 4

2. Follow the installation directions and install the server on ccc. 3. We will call the root of your installation as $TOMCAT_DIR

Managed Beans III Advanced Capabilities

CS506 Web Design & Development Final Term Solved MCQs with Reference

A.1 JSP A.2 JSP JSP JSP. MyDate.jsp page contenttype="text/html; charset=windows-31j" import="java.util.calendar" %>

JSP Scripting Elements

JDBC [Java DataBase Connectivity]

JavaServer Pages (JSP)

Web based Applications, Tomcat and Servlets - Lab 3 -

Three hours UNIVERSITY OF MANCHESTER SCHOOL OF COMPUTER SCIENCE. Date: Friday 21 st May Time:

Creating Web Application with BEA WebLogic Workshop. Jeff (Yefim) Zhuk

Application Development in JAVA. Data Types, Variable, Comments & Operators. Part I: Core Java (J2SE) Getting Started

JSF & Struts 1, 4, 7, 2, 5, 6, 3 2, 4, 3, 1, 6, 5, 7 1, 4, 2, 5, 6, 3, 7 1, 2, 4, 5, 6, 3, 7

Jakarta Struts. Pocket Reference. Chuck Cavaness and Brian Keeton. Beijing Boston Farnham Sebastopol Tokyo

Author: Sascha Wolski Sebastian Hennebrueder Tutorials for Struts, EJB, xdoclet and eclipse.

Sun Sun Certified Web Component Developer for J2EE 5 Version 4.0

COMP9321 Web Application Engineering

The Google Web Toolkit (GWT):

Servlets. An extension of a web server runs inside a servlet container

Oracle Developer Day

SERVLET AND JSP FILTERS

Stateless -Session Bean

Session 8. JavaBeans. Reading & Reference. Reading. Reference. Session 8 Java Beans. 2/27/2013 Robert Kelly, Head First Chapter 3 (MVC)

Data Service Patterns Jeff Zhuk

Web. 2 Web. A Data Dependency Graph for Web Applications. Web Web Web. Web. Web. Java. Web. Web HTTP. Web

Server-side Web Programming

JavaServer Pages. Juan Cruz Kevin Hessels Ian Moon

Java Server Pages JSP

The Spring Framework: Overview and Setup

HttpServlet ( Class ) -- we will extend this class to handle GET / PUT HTTP requests

4.1 The Life Cycle of a Servlet 4.2 The Java Servlet Development Kit 4.3 The Simple Servlet: Creating and compile servlet source code, start a web

Contents. 1. JSF overview. 2. JSF example

114. Jakarta Struts. Prerequisites. Version 1.1.3

Integrating Servlets and JSP: The Model View Controller (MVC) Architecture

Servlets by Example. Joe Howse 7 June 2011

Configuring Tomcat for a Web Application

To follow the Deitel publishing program, sign-up now for the DEITEL BUZZ ON-

FINALTERM EXAMINATION Spring 2009 CS506- Web Design and Development Solved by Tahseen Anwar

MVC, 2. MVC

Introduction to Servlets. After which you will doget it

Author: Sascha Wolski Sebastian Hennebrueder Tutorials for Struts, EJB, xdoclet and eclipse.

JSF: The "h" Library Originals of Slides and Source Code for Examples:

JAVA SERVLET. Server-side Programming INTRODUCTION

Advanced Internet Technology Lab # 4 Servlets

appendix A: Working with Struts

Servlet Fudamentals. Celsina Bignoli

sessionx Desarrollo de Aplicaciones en Red A few more words about CGI CGI Servlet & JSP José Rafael Rojano Cáceres

Advanced Web Technologies 8) Facelets in JSF

Lab session Google Application Engine - GAE. Navid Nikaein

Frameworks & Security

Table of Contents. Introduction... xxi

xcommand Table of contents Sven Ehrke extended command pattern (for Java) Introduction... 1 How others do it

Java Card 3 Platform. Peter Allenbach Sun Microsystems, Inc.

JavaScript: Functions

COMP9321 Web Application Engineering

Using JavaBeans with JSP

Advanced Action Classes

COE318 Lecture Notes Week 10 (Nov 7, 2011)

Session 24. Introduction to Java Server Faces (JSF) Robert Kelly, Reading.

Oracle EXAM - 1Z Java Enterprise Edition 5 Web Component Developer Certified Professional Exam. Buy Full Product

Java Servlets. Preparing your System

A Quick Introduction to Struts

UNIT 6:CH:14 INTEGRATING SERVLETS AND JSPTHE MVC ARCHITECTURE

Example jsf-cdi-and-ejb can be browsed at

Kamnoetvidya Science Academy. Object Oriented Programming using Java. Ferdin Joe John Joseph. Java Session

Creating Custom JSP Tag Libraries:

Enterprise Java Unit 1- Chapter 3 Prof. Sujata Rizal Introduction to Servlets

web.xml Deployment Descriptor Elements

3. The pool should be added now. You can start Weblogic server and see if there s any error message.

Introduction to Java Server Faces(JSF)

Database Systems Lab. 11. JSP I 충남대학교컴퓨터공학과 데이타베이스시스템연구실

Transcription:

Jakarta Struts: Declarative Exception Handling Struts 1.2 Version Core Servlets & JSP book: More Servlets & JSP book: www.moreservlets.com Servlet, JSP, Struts, JSF, and Java Training Courses: courses.coreservlets.com Slides Marty Hall, http://, books Sun Microsystems Press For live Struts training, please see JSP/servlet/Struts/JSF training courses at http://courses.coreservlets.com/. Taught by the author of Core Servlets and JSP, More Servlets and JSP, and this tutorial. Available at public venues, or customized versions can be held on-site at your organization. Slides Marty Hall, http://, books Sun Microsystems Press

Agenda Transferring to custom error pages when various exception types are thrown Global exceptions Per-Action exceptions Standard web.xml approach Using custom exception handlers Declaring Defining 4 Apache Struts: Declarative Exception Handling Idea Programmatic exception handling Explicit try/catch blocks in any code that can throw exception Works well when custom value (i.e., of variable) needed when error occurs Declarative exception handling Entries in struts-config.xml (or web.xml) indicate what pages should be displayed when various errors occur <exception key="some.key" type="package.someexception" path="/web-inf/somepage.jsp"/> Works well when custom page needed when error occurs The Struts approach applies only to exceptions thrown by Actions 5 Apache Struts: Declarative Exception Handling

Entries in struts-config.xml exception element with 4 possible attributes key: entry in a resource bundle (properties file) used to build an ActionMessage and that can be output with html:errors. Ignored now: see validation section type: the fully qualified class of the exception. The most specific match is used. Applies only to Actions. path: the address (relative to the Web app) of the error page. Should normally be in WEB-INF. handler: the class that will handle the error. Usually omitted, and default handler used. <exception key="errors.null" type="java.lang.nullpointerexception" path="/web-inf/errors/null.jsp"/> Used within global-exceptions or action 6 Apache Struts: Declarative Exception Handling Three Basic Approaches Give page for specific type of exception Use exception entry in global-exceptions or action Give page for generic Exception Use exception entry in global-exceptions, or Use exception-type entry in web.xml, or use error-page attribute of page directive Advantage of page directive: the exception object is bound, so you can print a backtrace Give custom handler for specific type of exception Use exception entry in global-exceptions or action, and Define subclass of ExceptionHandler 7 Apache Struts: Declarative Exception Handling

Handling Specific Exceptions Slides Marty Hall, http://, books Sun Microsystems Press Example 1: Page for NullPointerException struts-config.xml <global-exceptions> <exception key="some.key" type="java.lang.nullpointerexception" path="/web-inf/errors/null.jsp"/> </global-exceptions> null.jsp <!DOCTYPE...> <HTML> <HEAD><TITLE>NullPointerException</TITLE></HEAD> <BODY BGCOLOR="#FDF5E6"> <H1>NullPointerException</H1> Blah, blah, blah, blah. </BODY></HTML> 9 Apache Struts: Declarative Exception Handling

Example 1: Page for NullPointerException (Bean) package coreservlets; import org.apache.struts.action.*; public class ColorBean extends ActionForm { private String foregroundcolor, backgroundcolor; public String getforegroundcolor() { return(foregroundcolor); public void setforegroundcolor(string fgcolor) { if (!fgcolor.equals("")) { foregroundcolor = fgcolor;... 10 Apache Struts: Declarative Exception Handling Example 1: Page for NullPointerException (Action) public class ShowColorsAction extends Action { public ActionForward execute(actionmapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ColorBean colorbean = (ColorBean)form; String fg = colorbean.getforegroundcolor(); String bg = colorbean.getbackgroundcolor(); if (fg.equals(bg)) { colorbean.setforegroundcolor("black"); colorbean.setbackgroundcolor("white");... return(mapping.findforward("success")); 11 Apache Struts: Declarative Exception Handling

Example 1: Page for NullPointerException (Results) 12 Apache Struts: Declarative Exception Handling Example 1: Page for NullPointerException (Results) 13 Apache Struts: Declarative Exception Handling

Handling Generic Exceptions (Struts-Specific Approach) Slides Marty Hall, http://, books Sun Microsystems Press Example 2: Page for Generic Exception struts-config.xml <global-exceptions> <exception key="some.key" type="java.lang.nullpointerexception" path="/web-inf/errors/null.jsp"/> <exception key="some.key" type="java.lang.exception" path="/web-inf/errors/error.jsp"/> </global-exceptions> null.jsp <!DOCTYPE...> <HTML> <HEAD><TITLE>Error</TITLE></HEAD> <BODY BGCOLOR="#FDF5E6"> <H1>Error</H1> Blah, blah, blah, blah. </BODY></HTML> 15 Apache Struts: Declarative Exception Handling

Example 2: Page for Generic Exception (Action) public class ShowColorsAction extends Action { public ActionForward execute(actionmapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ColorBean colorbean = (ColorBean)form; String fg = colorbean.getforegroundcolor(); String bg = colorbean.getbackgroundcolor(); if (fg.equals(bg)) { colorbean.setforegroundcolor("black"); colorbean.setbackgroundcolor("white"); if (bg.equalsignorecase("papayawhip")) { throw(new Exception("Bogus background color!"));... return(mapping.findforward("success")); 16 Apache Struts: Declarative Exception Handling Example 2: Page for Generic Exception (Result) 17 Apache Struts: Declarative Exception Handling

Handling Generic Exceptions (Standard Approaches) Slides Marty Hall, http://, books Sun Microsystems Press Alternatives Using Standard Servlet/JSP Elements Pages to use for specific HTTP status codes Use the error-code element Within error-page Pages to use when specific uncaught exceptions are thrown Use the exception-type element Within error-page Page-specific error pages Use <%@ page errorpage="relative URL" %> In individual JSP page, not in web.xml 19 Apache Struts: Declarative Exception Handling

Error Pages and Status Codes <web-app...> <error-page> <error-code>404</error-code> <location>/web-inf/notfound.jsp</location> </error-page>... </web-app> 20 Apache Struts: Declarative Exception Handling Error Pages and Status Codes: Result 21 Apache Struts: Declarative Exception Handling

Error Pages and Exceptions: A Dangerous Computation package moreservlets; /** Exception used to flag particularly onerous programmer blunders. Used to illustrate the exception-type web.xml element. */ public class DumbDeveloperException extends Exception { public DumbDeveloperException() { super("duh. What was I *thinking*?"); public static int dangerouscomputation(int n) throws DumbDeveloperException { if (n < 5) { return(n + 10); else { throw(new DumbDeveloperException()); 22 Apache Struts: Declarative Exception Handling Error Pages and Exceptions: A Risky Page <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD><TITLE>Risky JSP Page</TITLE></HEAD> <BODY BGCOLOR="#FDF5E6"> <H2>Risky Calculations</H2> <%@ page import="moreservlets.*" %> <% int n = ((int)(10 * Math.random())); %> <UL> <LI>n: <%= n %> <LI>dangerousComputation(n): <%= DumbDeveloperException.dangerousComputation(n) %> </UL> </BODY></HTML> 23 Apache Struts: Declarative Exception Handling

Error Pages and Exceptions: Declaring Error Page for DDE <web-app...> <error-page> <exception-type> moreservlets.dumbdeveloperexception </exception-type> <location>/web-inf/dde.jsp</location> </error-page>... </web-app> 24 Apache Struts: Declarative Exception Handling Error Pages and Exceptions: WEB-INF/DDE.jsp <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD><TITLE>Dumb</TITLE></HEAD> <BODY BGCOLOR="#FDF5E6"> <H2>Dumb Developer</H2> We're brain dead. Consider using our competitors. </BODY></HTML> 25 Apache Struts: Declarative Exception Handling

Error Pages and Exceptions: Results 26 Apache Struts: Declarative Exception Handling Page-Specific Error Pages: Example <BODY> <%@ page errorpage="/web-inf/speederrors.jsp" %> <TABLE BORDER=5 ALIGN="CENTER"> <TR><TH CLASS="TITLE">Computing Speed</TABLE> <%! private double todouble(string value) { return(double.parsedouble(value)); %> <% double furlongs = todouble(request.getparameter("furlongs")); double fortnights = todouble(request.getparameter("fortnights")); double speed = furlongs/fortnights; %> <UL> <LI>Distance: <%= furlongs %> furlongs. <LI>Time: <%= fortnights %> fortnights. <LI>Speed: <%= speed %> furlongs per fortnight. </UL> </BODY></HTML> 27 Apache Struts: Declarative Exception Handling

Page-Specific Error Pages: Example (Continued) <BODY> <%@ page iserrorpage="true" %> <TABLE BORDER=5 ALIGN="CENTER"> <TR><TH CLASS="TITLE"> Error Computing Speed</TABLE> <P> ComputeSpeed.jsp reported the following error: <I><%= exception %></I>. This problem occurred in the following place: <PRE> <%@ page import="java.io.*" %> <% exception.printstacktrace(new PrintWriter(out)); %> </PRE> </BODY></HTML> 28 Apache Struts: Declarative Exception Handling Page-Specific Error Pages: Results 29 Apache Struts: Declarative Exception Handling

Custom Exception Handlers Slides Marty Hall, http://, books Sun Microsystems Press Using Custom Handlers Extend ExceptionHandler Use execute method, but with two extra arguments (Exception and ExceptionConfig) Give custom behavior (recording error in database, sending email, etc.) Return super.execute in most cases Declare handler in struts-config.xml <exception key="some.key" type="pkg.someexception" handler="pkg.someexceptionhandler" path="/web-inf/somefile.jsp"/> 31 Apache Struts: Declarative Exception Handling

Example 3: Custom Handler (struts-config.xml) <global-exceptions> <exception key="some.key" type="java.lang.nullpointerexception" path="/web-inf/errors/null.jsp"/> <exception key="some.key" type="coreservlets.criticalproblem" handler= "coreservlets.customexceptionhandler" path="/web-inf/errors/error.jsp"/> <exception key="some.key" type="java.lang.exception" path="/web-inf/errors/error.jsp"/> </global-exceptions> 32 Apache Struts: Declarative Exception Handling Example 3: Custom Handler (Custom Handler) package coreservlets; import javax.servlet.http.*; import org.apache.struts.action.*; import org.apache.struts.config.*; import javax.mail.*; import javax.mail.internet.*; import java.util.*; import javax.servlet.*; public class CustomExceptionHandler extends ExceptionHandler{ public ActionForward execute(exception exception, ExceptionConfig config, ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws ServletException { 33 Apache Struts: Declarative Exception Handling

Example 3: Custom Handler (Custom Handler, Continued) try { Properties properties = new Properties(); properties.put("mail.host", "coreservlets.com"); Session mailsession = Session.getDefaultInstance(properties, null); MimeMessage mailmessage = new MimeMessage(mailSession); mailmessage.setfrom (new InternetAddress("errors@some-company.com")); mailmessage.setfrom (new InternetAddress("hall@coreservlets.com")); mailmessage.setsubject("error in Struts application"); mailmessage.settext ("The struts-errors app had a critical problem:\n" + " " + exception + "\n\n" + "Get your butt out to the office and fix it NOW."); Transport.send(mailMessage); System.out.println("Sent emergency email."); catch(exception e) { return(super.execute(exception, config, mapping, form, request, response)); 34 Apache Struts: Declarative Exception Handling Example 3: Custom Handler (Custom Exception Class) package coreservlets; public class CriticalProblem extends Exception { public CriticalProblem(String message) { super(message); 35 Apache Struts: Declarative Exception Handling

Example 3: Custom Handler (Action) public class ShowColorsAction extends Action { public ActionForward execute(actionmapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ColorBean colorbean = (ColorBean)form; String fg = colorbean.getforegroundcolor(); String bg = colorbean.getbackgroundcolor(); if (fg.equals(bg)) { colorbean.setforegroundcolor("black"); colorbean.setbackgroundcolor("white"); if (bg.equalsignorecase("papayawhip")) { throw(new Exception("Bogus background color!")); if (Math.random() < 0.1) { String message = "Database server exploded. Building is burning!"; throw(new CriticalProblem(message)); return(mapping.findforward("success")); 36 Apache Struts: Declarative Exception Handling Summary Give page for specific type of exception Use exception entry in global-exceptions or action Give page for generic Exception Use exception entry in global-exceptions, or Use exception-type entry in web.xml, or use error-page attribute of page directive Give custom handler for specific type of exception Use exception entry in global-exceptions or action, and Define subclass of ExceptionHandler 37 Apache Struts: Declarative Exception Handling

Questions? Core Servlets & JSP book: More Servlets & JSP book: www.moreservlets.com Servlet, JSP, Struts, JSF, and Java Training Courses: courses.coreservlets.com Slides Marty Hall, http://, books Sun Microsystems Press