68
Industrial Training A Report Submitted in Partial fulfillment for the award of Bachelor of Engineering in Computer Science & Engineering Submitted to RAJIV GANDHI PROUDYOGIKI VISHWAVIDYALAYA BHOPAL (M.P) WEB DESIGNING Submitted by Manish Sen [0126CS081051] DEPARTMET OF COMPUTER SCIENCE & ENGINEERING

Traning Report

Embed Size (px)

Citation preview

Page 1: Traning Report

Industrial Training

A ReportSubmitted in Partial fulfillment for the award of

Bachelor of Engineering in Computer Science & Engineering

Submitted toRAJIV GANDHI PROUDYOGIKI VISHWAVIDYALAYA

BHOPAL (M.P)

WEB DESIGNING

Submitted byManish Sen [0126CS081051]

DEPARTMET OF COMPUTER SCIENCE & ENGINEERINGTHAKRAL COLLEGE OF

TECHNOLOGY, BHOPAL (M.P.)SESSION Dec-2011

Page 2: Traning Report

Company Profile:

Quality Policy :

“ HCL are committed to provide quality training, projects and consultancy with students and industry centric requirements and by continually improving the quality management system”

Page 3: Traning Report

ORGANIZATION CHART

HCL is India's pioneer in Internet and eCommerce and offers integrated end-to-end solutions with a comprehensive range of products and services, for both the Business to Consumer (B2C) and Business to Business (B2B) segments, that cover the four critical cornerstones of the Net: Connectivity, Content, Commerce and Community.

HCL’s, mission is to "Make the Internet work for you."

HCL enable this through the products, services and technology that it offer. And in the comprehensive suite of Business to Consumer and Business to Business eCommerce solutions.

HCL’s cutting edge B2B services including connectivity solutions like Electronic Data Interface, Virtual Private Networks, Security Services, Network Management Services as well as eSolutions services that include Internet Consulting, Solutions

SOFTWARE DEVELOPERS / FACULTY

DIRECTOR

PROJECT INCHARGE

GUEST FACULTY

PEON

OFFICE INCHARE

COUNSELOR

LAB INSTRUCTER

Page 4: Traning Report

Architectures, Design and Development of Solutions, Hosting and Management Services and eCommerce products, are relied upon by leading Corporates in India.

HCL Statement of Purpose

HCL’s purpose is to make a qualitative difference to the lives of millions of people and organisations by harnessing the power of India and of the Internet. HCL will do this by empowering them with the potential of the Internet and by leveraging the capabilities of Indian Knowledge Resources.

HCL Statement of Vision

HCL’s vision is to be the dominant and profitable India centric Internet company by: Building on India's unique advantages. Being the leader in terms of market share, quality, revenue, growth and gross

margins. Adding value to our stakeholders: namely customers, peers and associates. Being enablers and catalysts of the Internet for positive change.

HCL’s Credo

I will always treat others with dignity, courtesy and respect. I will work like an entrepreneur with urgency in thought and action. I will put customer needs first, delivering quality solutions that are of value

to them. I will always pursue excellence in my work. I will be open, honest and sincere with colleagues, customers, vendors and

everyone I deal with. I will always do what I have committed to do. I will always remember that I am part of a team.

HCL CENTER

Hcl Career Development Center Bhopal (Ph 4094357,4094852)

Page 5: Traning Report

Introduction:

During the industrial training the topics and knowledge about the technologies which we came to know are as follow:

Web Technologies Enterprise Technologies Benefits of Web Application over Desktop Scope of Web application Architecture of Web Application Ingredients of web application Client side & Server side Technologies

Web Technologies:

Servlets Java Server Pages (JSP) Java Server Faces (JSF)

Enterprise Technologies

Enterprise Java Beans

Benefits of Web Application over Desktop

No geographical constraints No software required on the client side (only browser is needed) Multiple users Distributed Architecture Easy Maintenance Security

Scope of Web application

Internet (WAN) / Intranet (LAN) / Extranet (MAN)

Architecture of Web Application

3-tier (Web Technologies)

Front End (HTML/Applet) Middleware (Servlets/JSP/JSF) Back End

n-tier (Enterprise Technologies)

Front End (HTML/Applet)

Front End

Middleware

Back End

Page 6: Traning Report

Middleware (Servlets/JSP/JSF) Business Logic (EJB) Back End

Client side & Server side Technologies

HTML Used for designing / user interface Client Side Scripting Validation of data on client machine. Example

New User Cascading Style Sheets Used for formatting multiple web pages

DHTML = HTML + Client side Scripting + Cascading Style Sheets

Server Side Technologies

Server Side ScriptingGenerates dynamic web pages that include security, database &

customization.

Database

Front End

Back End

Business logic

Middleware

mobile

Web tech.Front End

Page 7: Traning Report

Ingredients of web application

Client side: HTML, JavaScript, CSS

Software required on client: Browser (IE)

Server side: Servlets/ JSP / JSF

Software required on server: Web Server, Database

HTML

Page 8: Traning Report

+ HTML is an acronym of Hypertext Markup Language.+ In markup languages the text is marked in within TAGS.+ These TAGS are in pairs, they have an opening TAG & closing TAG.

<B> Hello World </B>

+ All markup languages are derived from “SGML” (Standard Generalized Markup Language).

+ Example: HTML, WML, XML.

Definition+ HTML is a collection of pre-defined TAGS taken from SGML that defines

the display attribute of the data.+ XML is a collection of user-defined TAGS taken from SGML that defines the

storage attribute of the data.

NOTE: These things have been defined by W3C “World Wide Web Consortium”.We are going to study HTML TAGS under the following categories:

1. Basic TAGS2. Formatting TAGS3. Lists4. Tables5. Inter and Intra document Links6. Forms7. Frames

Basic TAGS

NOTE: HTML is not case sensitive.

<HTML>…</HTML> + This TAG marks the beginning & end of HTML document.+ HTML document is divided in 2 parts

1. Head2. Body

<HEAD>…</HEAD>+ This TAG marks the beginning & end of HEAD part of HTML document.

<BODY>…</Body>+ This TAG marks the beginning & end of BODY part of HTML document.

<TITLE>…</TITLE>+ This TAG defines the title of the HTML document.+ This TAG should always be written within HEAD part.

Software requirement for HTML: Browser (IE)

Page 9: Traning Report

Steps to create & execute an HTML document

1. Open Notepad.2. Type the HTML document.

<HTML><Head>

<Title> First Page </title></head><Body>

This is my first page.</Body>

</HTML>3. Save it as AnyName.html or AnyName.htm4. Open Browser5. File | Open | <Browse the HTML file>6. To view the HTML code

View | Source OR Context Menu | View Source7. To refresh an HTML page

View | Refresh OR F5

Formatting TAGS

