1- Environment setup
Eclipse, MyEclipse, Tomcat, Netmeeting. Textpad, Access
2- J2EE Web Application overview
Any web application that runs in the servlet container is called a J2EE web application. The servlet container implements the Servlet and JSP specification
3- Servlet overview
What is a Servlet ?
A servlet is any class that can be invoked and executed on the server. Unlike applets, which do their work on the client , servlet do their work on the server
What is The Servlet Life Cycle ?
A server loads and initializes the servlet [by invoking init() ]
The servlet handles zero or more client requests [using service() or doXxx()]
The server removes the servlet [by invoking destroy()]
Web Application using Servlets
Back in the days when JSPs didn't exist, servlets were all that you had to build J2EE web applications. They handled requests from the browser, invoked middle tier business logic and rendered responses in HTML to the browser. Now that's a problem. A Servlet is a Java class coded by Java programmers. It is okay to handle browser requests and have business and presentation logic in the servlets since that is where they belong. HTML formatting and rendering is the concern of page author who most likely does not know Java. So, the question arises, how to separate these two concerns intermingled in Servlets? JSPs are the answer to this dilemma.
4- JSP overview
A JSP file is a java Servlet.
A JSP file is nothing more than another way to view a Servlet.
The concept of a JSP file is to allow us to see a Java Servlet as an HTML page.
The JSP file is pre-processed into a .java file, then compiled into a .class file.
JSP technology provides the glue between the page designer and the Java developer.
The Simple Self-contained JSP File
w In a small JSP application, it is common to see the data, business logic, and the user interface combined into one module of code.
w In addition, the application generally contains the logic that controls the flow of the application.
w In a simple request and response, the JSP file:
w Sets the data
w Controls the flow to the next page
w Creates the HTML
w The advantage of the single-page approach is that it is easy to understand and initially easy to build.
w It’s also, with all the graphical development tools, easy to get started.
w Consequences of the single-page approach.
w Heavy HTML and java coupling.
w The coder of the JSP file must be both a page designer and a java developer. The result is often either terrible java code or an ugly page, or sometimes both.
w Embedded flow logic.
w To understand the entire flow of the application, you have to navigate all of the pages. Imagine the spaghetti logic on a 100-page web site.
w Debugging difficulties
w In addition to being ugly to look at, HTML tags, Java code, and JavaScript code all in one page makes it difficult to debug problems.
w Tight coupling
w Changes to business logic or data means possibly touching every page involved.
No More Java Code in My HTML
w Instead of having a lot of HTML in java code (i.e. doing everything in a servlet), we have a lot of java code in an HTML file.
w This doesn’t really accomplish much, other than forcing page designers to write java code.
w All is not lost; with JSP 1.1, we have a new feature called tags.
5- JSP tags and Tag Libraries
A JSP tag is simply a way of abstracting out code from a JSP file.
For the same reason we don’t want to see HTML tags in java code, we don’t want to see java code in a JSP file.
The entire point of JSP technology is to allow the page designer to create JSPs without being distracted with java code.
Tags allow java programmers to extend JSP files by making java code look like HTML.
w The general concept of pulling the code from the JSP page and putting into a JSP tag.
w An example of Struts tag capability:
<form:form action="join.do" focus="email" > <form:text property="email" size="30" maxlength="30"/> <form:submit property="submit" value="Submit"/> </form:form> |
w Resulting HTML sent to the browser:
<form name="joinForm" method="POST“ action="join.do"> <input type="text" name="email" maxlength="30" size="30" value=""> <input type="submit" name="submit" value="Submit"> </form> <script language="JavaScript"> <!-- document.joinForm.email.focus() // --> </script> |
w Notes about JSP tags:
n JSP tags require a container that runs JSP 1.1 or later.
n JSP tags run on the server and are not interpreted by the client like HTML tags are.
n JSP tags provide proper code re-use.
w JSTL tag libraries(JSTL Core, formate, SQL, XML, Function)
<c:set var="browser" value="${header['User-Agent']}"/>
<c:out value="${browser}"/>
New Expression language
<someTags.aTag attribute="${aCustomer.address.country}">
<c:if test="${customer.country == 'Canada'}">
This customer is based in Canada.
</c:if>
6- MVC Design pattern overview
JSP Model 1 and Model 2(MVC) differ essentially in the location at which the bulk of the request processing is performed.
Model 1 |
Model 2 |
nIn the Model 1 architecture the JSP page alone is responsible for processing the incoming request and replying back to the client.
nModel 1 architecture is easy. There is some separation between content (Model JavaBeans) and presentation (JSP).
Model 1
n Problems with Model 1 Architecture
n In Model 1 the JSP contains the controlling logic and presentation logic which leads to Fat Client in the large applications (hardly maintained)
n Application control is decentralized in Model 1 architecture since the next page to be displayed is determined by the logic embedded in the current page. Decentralized navigation control can cause headaches when requirements keep changing.
Model-view-controller (MVC) Design Pattern
w MVC helps resolve some of the issues with the single module approach by dividing the problem into three categories:
n Model.
l The model contains the core of the application's functionality. The model encapsulates the state of the application. Sometimes the only functionality it contains is state. It knows nothing about the view or controller.
n View.
l The view provides the presentation of the model. It is the look of the application. The view can access the model getters, but it has no knowledge of the setters.
n Controller.
l The controller reacts to the user input. It creates and sets the model.
Model 2
w The main difference between Model 1 and Model 2 is that in Model 2, a controller handles the user request instead of another JSP. The controller is implemented as a Servlet.
w The following steps are executed when the user submits the request
w The Controller Servlet handles the user's request. (This means the hyperlink in the JSP should point to the controller servlet).
w The Controller Servlet then instantiates appropriate JavaBeans based on the request parameters (and optionally also based on session attributes).
w The JavaBeans talks to the middle tier or directly to the database to fetch the required data.
w The Controller sets the resultant JavaBeans (either same or a new one) in one of the following contexts - request, session or application.
w The controller then dispatches the request to the next view based on the request URL.
w The View uses the resultant JavaBeans from Step 4 to display data.
w Note that there is no presentation logic in the JSP. The sole function of the JSP in Model 2 architecture is to display the data from the JavaBeans set in the request, session or application scopes.
w Model 2 Advantages.
w Easier to maintain and extend since the views do not refer to each other and there is no presentation logic in the views
w Centralized control and processing logic in the servlet
w Model 2 Disadvantages.
w In medium to large applications, centralized control and processing logic in the servlet - the greatest plus of MVC is also its weakness. Consider a mediocre application with 15 JSPs. Assume that each page has five hyperlinks (or five form submissions). The total number of user requests to be handled in the application is 75. Since we are using MVC framework, a centralized controller servlet handles every user request. For each type of incoming request there is 'if' block in the doGet method of the controller Servlet to process the request and dispatch to the next view. For this mediocre application of ours, the controller Servlet has 75 if blocks.
Even if you assume that each if block delegates the request handling to helper classes it is still no good. You can only imagine how bad it gets for a complex enterprise web application (Fat Controller)
MVC with configurable controller
7- Struts Overview
Struts, an MVC 2 Implementation
w Struts is a set of cooperating classes, servlets, and JSP tags that make up a reusable MVC 2 design.
w This definition implies that Struts is a framework, rather than a library.
w Struts also contains an extensive tag library and utility classes that work independently of the framework.
w Client browser
w An HTTP request from the client browser creates an event. The Web container will respond with an HTTP response.
w Controller
w The Controller receives the request from the browser, and makes the decision where to send the request.
w The struts-config.xml file configures the Controller.
w Model state
w The model represents the state of the application.
w The business objects update the application state.
w The ActionForm bean represents the Model state at a session or request level, and not at a persistent level.
w The JSP file reads information from the ActionForm bean using JSP tags.
w View
w The view is simply a JSP file.
w There is no flow logic, no business logic, and no model information -- just tags.
w Tags are one of the things that make Struts unique compared to other frameworks.
Struts Main Components
w struts-config.xml
w Action Servlet
w Request Processor
w Action Mapping
w Action Form
w Action class
w Action Forward
w Action Errors
Action Servlet
w It is the central component of the struts controller classes
w It performs two important things
1-On start up, its reads the struts configuration file and loads it into memory in the init() method.
2-in the doGet() and doPost() methods, it intercept HTTP request and handles it appropriately.
struts-config.xml
<form-bean name="personAddBean" type="com.gm.ecvms.common.form.ECVMSActionForm">
<action path="/addPerson"
name="personAddBean"
scope="request“
validate="true"
input="/weblogic/displayPersonAdd"
type="com.gm.ecvms.main.web.process.personnel.personadd.AddPersonAction" >
<forward name="successRetrieve" path="/index"></forward>
</action>
Hello World Struts
1- View
<%@ page language="java" pageEncoding="UTF-8"%> <%@ taglib uri="http://struts.apache.org/tags-html" prefix="html" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html:html> <head> <title>hello.jsp</title> </head> <body> <p>Hello Struts</p> </body> </html:html> |
2- Controller
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN" "http://struts.apache.org/dtds/struts-config_1_2.dtd"> <struts-config> <data-sources /> <form-beans /> <global-exceptions /> <global-forwards /> <action-mappings > <action path="/SayHello" forward="/jsp/hello.jsp" /> </action-mappings> <message-resources parameter="struts.helloworld.ApplicationResources" /> </struts-config> |
HelloWord2
1- View
<%@ page language="java" pageEncoding="UTF-8"%> <%@ taglib uri="http://struts.apache.org/tags-html" prefix="html" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html:html> <head> <title>hello.jsp</title> </head> <body> <p>Hello <html:text name="helloForm" property="name" /></p> </body> </html:html> |
2- Controller
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN" "http://struts.apache.org/dtds/struts-config_1_2.dtd"> <struts-config> <data-sources /> <form-beans> <form-bean name="helloForm" type="struts.form.HelloActionForm" /> </form-beans> <global-exceptions /> <global-forwards /> <action-mappings > <action path="/SayHello" forward="/jsp/hello.jsp" /> <action path="/Hello" name="helloForm" type="struts.action.HelloAction"> <forward name="success" path="/jsp/hello.jsp" /> </action> </action-mappings> <message-resources parameter="struts.helloworld.ApplicationResources" /> </struts-config> |
package struts.action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import struts.form.HelloActionForm;
public class HelloAction extends Action{
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest req, HttpServletResponse res) throws Exception {
HelloActionForm helloForm = (HelloActionForm)form;
helloForm.setName("Ahmed Hashim");
return mapping.findForward("success");
}
}
3- Model
package struts.form;
import org.apache.struts.action.ActionForm;
public class HelloActionForm extends ActionForm{
private String name;
public HelloActionForm()
{
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Struts Request Life Cycle
The Action Servlet life cycle
8- Validation
What is the action form life cycle?
How the validation works?
What will happen when you add an error to the ActionErros?
The ActionErrors will be saved on the request scope and when you forward to the next view, you will be able to display the errors to the user.
Where the action will forward after getting error in validation?
The input attribute in the action definition.
Can I add some errors from the Action?
Sure, but don't forget to call the saveMessages() function
ActionMessages messages = new ActionMessages(); messages.add("STATUS", new ActionMessage("status.good")); messages.add("ACTION", new ActionMessage("action.next")); saveMessages(request, messages); |
How can I display the errors?
In your view module, you should handle it. Html tags are used to handle error messages; there are more than tag to do the job:
<html:errors />
Or
<logic:messagesPresent> <h3> <font color="red"> <bean:message key="myForm.error.header" /> </font> </h3> <ul> <html:messages id="msg"> <li><bean:write name="msg" /></li> </html:messages> </ul> </logic:messagesPresent> |
What are the classes to be used in Errors?
9- Struts tag library
Including tag library
<%@ taglib uri="/WEB-INF/tlds/struts-html.tld" prefix="html" %> |
The HTML Tag Library Tags
The following table lists each of the tags in the HTML Tag Library and a short description of each tag’s purpose.
Tag | Description |
Base | Generates an HTML <base> tag with its href attribute set to the absolute URL of the enclosing JSP. |
Button | Generates an HTML <input type=“button”> tag. |
Cancel | Generates an HTML <input type=“submit”> tag that, when executed, causes Struts’ Cancel feature to be triggered. |
checkbox | Generates an HTML <input type=“checkbox”> tag populated with data from a specified object. |
Errors | Displays a set of error messages stored as an org.apache.struts.action.ActionErrors object, a String, or a String array in request scope. |
File | Generates an HTML <input type=“file”> tag populated with data from a specified object. |
Form | Generates an HTML <form> tag tied to an Action object and its corresponding Form Bean from the struts-config.xml file. |
Hidden | Generates an HTML <input type=“hidden”> tag populated with data from a specified object. |
Html | Generates an HTML <html> tag with language attributes set to the current user’s locale. |
Image | Generates an HTML <input type=“image”> tag. |
Img | Generates an HTML <img> tag |
Link | Generates an HTML hyperlink <a> tag whose URL is composed by specifying a base URL and optionally specifying an anchor and/or query string parameters to add to the URL. |
messages | Displays a set of messages stored as an org.apache.struts.action.ActionErrors object, an org.apache.struts.action.ActionMessages object, a String, or a String array in request scope. |
Option | Generates an HTML <option> tag. |
password | Generates an HTML <input type=“password”> tag populated with data from a specified object. |
Radio | Generates an HTML <input type=“radio”> tag populated with data from a specified object. |
Reset | Generates an HTML <input type=“reset”> tag. |
Select | Generates an HTML <select> tag. |
Submit | Generates an HTML <input type=“submit”> tag. |
Text | Generates an HTML <input type=“text”> tag populated with data from a specified object. |
Textarea | Generates an HTML <textarea> tag populated with data from a specified object. |
Xhtml | Instructs the rest of the tags in the HTML Tag Library to generate their output as XHTML instead of HTML. |
Common Tag Attributes
As mentioned earlier, many of the tags in this library have several attributes in common. They are described in the following table.
Attribute | Description | Accepts Scriptlet | Required |
accesskey | Same as the corresponding HTML tag’s attribute with the same name.Specifies the keyboard key that causes this control to immediately receive focus when the key is pressed. | Yes | No |
Alt | Same as the corresponding HTML tag’s attribute with the same name.Specifies the alternate text for this control. | Yes | No |
altKey | Specifies a key from Struts’ ApplicationResources.properties file whose value will be used to set the corresponding HTML tag’s alt attribute. | Yes | No |
disabled | Same as the corresponding HTML tag’s attribute with the same name.Accepts “true” to denote that the control will be disabled, preventing its use. | Yes | No |
Onblur | Same as the corresponding HTML tag’s attribute with the same name.Specifies the JavaScript code to execute when this control loses input focus. | Yes | No |
onchange | Same as the corresponding HTML tag’s attribute with the same name.Specifies the JavaScript code to execute when this control loses input focus and its value has changed. | Yes | No |
Onclick | Same as the corresponding HTML tag’s attribute with the same name.Specifies the JavaScript code to execute when this control receives a mouse click. | Yes | No |
ondblclick | Same as the corresponding HTML tag’s attribute with the same name.Specifies the JavaScript code to execute when this control receives a mouse double-click. | Yes | No |
Onfocus | Same as the corresponding HTML tag’s attribute with the same name.Specifies the JavaScript code to execute when this control receives input focus. | Yes | No |
onkeydown | Same as the corresponding HTML tag’s attribute with the same name.Specifies the JavaScript code to execute when this control has focus and a key is pressed. | Yes | No |
onkeypress | Same as the corresponding HTML tag’s attribute with the same name.Specifies the JavaScript code to execute when this control has focus and a key is pressed and released. | Yes | No |
onkeyup | Same as the corresponding HTML tag’s attribute with the same name.Specifies the JavaScript code to execute when this control has focus and a key is released. | Yes | No |
onmousedown | Same as the corresponding HTML tag’s attribute with the same name.Specifies the JavaScript code to execute when this control is under the mouse pointer and a mouse button is pressed. | Yes | No |
onmousemove | Same as the corresponding HTML tag’s attribute with the same name.Specifies the JavaScript code to execute when this control is under the mouse pointer and the mouse is moved. | Yes | No |
onmouseout | Same as the corresponding HTML tag’s attribute with the same name.Specifies the JavaScript code to execute when this control is under the mouse pointer and is then moved away from the control. | Yes | No |
onmouseover | Same as the corresponding HTML tag’s attribute with the same name.Specifies the JavaScript code to execute when this control is not under the mouse pointer and is then moved to the control. | Yes | No |
onmouseup | Same as the corresponding HTML tag’s attribute with the same name.Specifies the JavaScript code to execute when this control is under the mouse pointer and a mouse button is released. | Yes | No |
Style | Same as the corresponding HTML tag’s attribute with the same name.Specifies the CSS style to apply to this control. | Yes | No |
styleClass | Same as the corresponding HTML tag’s class attribute.Specifies the CSS class to apply to this control. | Yes | No |
styleId | Same as the corresponding HTML tag’s id attribute.Specifies the CSS id to apply to this control. | Yes | No |
tabindex | Same as the corresponding HTML tag’s attribute with the same name.Specifies the tab order for this control. | Yes | No |
Title | Same as the corresponding HTML tag’s attribute with the same name.Specifies the title for this control. | Yes | No |
titleKey | Specifies a key from Struts’ ApplicationResources.properties file whose value will be used to set the corresponding HTML tag’s title attribute. | Yes | No |
10- Tiles
o How to design a web page?
header |
footer |
body |
o 2 approaches
i. Jsp
JSP based approach
In this approach each JSP page is coded separately .
Each page is responsible for laying out itself.
Although the header and footer are common to every page, the common JSP markup for header and footer was added into each JSP by direct copy and paste.
1. JSP based approach advantages
2. Minimizes the number of pages
JSP based approach consequences
a. Anytime the header and footer changes, it has to manually applied to every page which means heavy maintenance cost.
b. So much HTML and JSP code duplication
ii. <jsp:include />
In this approach the common markup related to header and footer is moved into jsp of their own.
The header and footer JSPs are added to the main JSP by using the standard <jsp:include> directive
w <jsp:include> approach advantages
w You only need to change common view components once
w Eliminates HTML and JSP code repetition
w Achieve view components reuse
w <jsp:include> approach consequences
w It increases the no of pages
w If you changed the layout ,then you would need to update every page
w Does not achieve the reuse of layout logic
o What is Tiles?
o
11- Validation Plugins
Disadvantages of ActionForm Validation
- validation logic within each ActionForm places redundant validation logic throughout your application.
- maintenance. If you need to modify or enhance the validation that occurs for an ActionForm, the source code must be recompiled. This makes it very difficult to configure an application.
Solution:
The Validator framework allows you to move all the validation logic completely outside of the ActionForm and declaratively configure it for an application through external XML files. No validation logic is necessary in the ActionForm, which makes your application easier to develop and maintain. The other great benefit of the Validator is that it's very extensible. It provides many standard validation routines out of the box, but if you require additional validation rules, the framework is easy to extend and provides the ability to plug in your own rules (again without needing to modify your application).
Validator-rules.xml
The validation-rules.xml configuration file contains a global set of validation rules that can be used out of the box by your application. This file is application-neutral and can be used by any Struts application. You should need to modify this file only if you plan to modify or extend the default set of rules.
Built in rules in Validation-rules.xml
Table 6-1: Validator's Preconfigured Validations | |
Validation | Description |
Byte | Validates that the specified field contains a valid byte. |
creditCard | Validates that the specified field contains a valid credit card number. |
Date | Validates that the specified field contains a valid date. |
Double | Validates that the specified field contains a valid double. |
Email | Validates that the specified field contains a valid e-mail address. |
Float | Validates that the specified field contains a valid float. |
floatRange | Validates that the specified field contains a valid float and falls within the specified range. |
Integer | Validates that the specified field contains a valid integer. |
intRange | Validates that the specified field contains a valid integer and falls within the specified range. |
Long | Validates that the specified field contains a valid long. |
Mask | Validates that the specified field conforms to a given regular expression (or 'mask'). |
Maxlength | Validates that the string in the specified field's length is less than or equal to the specified maximum length. |
Minlength | Validates that the string in the specified field's length is greater than or equal to the specified minimum length. |
Range | Deprecated Use the intRange validation instead. |
Required | Validates that the specified field contains characters other than white space (i.e., space, tab, and newline characters). |
Requiredif | Performs the required validation on the specified field if a specified rule is met. |
Short | Validates that the specified field contains a valid short. |
Validator.xml
The second configuration file that is required by the Validator framework is the validation.xml file. This file is application-specific; it describes which validation rules from the validation-rules.xml file are used by a particular ActionForm. This is what is meant by declaratively configured—you don't have to put code inside of the ActionForm class. The validation logic is associated with one or more ActionForm classes through this external file.
<formset> <form name="checkoutForm"> <field property="phone" depends="required,mask"> <arg0 key="registrationForm.firstname.displayname"/> <var> <var-name>mask</var-name> <var-value>${phone}</var-value> </var> </field> </form> </formset> |
The field elements attributes
Attribute | Description |
property | The property name of the JavaBean (or ActionForm) to be validated. |
depends | The comma-delimited list of validation rules to apply against this field. For the field to succeed, all the validators must succeed. |
Page | The JavaBean corresponding to this form may include a page property. Only fields with a page attribute value that is equal to or less than the value of the page property on the form JavaBean are processed. This is useful when using a "wizard" approach to completing a large form, to ensure that a page is not skipped. |
indexedListProperty | The method name that will return an array or a Collection used to retrieve the list and then loop through the list, performing the validations for this field. |
In struts config add
Extend ValidatorActionForm not ActionForm
Define form bean in struts-config-xml
<form-beans> <form-bean name="logonForm" type="com.jamesholmes.minihr.LogonForm"/> </form-beans> |
In validator.xml add the formvalidation definition
<form-validation> <formset> <form name="logonForm"> <field property="username" depends="required"> <arg0 key="prompt.username"/> </field> </form> </formset> </form-validation> |
Configuring ApplicationResources.properties
<validator name="required" classname="org.apache.struts.validator.FieldChecks" method="validateRequired" org.apache.commons.validator.ValidatorAction, org.apache.commons.validator.Field, org.apache.struts.action.ActionErrors, javax.servlet.http.HttpServletRequest" msg="errors.required"> |
# Error messages for Validator framework validations errors.required={0} is required. errors.minlength={0} cannot be less than {1} characters. errors.maxlength={0} cannot be greater than {2} characters. errors.invalid={0} is invalid. errors.byte={0} must be a byte. errors.short={0} must be a short. errors.integer={0} must be an integer. errors.long={0} must be a long. errors.float={0} must be a float. errors.double={0} must be a double. errors.date={0} is not a date. errors.range={0} is not in the range {1} through {2}. errors.creditcard={0} is not a valid credit card number. errors.email={0} is an invalid e-mail address. |
Client side validation
<html:javascript formName="logonForm"/>
<form name="logonForm">
<field property="username" depends="required">
<arg0 key="prompt.username"/>
</field>
<field property="password" depends="required">
<arg0 key="prompt.password"/>
</field>
</form>
12- Exception Handling
1- Java exceptions
2- The method invocation stack
3- What About the throws Clause? (programming by Contracts)
4- Performance Impact of Exception Handling
5- Using ModuleException
6- Declarative Versus Programmatic Exception Handling
<action path="/loginAction" name="loginForm" validate="true" input="/PreLogin.do" scope="request" type="evote.action.LoginAction"> <forward name="success" path="viewIndex.page" /> <forward name="fail" path="viewLoginPage.page" /> <exception key="exception1" type="evote.exception.LoginException" path="viewLoginPage.page" /> </action> |
7- Struts exception handeling
8-
Refereces
3.
Comments
Post a Comment