• No results found

Enter Customer Address

In document CoreJava_JSP_Servlet_Struts_EJB (Page 172-200)

Id:

Name:

Address City:

Address Line 1 Address Line 2

Address Line 3

<jsp:getProperty name="customerVO" property="id" />

<jsp:getProperty name="customerVO" property="name" />

<jsp:getProperty name="customerVO" property="address" />

<jsp:getProperty name="customerVO" property="cityId" />

Note the usage of jsp:useBean tag here - right on the top. The rule is same: JSP-Servlet engine will check whether there is bean called customerVO in request, if yes it will use it or else it will create it. Since the control has been forwarded from AddCustomer.jsp (which creates customerVO and puts in request) to this page, servlet engine will not recreate it - instead use it.

See the usage of jsp:getProperty tag to get the value of attributes of the bean and set it to text boxes.

Techniques for Form Editing Editing a Form

A form used to accept values from the user and put it in the database can be also be used to display

the values retrieved from the database so that it can be ammended by the user

Write a index.jsp which will have anchor to EditCustomer.jsp. The text of the anchor must display :

"Edit Customer".

The EditCustomer.jsp must accept customer Id from the user. When the user clicks on submit,

submit the request to RetrieveCustomer.jsp. RetrieveCustomer.jsp must contain scriptlet which will load database driver, establish connnection, retrieve data and create a javabean called customerVO of class CustomerValueObject and put the same in request object. The customer row retrieved must be exactly the one the id of which is entered by the user on EditCustomer.jsp

RetrieveCustomer.jsp will finally forward the request to Customer.jsp which will display the data in

text boxes using jsp:getProperty. Needless to say, you will have to use jsp:useBean also on the top of Customer.jsp.

Submit

Assignment(s) Form Bean Exercise

Extend the application you have written in "Assignments for Implicit Objects " to use Form Beans to

edit Customer, Tax etc.

Retrieve the customer the way you have done earlier and forward to Customer.jsp. Use jsp:useBean, jsp:getProperty to display the values retrieved in the text boxes. Write EditCustomer.jsp EditTax.jsp etc to update the edited values back to database

Chapter: 4 - Protecting Your Website Creating the Login Page

Chapter: 5 - Servlets Introducing Servlets What is a Servlet

A servlet is a Java programming language class used to extend the capabilities of servers that host applications accessed via a request-response programming model.

Although servlets can respond to any type of request, they are commonly used to extend the

applications hosted by Web servers. For such applications, Java Servlet technology defines HTTP-specific servlet classes.

The javax.servlet and javax.servlet.http packages provide interfaces and classes for writing servlets.

All servlets must implement the Servlet interface, which defines life-cycle methods.

When implementing a generic service, you can use or extend the GenericServlet class provided with

the Java Servlet API.

The HttpServlet class provides methods, such as doGet and doPost, for handling HTTP-specific

services.

Servlet Life Cycle

The life cycle of a servlet is controlled by the container in which the servlet has been deployed.

When a request is mapped to a servlet, the container performs the following steps.

If an instance of the servlet does not exist, the Web container

Loads the servlet class.

Creates an instance of the servlet class.

Initializes the servlet instance by calling the init method.

Invokes the service method, passing a request and response object.

If the container needs to remove the servlet, it finalizes the servlet by calling the servlet's destroy

method.

Service Methods

Writing Service Methods

The service provided by a servlet is implemented in the service method of a GenericServlet, the

doMethod methods (where Method can take the value Get, Delete, Options, Post, Put, Trace) of an HttpServlet, or any other protocol-specific methods defined by a class that implements the Servlet interface.

In the rest of this chapter, the term service method will be used for any method in a servlet class that

provides a service to a client.

The general pattern for a service method is to extract information from the request, access external

resources, and then populate the response based on that information.

For HTTP servlets, the correct procedure for populating the response is to first fill in the response

headers, then retrieve an output stream from the response, and finally write any body content to the output stream.

Response headers must always be set before a PrintWriter or ServletOutputStream is retrieved

because the HTTP protocol expects to receive all headers before body content.

The doGet and doPost Methods