+ Html supports 6 levels of heading starting from H1 to H6<H1> this is for Heading 1 </H1><H2> this is for Heading 2 </H2><h3> this is for Heading 3 </h3><h4> this is for Heading 4 </h4><h5> this is for Heading 5 </h5><h6> this is for Heading 6 </h6>

+ The difference is in size. Default Alignment is “left”.<H1 ALIGN = “Right”> Heading One </H1> TAG+ <H1>…</H1> TAG, H1 is element, ALIGN is attribute.+ An element can have more than one attribute separated by “SPACE”.

<B> This is for Bold </B><I> This is for Italic </I><u> This is for Underline </u><B><I><u> This is for Bold, Italic and Underline </u></I></B><strike> Strike Through </strike> Strike Through<blink> For blinking text </blink> (Netscape only)<font> specifies, font name, size & color </font>

<font name = “Arial, Algerian” size = 4> Hello </font>

1st preference 2nd preference else default

Page 10: Traning Report

<font name = “Arial, Algerian” size = 4 color =”red”> Hello </font><font color = “#ff0000”> hello </font>

Format = #rrggbbrr, gg, bb can go from 00 to ff (0 to 255)

<pre> This is for pre-formatted text </pre><pre>

One Two ThreeFour Five Six

</pre><P>This is for paragraph </p><p ALIGN="Justify"> This is for paragraph </p>+ <P>…</p> is the only TAG supporting justified alignment.<BR> this is for line break<hr> This is for horizontal Ruler<hr width = 30%> + <hr> has default alignment “CENTER”.+ <BR>, <hr> are known as empty TAGS.

Superscript 2<sup>2</sup> 22

Subscript H<sub>2</sub>O H2O<address> This is used for writing web addresses </address>EX. <address> [email protected] </address><code> This is used for writing coding within document </code><code>

int a, b; <BR>a = 10; <BR>b = 20; <BR>

</code>

<marquee> This is for scrolling text </marquee>+ Attributes are bgcolor, width, direction, behavior (alternate)

Lists in HTML

Page 11: Traning Report

HTML supports 3 types of List1. Ordered List2. Unordered List3. Definition List

Ordered List<ol>

<LI> This is Point one | 1. This is Point One<LI> This is Point one | 2. This is Point One<LI> This is Point one | 3. This is Point One

</ol>

ol: ordered listli: list index

<ol start = 6><LI> This is Point one | 6. This is Point One<LI> This is Point one | 7. This is Point One<LI> This is Point one | 8. This is Point One

</ol>

Unordered Listul: unordered list<UL>

<LI> This is Point one<LI> This is Point one<LI> This is Point one

</UL>

This is Point one This is Point one This is Point one

Definition List<dl><dt>Term </dt>

<dd> definition </dd><dt>HTML </dt>

<dd> Hypertext Markup Language </dd><dt>CGI </dt>

<dd> Common Gateway Interface</dd></dl>

Page 12: Traning Report

Links in HTML

Page 13: Traning Report

There are 2 types of Links1. Inter-document links (between 2 pages)2. Intra-document links (within a page)

To create links HTML provides <a>.....</a> Attributes:

Name : Specifies anchor namehref : Specifies hypertext referencetarget : Specifies target frame

To create intra document link1. Name the Part of the page

<a NAME="LinkName"> -----Data------ </a>2. Create a link for it.<a href="#LinkName"> Link </a>

Images+ Calling Images within HTML

To call image within HTML <img> is used<img>Attributes:src: Specifies source fileborder: specifies border widthwidth: specifies width of imageheight: specifies height of imagealt: specifies alternative text

Tables in HTML

< TABLE >…</TABLE>Marks beginning and end of Table

<TR>…</TR>Marks beginning and end of Table Row

<TH>…</TH>Marks beginning and end of Table Heading Cell

<TD>…</td>Marks beginning and end of Table Data Cell

< TABLE >…</TABLE>Attributes of table are:

width: Specifies table widthcellspacing: Specifies space between 2 cellscellpadding: Specifies space within a cellbgcolor: Specifies background colorborder: Specifies border width

<TD>…</TD> and <TH>…</TH>Attributes are:

Page 14: Traning Report

bgcolor: Specifies background coloralign: Can be left, right or centervalign: Can be top, bottom or centercolspan: Number of columns to coverrowspan: Number of rows to cover

&nbsp; Space&gt; Greater Than&lt: Lesser Than&quot; Double Quotes&cpyrt;

< TABLE width = 100% border =3><TR>

<TH> &nbsp; </TH><TH> East </TH><TH> West </TH>

</TR><TR>

<TH> Product A </TH><TH> 100 </TH><TH> 200 </TH>

</TR><TR>

<TH> Product B </TH><TH> 300 </TH><TH> 200 </TH>

</TR></TABLE>

Frames

Page 15: Traning Report

<frameset>…</frameset>+ This TAG is used to divide browser window in parts (rows and columns)+ This TAG is supported only by IE. Netscape does not support this TAG.+ This TAG should be written within HEAD part of HTML document.

Attributes:rows: Specifies rows detailscols : Specifies column details

Forms+ To create Forms in HTML < FORM >...</FORM> is used.+ Objective is to take input from user.< FORM >…</FORM>

+ marks the beginning & end of HTML form.Attributes of < FORM >...</FORM> are

Name: Specifies form namemethod: GET or POST

GET is used to fetch details from serverPOST is used to send details to server

action: Specifies the server side file to be called

HTML provides the following form elements

1. Text: To accept single line text2. TextArea: To accept multiline text3. Password: To accept passwords4. Button: To Trigger an action5. Submit: Special button used for form submission. (Calls the file mentioned in action attribute of FORM TAG) 6. Reset: Special button used for clearing contents of a form7. Hidden: To create a hidden form field.8. Checkbox: To select one or more options9. Radio: To select one out of multiple10. Select: To select one or more options

<Input>…</Input>+ It is used to create text, password, button, submit, reset, radio, checkbox, hidden.

Attributes: + type: can be text, password, button, submit, reset, radio, checkbox, hidden

+ name: specifies input name + value: specifies value for text, password, radio, checkbox and hidden. Also specifies caption of button, submit or reset + checked: only for radio and checkbox + size: specifies visible width of text, password + maxlength: maximum num. of characters in text or password.

<TextArea>.....</TextArea>

Page 16: Traning Report

+ It is used to create multiline text.Attributes are:

rows: specifies no. of rowscolumns: specifies no. of columnsname: specifies name of textarea

+ It is used as substitute for radio & checkbox.Attributes are:

Name: specifies select nameMultiple: specifies that more than one option can be selected.Size: specifies visible no. of rows.

Servlets

Page 17: Traning Report

+ Servlets are small programs written in Java executed in server. They are the server side applets.

+ Objective of servlets is to generate dynamic web pages. These dynamic web pages include security, user preferences & customization.

Software Requirements + Web Technologies

+ J2SE 5.0+ Web Server (Apache Tomcat*, JRun, Resin)+ Database

+ Enterprise Technologies+ J2EE 5.0This includes Java application server that is capable to execute both web &

enterprise applications and a database called Derby database.

Steps for installation 1. Install JDK 1.52. Set the path

To verifyStart | Run | cmd

C:\Windows\Desktop > java –version3. Install Apache Tomcat 4.x

To checka. Start | Programs | Apache Tomcat 4.1 | Start Tomcat

NOTE: Please don’t close the window, minimize it.b. Open Browser (IE)

http://localhost:8080/4. Set the CLASSPATH of servlet.jar.

NOTE: CLASSPATH is a java variable that defines the location of jar (class files)+ Start | Find | Files & Folders | servlets.jar

OR+ Start | Programs |Apache Tomcat 4.1 | Programs | Directory |

Common | Lib+ Copy path from address bar.

+ My Computer | Properties | Advanced | Environment Variables | System Variables

+ Select NEWVariable Name CLASSPATHVariable Value <paste the path>\servlet.jar;.;

To verify Start | Run | cmd

C:\Windows\Desktop >echo %CLASSPATH%Steps to write & execute “Hello World” program in servlets

1. Open notepad.2. Type the programimport java.io.*;import javax.servlet.*;

Page 18: Traning Report

import javax.servlet.http.*;public class Myservlet extends HttpServlet{

public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException

{PrintWriter out = response.getWriter();out.println("Hello World");

}}3. Save it as MyServlet.java4. Compile it MyServlet.class will be created.5. Copy .class to

Start | Programs | Apache Tomcat 4.1 | Programs Directory | WebApps | Examples | web-inf |classes

6. Open Browserhttp://localhost:8080/examples/servlet/MyServlet

NOTE: + Web Server should be running.+ Apache Tomcat is also known as container.7. When work is over

Start | Programs | Apache Tomcat 4.1 | Stop Tomcat

HttpRequest/Response Model

Page 19: Traning Report

+ Every request/response carries some data & headers.+ The headers that are delivered from client to server are called request headers.+ The headers that are delivered from server to client are called response headers.+ One of the important request headers is method.

+ Method can contain 7 possible values.1. GET

+ It is used to fetch details from server.+ Most browsers limit the data to 240 characters but IE 6 can support up to 1024 characters.+ This data is known as “Query String”.+ This gets appended at the end of the URL.+ Format

?var1=value1&var2=value2+ Query String starts with “?” and is separated by “&” and contains variables and its values.+ It is the default method.+ It is not a safe method as data is visible at address bar, history, favorites, and server log files.

2. POST+ It is used to send details to server.+ It can carry any size of data.+ This data is not visible.It is a safe method.

3. PUT+ It is used to place file on server.

4. DELETE+ It is used to delete file from server.

5. HEADER+ To check response header.

6. TRACE+ To check request header.

response

Web Server

DBA

Client

Browser Server Side

Services

request

Server

Makes use of

calls

Servlets

Receives request

Page 20: Traning Report

Servlet Basics

Page 21: Traning Report

+ Any servlet created by the user should implement Servlet interface.+ This done indirectly by inheriting GenericServlet or HttpServlet. + HttpServlet is also a derived class of GenericServlet.+ GenericServlet can give response to all requests including Http request.

ftp:// ftp requesttelnet:// telnet requesthttp:// http request

+ GenericServlet and its supporting classes come from javax.servlet package.+ HttpServlet and its supporting classes come from javax.servlet.http package.+ Both these packages come from Tomcat 4.1 servlet.jarTomcat 5.5 servlet-api.jarSun Application Server j2ee.jar

There are 3 methods in the lifecycle of Servlet

Page 22: Traning Report

public void init()// It is used for initialization// called only once when the Servlet is loaded in Web Servers memorypublic void service(ServletRequest req, ServletResponse res)// it is called for each Requestpublic void destroy()// It is used for releasing of resources.// called when the web server is closed.

Request+ To work on Request Servlet provides “HttpServletRequest”. + It comes from javax.servlet.http package.+ Request carries data & headers.String getParameter(String name)String[] getParameterValues(String name)Enumeration getParameterNames()

C:\Windows\Desktop>javap javax.servlet.http.HttpServletRequest + Used to list all the methods in the specified class

Execution of a Servlet+ There are 3 ways to execute/invoke a Servlet.

1. DirectlyStore:

<web server-root> | WebApps | examples | web-inf | classes Execute:

http://localhost:8080/examples/servlet/ServletName (on local machine)or

http://<ip-address-of host>:8080/examples/servlet/ServletName (on remote machine)2. HTML: On form submission

Store (Servlet):<web server-root> | WebApps | examples | web-inf | classes

Store (HTML):<web server-root> | WebApps | examples | servlets

In HTML form:<form method = “” action = “../servlet/ServletName”>

Execute:http://localhost:8080/examples/servlets/HTMLFile.html

3. HTML: Through HyperlinkStore (Servlet):

<web server-root> | WebApps | examples | web-inf | classesStore (HTML):

<web server-root> | WebApps | examples | servlets In HTML form:

<a href = “../servlet/ServletName”>link</a> Execute:

http://localhost:8080/examples/servlets/HTMLFile.html

Page 23: Traning Report

Fetching Headers from Request

Request-Headers (HttpServletRequest) To fetch request Headers methods are:1. Giving name & fetching value: (General Method)

String getHeader(String name)int getIntHeader(String name) Date getDateHeader(String name)Enumeration getHeaderNames()

2. Fetching individual headers (Specific Method)String getContentType()int getContentLength()String getMethod()String getRequestURI()String getProtocol()

Example:

Page 24: Traning Report

String x = request.getMethod();String y = request.getHeader(“Method”);String x = request.getContentType();String y = reuest.getHeader(“ContentType”);

Various HeadersAccept:

MIME types that are accepted by clients.User-Agent:

Browser and OS used by clients.Accept-Encoding:

Encoding formats supported by clients.Accept-Language:

Languages accepted by clients.Referer:

Specifies the referring page, if no page is there it returns null.Rediff referer is Null

SCA.com

MSN

Google

Protocol:Specifies protocol used EX. HTTP 1.1

ContentLength:Specifies the size of the content.

ContentType:Specifies the type of the content.

RequestURI:Specifies the requestURI used

Method:Specifies the method used.

URI: Universal Resource IdentifierEx. http://www.yahoo.com/images/abc.gif

URL: Universal Resource LocatorEx. http:// www.yahoo.com/images

.

Page 25: Traning Report

Response

Server Client+ To work on response, servlet provides “HttpServletResponse”.+ This class comes from javax.servlet.http package.+ There are two things carried along with response.

1. Data2. Headers