The doGet method is one of the service methods that is executed by the container when the requested is submitted to the server and the method of submission os get

The doPost method is no different then doGet method - the only difference is that it is executed by

the container when the method of request submitted by the client is post

All that we did in AddCustomer.jsp and RetrieveCustomer.jsp should have been actually done in

Servlet.

The JSP(s) are for managing presentation logic and servlets are the ones that must be used for

processing requests and managing control logic of web-navigation.

Creating a Servlet

Create a servlet called CustomerServlet which will do all that you have written in AddCustomer.jsp

Please note that when you create a servlet, the servlet is requested from client-side with a URL patterns and not the name

of the servlet.

Please see the web.xml file

Now instead of action="AddCustomer.jsp" in Customer.jsp - change it to "customerservlet" - the url pattern for

CustomerServlet

Write the following code in doPost method as follows:

String name, address;

int id, cityId;

// Note that all the data that comes in request comes in String id = (new Integer(request.getParameter("id"))).intValue();

name = request.getParameter("name");

address = request.getParameter("address");

cityId = (new Integer(request.getParameter("cityId"))).intValue();

out.println("The id is : " + id + " Name : " + name + " Address : " + address + " City : " + cityId);

// Note the usage of out implicit object

CustomerValueObject customerVO = new CustomerValueObject();

customerVO.setId((new Integer(id)).intValue());

customerVO.setName(name);

customerVO.setAddress(address);

customerVO.setCityId((new Integer(cityId)).intValue());

request.setAttribute("customerVO", customerVO);