Response Headers+ Allow: methods allowed by server+ Cache-Control:

Possible value can be:public, private, no-cache, no-store, must-revalidate, proxy-revalidate, max-age =XXX,

s-max-age =XXX (in seconds)setHeader(“Cache-Control”, “no-cache”);setHeader(“Pragma”, “no-cache”);+ Connection: keep-alive, closed

Page 26: Traning Report

+ Content-Encoding+ Content-Language+ Content-Length+ Content-Type+ Expires+ Last-Modified+ Location: If changed what is the new location+ Pragma+ Refresh: specifies the time in seconds after which the page should be refreshed.

To set response header two methods are there1) General 2) Specific

General Method setHeader(String name, String value)setIntHeader(String name, int value)setDateHeader(String name, int value)

Specific MethodssetContentType(String contenttype)setContentLength(int length)

The HTTP Status Codes

HTTP 1.1 status codes can be classified in 5 gengeral categories 100-199:

Codes in 100’s are informational, indicating that client should respond with other action.

200-299:Codes in 200’s signify, that response was successful.

300-399:Values in the 300’s are used for files that have moved and usually include a location header indicating the new address.

400-499:Values in 400’s indicates an error by client.

500-599:Codes in the 500’s signify an error by server.

public void sendRedirect(String url)Pre-requisites

Page 27: Traning Report

+ PrintWriter should not be fetched and Content-Type should not be set. Reason: we are directing it so we should not fetch stream.+404

public void sendError(int code, String msg)

Cookies

+ Cookies are textual information stored by server on client machine.+ Maximum a client can have 20 cookies per site, 300 cookies in all and maximum

size per cookie is 4KB.Objective Of Cookie

Identification and CustomizationBenefits Of Cookies

+ Identifying a user during an e-commerce session.+ Remembering user name and password.+ Customizing sites+ Focusing Advertising

Some Problems with Cookies+ Security issues

To Delete all CookiesTools | Internet Options | Temporary internet files | Delete Cookies

Sending Cookies

Page 28: Traning Report

1. Create a cookie objectCookie c = new Cookie(“Name”, “Value”);2. Define the maximum age.c.setMaxAge(60*60*24*7); //seconds (1 week)3. Placing the cookie object into the HTTP response header.response.addCookie(c);

NOTE: These characters can’t be used in cookie value:[ ] ( ) = “ / ? @ : ;

Reading Cookies from Client1. Call request.getCookies methodCookie cookies[] = request.getCookies();2. Loop down the array, calling getName on each one until you find the cookie of

interest.for(int i = 0; i<cookies.length; i++){

String s =cookies[i].getName();if(s.equals(“Names”)){

val = s.getValue();break;

}}

Types of Cookies1. Session Cookie2. Persistent Cookie+ If no maxage is defined the maxage is -1 and it is a session cookie.

ConstructorCookie(String name, String value)

MethodsetValue(String value)getValue()String getName()setComment(String comment)String getComment()setMaxAge(int age)int getMaxAge()setVersion(int version)int getVersion()setSecure(boolean) // def: falseboolean getSecure()

Page 29: Traning Report

Session Tracking

Objective: To transfer data between pagesMethods of Session Tracking

1. Cookies2. URL Rewriting 3. Hidden form fields

Basics of Session Tracking1. Accessing the session object associated with the current request.2. Looking up the information associated with a session.3. Storing information in a session.4. Discarding session data.

1. Accessing the session object associated with the current requestTwo methods – fetch or create

HttpSession session = request.getSession(); //falseThis means fetch the session and don’t create a new session.HttpSession session = request.getSession(true);This means create a new session, data in the session will be lost.

Page 30: Traning Report

HttpSession session = request.getSession(false);This means fetch the session and don’t create a new session.

2. Looking up the information associated with a sessionObject value = session.getAttribute(“Name”);

3. Storing information in a sessionsession.setAttribute(“Name”, “Value”);

4. Discarding session datasession.removeAttribute(“Name”); //one variable & valuesession.invalidate(); //all valuessession.logout(); //all variables & values

+ To work on Session Tracking servlet provides HttpSession class.+ This class comes from javax.servlet.http package.Methods

Object getAttribute(String name)setAttribute(String name, Object value)removeAttribute(String name)Enumeration getAttributeNames()invalidate()logout()String getId()boolean isNew()long getCreationTime()long getLastAccessedTime()setMaxInactiveInterval(in seconds)int getMaxInactiveInterval()

Cookies v/s Session Tracking+ Objective of cookies is customization whereas session Tracking is used for

Transfering data from one page to another.+ Cookies can be persistent whereas session Tracking is always temporary.+ Cookies share the data in the form of text whereas session store the data in the

form of Object.+ There are some constraints with cookies (max 20), there are no such constraints

with session.

Page 31: Traning Report

Servlet Collaboration

+ Joining more than 1 servlet to generate the output.+ Obsolete Technologies

+ SSi (Server side Include)+ Servlet Chaining+ Servlet Tunnelling

+ Techniques of collaboration + Forward (Chaining & Tunnelling)+ Include (SSi)

+ To work on collaboration servlet provides RequestDispatcher class+ This class comes from javax.servlet.http package.

Collaboration ---------------- Forward+ works as a substitute to chaining & tunnelling.1. Fetch the RequestDispatcher2. Forward the control.

RequestDispatcher rd = request.getRequestDispatcher(“../servlet/Abc”);rd.forward(request, response);

Page 32: Traning Report

Collaboration ------------------ Include+ Works as a substitute to server side includes SSi.1. Fetch the RequestDispatcher2. Include another servlet

RequestDispatcher rd = request.getRequestDispatcher(“../servlet/Abc”);rd.include(request, response);

Sharing of data in Web Scope1. Page (Default)2. Request (Between 2 pages)3. Session (Between multiple pages for a single client)4. Application (Between mulitple pages for a multiple client)

+ Request Scope+ HttpServletRequest

setAttribute(String name, Object value)Object getAttribute(String name)removeAttribute(String name)

+ Session Scope+ HttpSession

setAttribute(String name, Object value)Object getAttribute(String name)removeAttribute(String name)

+ Application Scope+ ServletContext

setAttribute(String name, Object value)Object getAttribute(String name)removeAttribute(String name)

Logic+ Request Scope

+ A.javaString name = “Manish”;request.setAttribute(“Name”, name);RequestDispatcher rd =

request .getRequestDispatcher(“../servlet/B”);rd.forward(request, response);

+ B.javaString name =(String) request.getAttribute(“Name”);

+ Session Scope+ A.java

String name = “Manish”;HttpSession session = request.getSession();session.setAttribute(“Name”, name);RequestDispatcher rd =

request .getRequestDispatcher(“../servlet/B”);rd.forward(request, response);

+ B.javaHttpSession session = request.getSession();String name =(String) session.getAttribute(“Name”);

+ Application Scope+ To work on Application scope ServletContext class is used.

Page 33: Traning Report

+ This class comes from javax.servlet.http package.+ To fetch SevletContext

getServletContext()This method comes from HttpServlet class

+ A.javaString name = “Manish”;ServletContext sc = getServletContext();sc.setAttribute(“Name”, name);RequestDispatcher rd =

request .getRequestDispatcher(“../servlet/B”);rd.forward(request, response);

+ B.javaServletContext sc = getServletContext();String name =(String) sc.getAttribute(“Name”);

JDBC using Servlets

Sql.txtCreate table books(code number(5) Primary Key,

name varchar2(20), aname varchar2(20), pub varchar2(20), price number(8,2));

CREATE SEQUENCE books_seq START WITH 1;

+ Create all table and sequence+ Create a DSN by the name “emp”

Resource Bundle+ Based on unicode character System that java supports.

Steps to implement Resource Bundles

Page 34: Traning Report

+ We create a text file by the extension .properties.+ This text file contains pairs of key and values.+ We obtain the reference of the property in the servlet.+ Instead of using values directly, we fetch the values from property file by giving

the key.ResourceBundle bundle = Resource.getBundle(“NameOfPropertyFile”, locale);

+ ResourceBundle class comes from java.util package.+ getBundle takes two arguments -- name and locale (region)+To fetch value from property file

String value = bundle.getString(“key”);Benefits + Centralised updates

+ Internationalization (i18n)+ Changing labels without compilation

ListenersApplication Scope

+ Servlets 2.3 provides listeners for working on application scope.These listeners are:

javax.servlet.ServletContectListenerprovides handlers for context creation and destroy

javax.servlet.ServletContextAttributeListenerprovides handlers for context attributes added, removed and

replaced. javax.servlet.ServletContextListener

public void contextIntialized(ServletContextEvent sce)public void contextDestroyed(ServletContextEvent sce)

NOTE: Since SimpleServlet and MyContextListener are two independent programs hence the listener has to be told when to be executed hence its details are provided in the Web.xml with few tags as followed.<listener>

<listener-class>MyContextListener</listener-class> </listener>Also the entry made by the listener is on the server side not on the client side in our case the System.out.println refers to the Server.log file located in C:\Sun\Appserver\Domains\Domain1\Logs

javax.servlet.ServletContextAttributeListenerpublic void attributeAdded(ServletContextAttributeEvent sca)public void attributeRemoved(ServletContextAttributeEvent sca)public void attributeReplaced(ServletContextAttributeEvent sca)

+ Session Scope+ Servlets 2.3 provides listeners for working on session scope.

These listeners are:javax.servlet.http.HttpSessionListener

provides handlers for session creation and destroyjavax.servlet.http.HttpSessionAttributeListener

Page 35: Traning Report

provides handlers for session attributes added, removed and replaced.

javax.servlet.http.HttpSession Listenerpublic void sessionCreated(HttpSession Event hse)public void sessionDestroyed(HttpSession Event hse)

javax.servlet.http.HttpSessionAttributeListenerpublic void attributeAdded(HttpSessionBindingEvent hsbe)public void attributeRemoved(HttpSessionBindingEvent hsbe)public void attributeReplaced(HttpSessionBindingEvent hsbe)

HttpSessionBindingEvent classHttpSession getSession()String getName()Object getValue()

Filters

Requirements:1. Tracing inputs in form of request2. Tracing outputs in form of Response

Execution+ They are executed prior the request is given to servlet+ They are executed pror the response is delivered to client.

Methods in Life Cycle Of Filters+ init+ doFilter+ destroy

Details of Filter are specified in web.xml<filter>

<filter-name>SampleFilter</filter-name><filter-class> SampleFilter </filter-class>

</filter><filter-mapping>