RequestDispatcher dispatcher = request.getRequestDispatcher("CustomerAddress.

jsp");

dispatcher.forward(request, response);

Note the RequestDispatcher object used here to forward the request to CustomerAddress.jsp. Also note how customerVO object is created and put in request. This is not a JSP hence we have to do it without a tag

Maintaining Client State Accessing a Session

Many applications require a series of requests from a client to be associated with one another. For example, the user logs on to your system and you would like to maintain his user info such as first name and lastname across multiple request infact throughout out his interaction with the application.

Web-based applications are responsible for maintaining such state, called a session, because the

HTTP protocol is stateless.

To support applications that need to maintain state, Java Servlet technology provides an API for

managing sessions and allows several mechanisms for implementing sessions.

Sessions are represented by an HttpSession object.

You access a session by calling the getSession method of a request object.

This method returns the current session associated with this request, or, if the request does not have a session, it creates one

Associating Attributes with a Session

Create a Login.jsp with a form on it accepting username and password from the user

On submitting this form - invoke (using action="loginservlet") LoginServlet

You must create all servlets in some package - here you create LoginServlet in servlets package

In valueobjects package create a class called UserValueObject.java as a java bean with attributes such as: userName,

firstName, lastName. (You know what is a java bean - it must have getter & setter methods for each one of these attributes)

Write the doPost method in LoginServlet as follows:

String userName = request.getParameter("userName");

userVO.setUserName(userName);

// You can get firstName and lastName // can be read from database.

userVO.setFirstName("Saurav");

userVO.setLastName("Ganguly");

HttpSession session = request.getSession();

// the following will help you to keep // userVO server-side till the users // session is alive.

session.setAttribute("userVO", userVO);

// dispatcher must be actually taken for index.jsp

RequestDispatcher dispatcher = request.getRequestDispatcher("Customer.jsp");

dispatcher.forward(request, response);

Using the Session Object

Create a new JSP called Banner.jsp

Write a scriplet in Banner.jsp as follows:

UserValueObject userVO = (UserValueObject) session.getAttribute("userVO");

String firstName = userVO.getFirstName();

String lastName = userVo.getLastName();

out.println("Welcome : " + firstName + " | " + lastName);

I said scriptlet friends. You know what is a scriplet.

Now include this jsp in each jsp using

<jsp:include page="Banner.jsp" />

Execute Login.jsp and now switch to any jsp (without closing the browser) typing the jsp name on the address bar.

See that you will get Welcome info on all the jsps

Assignment(s) Servlet Assignment(s)

Re-Design the entire application written earlier, to use servlets instead of all the JSP(s) which were

doing the request processing and not managing the presentation logic for e.g. AddCustomer.jsp, RetrieveCustomer.jsp, DeleteCustomer.jsp etc. Now no jdbc code must be there in any JSP - All the jdbc code must be in Servlets.

Using Session Objects

Consider that each Customer has one or more Addresses. Create a Customer Data Entry Application which will accept Customer Details like name, address etc and also one ore more Addresses which will have line1, line2 and line3 of address. Save the entire Customer along with Address only after user confirms. Till the time user finishes entering all the Addresses you must keep Customer Details like name and address in Session Object. Use value objects, form beans, request and session objects.

This must be a complete master-detail application with add, modidy, delete and view options.

Struts

Chapter: 1 - Introduction to MVC What is MVC ?

The MVC Architectural Pattern

The early JSP specifications advocated two philosophical approaches for building applications using

JSP technology: MVC Model-1 & MVC Model-2

Model 1 and 2 differ essentially in the location at which the bulk of the request processing was

performed

In the Model 1 architecture, the JSP page alone is responsible for processing the incoming request

and replying back to the client.

There is still separation of presentation from content, because all data access is performed using

beans

MVC Model 2

The Model 2 architecture, is a hybrid approach for serving dynamic content, since it combines the

use of both servlets and JSP.

It takes advantage of the predominant strengths of both technologies, using

JSP to generate the presentation layer and

servlets to perform process-intensive tasks

The servlet acts as the controller and is in charge of :

the request processing

the creation of any beans or objects used by the JSP,

deciding, depending on the user's actions, which JSP page to forward the request to.

Note particularly that there is no processing logic within the JSP page itself

JSP is simply responsible for retrieving any objects or beans that may have been previously created

by the servlet, and extracting the dynamic content from that servlet for insertion within static templates

Struts Implements MVC Struts Logical Structure

Struts implements MVC. Yes - MVC 2.

Chapter: 2 - Introduction to Struts The Architecture of Struts

Struts Architecture

Struts is comprised of a controller servlet, beans and other Java classes, configuration files, and tag

libraries.

A controller for your application (the Struts servlet acts as a common controller for the whole

application)

A collection of Java beans and other helper classes that you use in the "Model" part of your

application

A collection of tag libraries used in your jsp-pages

To glue these things together Struts uses a set of configuration files. Together this gives you the

skeleton that you can use to "strut" your application

The Flow

Consider, that the request sent from the client (browser) is toCreateCustomer.do - The *.do url pattern is mapped to ActionServlet in web.xml file and hence ActionServlet service method is executed

The ActionServlet reads struts-config.xml file and searches for <action> element with path="/

toCreateCustomer" and detects the Action class name configured with this path

The ActionServlet now instantiates the Action class and executes the execute method of it

Please note: Before executing the execute method, the ActionServlet instantiates the formbean object

(if configured) and populates it with the data entered by the end-user, executes the validate method and then passes it as the parameter to the execute() method.

Benefits of Using Struts Benefits of Using Struts

Struts has been designed to give you modularity and loose couplings in your application.

If you're building a simple, small application you might find it complicated to have to create and

handle so many files.

You might even be tempted to put all your code in a single jsp-file

My advice to you is: don't do it! I'm sure you can build a single-page application faster using only

one jsp-page, but if we're talking about more complex applications, the extra effort put in by using a modular framework will soon be rewarded

There is one single servlet in the entire application i.e. ActionServlet. This servlet is provided by Struts-Framework API

All the requests coming to the application server (which requires dynamic contents / need to access

the model) is received by this ActionServlet.

The ActionServlet reads Struts-Config.xml file and identifies the Action class to be instantiated.

The ActionServlet instantiates the Action Class and executes the execute() method

It is this execute() method, in the Action Class where you write your use case logic.

Note that the ActionClass you write is extended from Action class provided by Struts-Framework API. The execute () method has 4 parameters (ActionMapping mapping, ActionForm form, HttpServletRequest request,

HttpServletResponse response).

The ActionForm

If the form is to be processed the programmer-defined class of type ActionForm can be configured in

Struts-Config.xml file

It is the responsibility of Struts-Framework to instantiate this class, read the contents entered by the

end-user and copy the same to this FormBean class.

The best thing is that (as explained in notes of previous slide) one of the parameters passed to the

execute method of Action Class is this instantiated and populated FormBean object

You can execute accessor (getter) methods on this form object to get the data entered by the end-user

in the execute method

The validate method of ActionForm class

The Struts-Framework after instatiating and populating the ActionForm object, executes the validate method.

You can write validations in this validate method and return object of type ActionErrors containing

the list of Errors (if there are any as per the business rule)

The Struts-Framework will automatically forward to the input page (forcing user to re-enter the data)

With the help of simple error tags, (provided by Struts) you can display the error messages on the

input page

Setting up Struts The Jar Files

There are n number of jar files provided by Struts-Framework which togethger provides all the

Struts-Functionality. The architecturally-significant among these is Struts.jar

All the architecturally-significant components like: ActionServlet, Action, ActionForm, ActionError,

ActionErrors etc. are in this jar file.

This and all the other jar files must be copied to your WEB-INF/lib folder

Please download the following zip file, Unzip it and copy all the jar files in the location mentioned

above:

Download Jar Files

Any jar file put in the lib folder need not be explicity specified in the classpath of your web application. They are implicity included in the classpath

The TLD Files

As mentioned earlier, Struts offers collection of rich tags which tremendously eases the development

of presentation logic.

All the tag classes are in struts.jar file and all the descriptors of tags are in the .tld files copied on

WEB-INF folder

These files must be copied in WEB-INF folder

Please download the following zip file and copy it to the location mentioned above:

Download TLDs

Struts-Config.xml

This is the Struts Configuration file.

It contains the configuration of form beans, action classes, forwards etc.

This is the architecturally siginificant component of Struts-Framework. If not present, the framework

will cease to work.

This file must be copied to WEB-INF/ folder

Please download the following sample Struts-Config.xml file and copy it to the location mentioned

above:

Download Struts-Config

Configuring your web.xml to use Struts

Create a Servlet Component in web-xml file with the name action. This servlet component must be mapped to the servlet class : ActionServlet. The fully qualified path of the this servlet is: org.apache.struts.action.

ActionServlet

Also set the initialization parameter called "config" for this servlet. Set the value of this parameter to:

/WEB-INF/struts-config.xml. The xml code is given below

<servlet>

<servlet-name>action</servlet-name>

<display-name>ActionServlet</display-name>

<description>Struts Controller</description>

<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>

<init-param>

<param-name>config</param-name>

<param-value>/WEB-INF/struts-config.xml</param-value>

<description>No Description</description>

</init-param>

</servlet>

Now add a servlet mapping in your web.xml file for the ActionServlet as follows:

<servlet-mapping>

<servlet-name>action</servlet-name>

<url-pattern>*.do</url-pattern>

</servlet-mapping>

Now you are ready to strut your application

You will have to redeploy your application to bring all the changes in effect Chapter: 3 - Getting Started

The Customer Mananagement App The Application

Let us develop a small sample application which will have the option of creating a new Customer.

Each customer that is recorded belong to a particular city and and we need to provide the list of cities to the user. Also, we need to perform basic validation like customer name cannot be left blank. If this validation fails, the system must re-present the customer form displaying the error message(s) - or else save the Customer

Please create the following jsp(s)

index.jsp - With the anchor toCreateCustomer.do (The application will actually present the

customer.jsp form when user clicks on the anchor)

customer.jsp - with the html form to accept the customer id, name, city and address

Simple Action Class The Action Class

Create a new package (folder) called presentationtier and then class within it called

ToCreateCustomerAction.java Extend this class from Action

To extend from Action class, import org.apache.struts.action.Action class

Now override execute method, the signature of which is: public ActionForward execute

(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException

Write following lines in the execute method:

SOP : Retrieving Cities

return mapping.findForward("success");

Compile the class

It is assumed that you already have created a web application and tested the same.

It is assumed that you already have created a web application and tested the same.

In document CoreJava_JSP_Servlet_Struts_EJB (Page 172-200)

Related documents