<filter-name>SampleFilter</filter-name><url-pattern>/*</url-pattern>

</filter-mapping>

Filter Chaining+ write filter-name and filter-class for every process in both <filter>

and <filter-mapping>

JSP(Java Server Pages)

+ JSP like servlets is also used to generate dynamic web pages.+ These dynamic web pages includes security, user preferences (customization) &

database.

Page 36: Traning Report

+ JSP is called as reverse engineering of servlets.Servlet HTML within JavaJSP Java within HTML

+ It is also called cooked up servlets.

Steps to create & execute a JSP program1. Open Notepad2. Type the program3. Save it: Extension should be .jsp.

Eg. First.jsp4. Copy the .jsp file to <webserver-root> | Webapps | root5. Open browser

http://localhost:8080/First.jspThe simplest JSP program is to make an HTML file & make its extension as jsp & execute it.NOTE: The web server should be running.

Need & Benefits of JSP Need

1. It is hard to write & maintain HTML.2. You cannot make use of standard HTML tools.3. The HTML is inaccessible to non-java developers

Benefits1. It is easier to write & maintain HTML.2. You can make use of standard HTML tools.3. You can divide up development team.

LifeCycle of JSPJSP operations in various Scenarios

1. Calling java code directly within JSP (Scripting Elements)1. Expressions <%= %>2. Scriplets <% %>3. Declarations <%! %>

Expressions+ It is used to display value of a variable/objects.

Syntax:<%= Expressions %>

These variables/objects can be:1. Pre-defined 2. User-defined

Pre-defined objectsrequest HttpServletRequestresponse HttpServletResponseout JSPWriter (Advanced version of PrintWriter)session HttpSessionapplication ServletContextconfig ServletConfigpage this (Current page)

Scriplets

Page 37: Traning Report

+ It is used to write set of java statements within JSP page.Syntax

<%Java Statements

%>Declarations

+ It is used to declare member data or member functions within class that is created on conversion of JSP to servlet.Syntax

<%! Field declaration %/><%! Method declaration %/>

Expression:1. Expressions.jsp

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

Scriplet:1. BGColor.jsp

<HTML><HEAD>

<TITLE>Color Testing</TITLE></HEAD>

<% String bgColor = request.getParameter("bgColor");if ((bgColor == null) || (bgColor.trim().equals(""))) {

bgColor = "WHITE"; }

%><BODY BGCOLOR="<%= bgColor %>">

<H2 ALIGN="CENTER">Testing a Background of "<%= bgColor %>"</H2></BODY>

</HTML>

Declarations:AccessCounts.jsp

2. Calling external Java code within JSP JSP Page Directive

+ JSP page directive affects the overall structure of servlet being created.Syntax:

<%@ directive attribute = “value” %><%@ directive attribute1 = “value1”

attribute2 = “value2” ………………………….. attributeN = “valueN”

Page 38: Traning Report

%>In JSP there are three main types of directives

1. Page2. include3. taglib

The page directive lets you define one or more of the following attributes: import contentType pageEncoding session isELIgnored (JSP 2.0 only) buffer autoflush info errorPage isErrorPage isThreadSafe language extends

The IMPORT attribute+ By default the servlet import

+ java.lang.*+ java.servlet.*;+ java.servlet.http.*;+ java.servlet.jsp.*;

NOTE: + All classes created by user should be stored in a package.+ These packages are stored insideWebapps | root | web-inf | classes

To import classes syntax is:<%@page import = “package.class”%><%@page import = “package.class1, package.class2, ... , package.class3”%>

The CONTENTTYPE & PAGEENCODING Attribute<%@page contentType = “MIMI-TYPE”%>is same as<% response.setContentType(“MIME-TYPE”) %><%@page pageEncoding = “GZIP”%>is same as<% response.setHeader(“Content-Encoding”, “GZIP”) %>

The SESSION Attribute<%@page session = “true”%> <%--Default--%><%@page session = “false”%>

The ISELIGNORED Attribute+ The isELIgnored attribute (Expression language) – feature of JSP 2.0

<%@page isELIgnored = “true”%> <%--Default--%>

Page 39: Traning Report

<%@page isELIgnored = “false”%>

The BUFFER & AUTOFLUSH Attribute+ The buffer attribute specifies the size of buffer used by the out variable.

<%@ page buffer = “sizeKb”%><%@ page buffer = “none”%>

+ The default buffer size is server specific, but it should be less than 8 Kb.+ Incase of buffereing data can be forceably flushed using response.flushBuffer()

<%@page autoflush = “true”%> <%--Default--%><%@page autoflush = “false”%>

The INFO Attribute+ The info attribute defines a string that can be retrieved from the servlet by means

of the getServletInfo method.<%@ page info = “some msg”%>

The ERRORPAGE & ISERRORPAGE Attribute+ The errorPage attribute specifies a JSP page that should process any exceptions

thrown but not caught in the current page.<%@ page errorPage = “RelativeURL”%>

+ The exception thrown will automatically be available to the designated error page by means of the “exception” variable.

+ The isErrorPage attribute indicates whether or not the current page can act as the error page for another JSP page.<%@page isErrorPage = “true”%><%@page isErrorPage = “false”%> <%--Default--%>

The EXTENDS Attribute+ The extends attribute designates the superclass of the servlet that will be

generated for the JSP page.<%@ page extends = “package.class”%>

The LANGUAGE Attribute+ The language attribute is intended to specify the scripting language being used.

<%@ page language = “java”%>+ Java is both the default & the only legal choice.

The ISTHREADSAFE Attribute+ The isThreadsafe attribute controls whether the servlet that results from the JSP

page will allow concurrent access (the default) or will gurantee that no servlet instance processes more than one request at a time (isThreadSafe = “false”)<%@ page isThreadSafe = “false”%><%@ page isThreadSafe = “true”%> <%--Default--%>

3. Calling external files in JSP

Page 40: Traning Report

JSP:INCLUDE Action+ This helps you include the output of a page at request time.+ The following types of output can be included in a JSP page.

+ The content of an HTML document.+ The content of a plain text document.+ The output of the JSP page.+ The output of a servlet.

Syntax:<jsp:include page = “relative-url”></jsp:include>

OR<jsp:include page = “relative-url”/>

Attributes:+ page: specifies URL of the page to be included.+ flush: whether the main page should be flushed prior to inclusion, default: false.

The JSP:PARAM element+ At the sending end<jsp:include page = “relative-url”>

<jsp:params><jsp:param name = “bgcolor” value = “yellow” /><jsp:param name = “bgcolor” value = “yellow” />

</jsp:params></jsp:include>

+ <jsp:params>…</jsp:params> is used when more than one parameters are to be used.

Including files at Page Translation Time: The INCLUDE directive+ The include directive is used to include a file in the JSP document at the time the

document is translated into servlet (which is typically the first time it is accessed)Syntax:

<%@ include file = “relative-url”%>

4. Calling Applets wintin JSP

<jsp:plugin>…</jsp:plugin>Attributes of jsp:plugin

Type: applet/beanCode: specifies .class fileWidth: specifies width of applet.

Height: specifies height of applet.name: specifies name of applet.

+ To pass parameters to applet<jsp:param>

Name: specifies parameter nameValue: specifies parameter value

+ for multiple parameters<jsp:param> is written within

Page 41: Traning Report

<jsp:params>…</jsp:params>+ Incase the browser does not support java <jsp:fallback> can be used to work as alternative.<jsp:plugin type = “Applet” code = “MyApplet.class” width = 300 height = 300>NOTE: All class files used by Applet should be stored within webapps/root directory

4. Using Java Beans Components within JSP+ Benefits of Beans+ Creating Beans+ Installing Bean classes into server+ Accessing Bean Properties+ Explicitly setting bean properties+ Automatically setting bean properties from request parameters

Using beans basic Syntax JSP:USEBEAN

+ It is used to create a bean object.Attributes are:

id: specifies bean nameclass: specifies bean classscope: specifies bean scopetype: specifies bean type

JSP:GETPROPERTY+ This element reads and outputs the value of a bean property.Attributes are:name: specifies bean object nameproperty: specifies property name

<jsp:getProperty name = “beanName” property = “PropertyName” /> JSP:SETPROPERTY

+ This element modifies a bean property, it calls setXxx().Attributes are:name: specifies bean object nameproperty: specifies property namevalue: specifies new value

<jsp:setProperty name = “beanName” property = “PropertyName” value = “propertyValue” />Installing Bean ClassesNOTE: All beans should be packaged.Webapps | root | web-inf | classes | package

5. MVC using RequestDispatcher

Page 42: Traning Report

MVC Model: data (Bean)View: presentation/rendering (JSP)Controller: combines model with view (Servlet)

MVC applications can be classified in 2 categories:1. MVC Type 1 (Impure MVC)2. MVC Type 2 (Pure MVC)

MVC Type 2 ensures not even 1 scriplet/expression/declaration with JSP. JSP should be used only & only for output.MVC Type 2 can be implemented in multiple ways:

1. RequestDispatcher2. Struts3. Java Server Faces (JSF)

Objective: Implementing pure MVC using RequestDispatcherPre-requisties

1. <web server-root> | conf2. Open web.xml in notepad.3. F3 (find) | invoker & remove the comments4. Save the file & restart the server

6. EL (Expression Language)+ El is an important feature of JSP 2.0 not of 1.2.+ EL stands for Expression Language.+ EL is used for evaluating & outputting the values of java objects that are stored in

standard locations.+ The two important features of EL are

1. Evaluating2. Outputting

# Benefits of EL+ Concise access to stored objects .+ Shorthand notation for bean properties.+ Simple access to collection elements + Succint (short) access to request parameters, cookies, and other request data.+ A small but useful set of simple operators.+ Conditional output.+ Automatic type conversion.+ Empty values instead of error messages.

# Invoking the Expression Language${Expression}

# Accessing stored objects${varname}

http://localhost:8080/servlet/coreservlets.ScopedVars

# Accessing bean Properties${beanName.propertyName}

Page 43: Traning Report

# Accessing Collections through EL${attributeName[entryName]}${attributeName.entryName}

Both for key${attributeName[index]}

For index

# Accessing implicit ObjectsThese includes pageContent, paramValues, header, headerValues, cookie

Syntax: object.propertyName# EL Operators

+ Arithmetic Operators+, -, *, / or div, % or mod

+ Relational Operators== or eq, != or ne, < or lt, > or gt, <= or le, >= or ge

+ Empty OperatorsThis operator returns true if value is null else false

+ Logical Operators&& and, || or, ! not

# Evaluting Expressions Conditionally${test ? Expression1 : Expression2}

7. JSTL (Java Server Tag Libraries)+ Can be in the form of

1. pre-defined TAG/Standard TAG Library2. User-defined TAG/Custom TAG Library

1. Create your own TAG in the form of a file+ The name of the file will be the name of the TAG.+ Extension of this file should be .tag.+ This file can be stored in any of the directories within web-inf directory.+ This Directory (where .tag files are stored) is refered as tag library

2. Call this directory within your JSP page.<%@ taglib prefix = “tags” tagdir = “/web-inf/tags” %>Over here,

prefix: It is used to refer tags from tag librarytagdir: it specifies the directory name (location)

8. jdbc (Benefits of ConnectionPool)

+ Limiting/Sharing number of connections+ Speed+ Centralized update for all database operations

Data:static final int MAX_CONNECTIONS = 20;static Vector connections = null;

Page 44: Traning Report

static ConnectionPool instance = null;public void initialize()

// creates pool of MAX_CONNECTIONS if connection is null.public void removeAllConnections()// executes loop (size of vector) and closes all connections and set vector to null.public Connection getConnection()// fetches a single connection from vector, if vector is not null and size if greater than 0public void putConnection(Connection)// adds a connection back to pool and notifies.public static ConnectionPool getInstance()// returns a common object of ConnectionPool if existing, else it creates and returns

//first personConnectionPool cp;cp = ConnectionPool.getInstance();cp.initialize();Connection con = cp.getConnection();

//Statement//executeQuery or executeUpdate

cp.putConection(con);//second person

ConnectionPool cp;cp = ConnectionPool.getInstance();cp.initialize();Connection con = cp.getConnection();

//Statement//executeQuery or executeUpdate

cp.putConection(con);

Assignments given:Design Forms:-

After the form is crafted, how the form will be appear, just design it on the paper. Ex In our project, a single form allows –

o Inserting data into tableo Updating data already existing in tableo Viewing of data available in tableo Deleting data from table

Design structure of forms with command buttons on it.

Solution:

Course .java(servlet)

import java.io.*;import javax.servlet.*;import javax.servlet.http.*;

Page 45: Traning Report

import java.sql.*;import java.util.*;public class Course extends HttpServlet{

Connection conn=null;Statement stmt = null;ResultSet rs;

---------------------------Register Driver---------------------------------------------------public void init(){

try{DriverManager.registerDriver(new sun.jdbc.odbc.JdbcOdbcDriver());conn=DriverManager.getConnection("jdbc:odbc:MyDsn","scott","tiger"); System.out.println("Database Connection Established");}

catch(Exception e){System.out.println("Sorry failed to connect to the DataBase." +e.getMessage());}}

//--------------------------------------------------------------------------------------public void doGet(HttpServletRequest request,HttpServletResponse response) throws

ServletException, IOException{

response.setContentType("text/html");PrintWriter out=response.getWriter();int y=0;int x=0;out.println("<html><head><title>Welcome to World</title>");

//-----------------------------------------------------------------java script----------------out.println("<script>");out.println("function abc() {");out.println("if (document.thisform.name.value==0) {");out.println("alert('Invalid name.');");out.println("return false; }");out.println("if (document.thisform.ctype.value==0) {");out.println("alert('Invalid course type');");out.println("return false; }");out.println("if (document.thisform.duration.value==0) {");out.println("alert('Invalid duration');");out.println("return false; }");out.println("if (document.thisform.semester.value==0) {");out.println("alert('Invalid Semester');");out.println("return false; }");out.println("document.thisform.submit();");out.println("return false; }");out.println("function setEditMode(id,nm,ctp,dura,sem)");out.println("{");

Page 46: Traning Report

out.println("document.thisform.hiddenid.value=id;");out.println("document.thisform.name.value=nm;");out.println("document.thisform.ctype.value=ctp;");out.println("document.thisform.semester.value=sem;");out.println("document.thisform.hidMode.value='U';");out.println("}");out.println("function setDelMode()");out.println("{");out.println("document.thisform.hidMode.value='D';");out.println("formDeleteValues('hidSelDel');");out.println("}");out.println("function formDeleteValues(hidden)");out.println("{");out.println("var selval=\" \"; ");out.println("for(i=0;i<document.forms[0].elements.length;i++)");out.println("{");out.println("if(document.forms[0].elements[i].type == \"checkbox\")");out.println("{");out.println("if(document.forms[0].elements[i].checked == true) {");out.println("selval=selval + document.forms[0].elements[i].value + \",\" ;");out.println("}");out.println("}");out.println("}");out.println("if(selval.length < 1)");out.println("{");out.println("alert(\"Please choose records you wish to delete.\");");out.println("}");out.println("else");out.println("{");out.println("selval=selval.substring(0,selval.length-1);");out.println("eval(\"document.forms[0].\" +hidden+\".value = '\"+selval+\"'\");");out.println("document.forms[0].submit(); } }");out.println("</script></head>");

//---------------------------------------------------------------------body------------------out.println("<body bgcolor='rgb(255,210,117)'>");int id=0;

//---------------------------------------------------------------Insert-----------------------int semester=0;if ("I".equals(request.getParameter("hidMode")) && conn != null){

String name=request.getParameter("name");if(name==null){

name=" ";}else{

name=request.getParameter("name");}String ctype=request.getParameter("ctype");

Page 47: Traning Report

if(ctype==null){

ctype=" ";}else{

ctype=request.getParameter("ctype");}String duration=request.getParameter("duration");if(duration==null){

duration=" ";}else{

duration=request.getParameter("duration");}String sem1=request.getParameter("semester");if(sem1==null){

semester=0;}else{

semester=Integer.parseInt(sem1);}try{

stmt = conn.createStatement(); String sql=new String();sql="select max(id) from Course";rs=stmt.executeQuery(sql);boolean b = rs.next();if(b){

x = rs.getInt(1);}else{

x = 0;}x=x+1;id=x;

if(name.length() >= 1 && ctype.length() >= 1 && duration.length() >= 1 && sem1.length() >= 1)

{stmt=conn.createStatement();

sql="Insert into Course values("+ id +",'"+ name +"','"+ ctype +"','"+ duration +"',"+ semester +")";

Page 48: Traning Report

System.out.println(sql);y=stmt.executeUpdate(sql);

}else{

out.println("Details cannot be left blank");}

}catch(Exception e){

out.println("Sorry! Failed 2 insert values into the Database."+e.getMessage());

}

}

//----------------------------------------------------------------------------update---------if("U".equals(request.getParameter("hidMode")) && conn != null){

String name=request.getParameter("name");if(name==null){

name=" ";}else{

name=request.getParameter("name");}String ctype=request.getParameter("ctype");if(ctype==null){

ctype=" ";}else{

ctype=request.getParameter("ctype");}String duration=request.getParameter("duration");if(duration==null){

duration=" ";}else{

duration=request.getParameter("duration");}String sem1=request.getParameter("semester");if(sem1==null){

Page 49: Traning Report

semester=0;}else{

semester=Integer.parseInt(sem1);}try{

stmt=conn.createStatement();String sql4=new String();

sql4="update Course set name='"+ name + "',ctype='"+ctype +"',duration='"+ duration +"',semester="+semester + " where id="+ Integer.parseInt(request.getParameter("hiddenid"));

System.out.println(sql4);stmt.executeUpdate(sql4);response.sendRedirect("../servlet/Course");

}catch(Exception e){

out.println("Sorry! Failed 2 update values in the database"+ e.getMessage());

}

}//--------------------------------------------------------------------------Delete------------

if("D".equals(request.getParameter("hidMode")) && conn != null){

try{

stmt=conn.createStatement();String sql5=new String();

sql5="delete from Course where id IN("+ request.getParameter("hidSelDel") +") ";System.out.println(sql5);stmt.executeUpdate(sql5);response.sendRedirect("../servlet/Course");

}catch(Exception e){

out.println("Sorry failed 2 delete values from the database" + e.getMessage());

}}

//--------------------------------------------------------------------------html--------------out.println("<form name='thisform' action='../servlet/Course'>");out.println("<input type='hidden' name='hidMode' value='I'>");out.println("<input type='hidden' name='hiddenid' value=id>");out.println("<input type='hidden' name='hidSelDel' >");out.println("<table align='center' bgcolor='rgb(255,210,117)' width='50%'>");out.println("<tr>");out.println("<td>");ServletContext app = getServletContext();

Page 50: Traning Report

RequestDispatcher dispatcher =app.getRequestDispatcher("/Menu.jsp"); dispatcher.include(request,response);

out.println("</td></tr><br><br><br><tr height='200'>");out.println("<td align='center' colspan='10'>");out.println("<table align='center' bgcolor='rgb(255,210,117)' border='1'

bordercolor='maroon' cellpadding='2' cellspacing='0' width='100%'>");out.println("<tr><td align='left' colspan='2' bgcolor='maroon'>");out.println("<font color='rgb(255,210,117)' ><b>Course

Details</b></font></td></tr>");out.println("<tr><th align='right'>Name</th>");out.println("<td><input type='text' name='name' size='25'></td></tr>");out.println("<tr><th align='right'>Course type</th>");out.println("<td><input type='text' name='ctype' size='25'></td></tr>");out.println("<tr><th align='right'>Duration</th>");out.println("<td><input type='text' name='duration' size='25'></td></tr>");out.println("<tr><th align='right'>Semester</th>");out.println("<td><Select name='semester'><option value='1'>Sem1<option

value='2'>Sem2<option value='3'>Sem3<option value='4'>Sem4<option value='5'>Sem5<option value='6'>Sem6<option value='7'>Sem7<option value='8' selected>Sem8</Select></td></tr>");//---------------------------------------------------------------------------------------------

out.println("<tr><td colspan='2' align='right'><input type='submit' value='Save' onClick='return abc();'>");

out.println("<input type='reset' value='Reset'></td></tr></table>");out.println("</td></tr></table>");if(conn != null){

try{

stmt=conn.createStatement();String sql2=new String();sql2="Select * from Course";ResultSet rs1=stmt.executeQuery(sql2);out.println("<br><br><table align='center' border='1' width='50%'

bordercolor='skyblue'>");out.println("<tr bgcolor='black'>");out.println("<td width='12%' align='center' ><input type='button'

name='cmdDelete' value='Delete' onClick='setDelMode();'></td>");out.println("<td><font color='#FFFFFF'>Name</font></td>");out.println("<td><font color='#FFFFFF'>Course type</font></td>");out.println("<td><font color='#FFFFFF'>Duration</font></td>");out.println("<td><font color='#FFFFFF'>Semester</font></td>");out.println("</tr>");int id1,semester1;String name1,ctype1,duration1;if(rs1 != null){

while(rs1.next()){

out.println("<tr>");

Page 51: Traning Report

id1=Integer.parseInt(rs1.getString("id")); name1=rs1.getString("name");ctype1=rs1.getString("ctype");duration1=rs1.getString("duration");

semester1=Integer.parseInt(rs1.getString("semester"));

//---------------------------------------------------------------------------------------------out.println("<td><input type='checkbox' name='chk"+id1+"' value=" + id1

+"></td>");out.println("<td style=\"cursor:pointer\"

onMouseDown=\"setEditMode('"+ id1 +"','"+ name1 +"','"+ ctype1 +"','"+ duration1 +"','"+ semester1 +"');\">" + name1 + "</td>");

out.println("<td style=\"cursor:pointer\" onMouseDown=\"setEditMode('"+ id1 +"','"+ name1 +"','"+ ctype1 +"','"+ duration1 +"','"+ semester1 +"');\">" + ctype1 + "</td>");

out.println("<td style=\"cursor:pointer\" onMouseDown=\"setEditMode('"+ id1 +"','"+ name1 +"','"+ ctype1 +"','"+ duration1 +"','"+ semester1 +"');\">" + duration1 + "</td>");

out.println("<td style=\"cursor:pointer\" onMouseDown=\"setEditMode('"+ id1 +"','"+ name1 +"','"+ ctype1 +"','"+ duration1 +"','"+ semester1 +"');\">" + semester1 + "</td>");

out.println("</tr>");}

}out.println("</table>");

} catch(Exception e)

{out.println("Sorry Failed to execute the Query." +e.getMessage());

}}out.println("</form>");out.println("</body></html>");

}}

Remaining servlets were similar with there respective details. In our Project, the designing of the form will appear like –

Page 52: Traning Report
Page 53: Traning Report
Page 54: Traning Report
Page 55: Traning Report

Lesson learned: I have learned during the training session the language ADVANCE JAVA and how to design the WEB PAGES and how to make the web sites in the web.