Professional Documents
Culture Documents
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)
DEPARTMET OF COMPUTER SCIENCE & ENGINEERING THAKRAL COLLEGE OF TECHNOLOGY, BHOPAL (M.P.) SESSION Dec-2011
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
ORGANIZATION
DIRECTOR
CHART
OFFICE INCHARE
PEON
LAB INSTRUCTER
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. HCLs, 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. HCLs 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 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 HCLs 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 HCLs 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. HCLs 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 4094357,4094852) Center Bhopal (Ph
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
Front End
Middleware
Front End (HTML/Applet) Middleware (Servlets/JSP/JSF) Back End n-tier (Enterprise Technologies) Front End (HTML/Applet) Middleware (Servlets/JSP/JSF) Business Logic (EJB) Back End
Back End
Front End
mobile
Middleware
Front End
Web tech.
Business logic
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 Scripting Generates dynamic web pages that include security, database & customization.
HTML
+ 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 TAGS 2. Formatting TAGS 3. Lists 4. Tables 5. Inter and Intra document Links 6. Forms 7. 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. Head 2. 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.
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
<font name = Arial, Algerian size = 4 color =red> Hello </font> <font color = #ff0000> hello </font> Format = #rrggbb rr, gg, bb can go from 00 to ff (0 to 255) <pre> This is for pre-formatted text </pre> <pre> One Two Three Four 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 H 2O <address> This is used for writing web addresses </address> EX. <address> manish@hotmail.com </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
HTML supports 3 types of List 1. Ordered List 2. Unordered List 3. Definition List Ordered List <ol> <LI> This is Point one <LI> This is Point one <LI> This is Point one </ol> ol: ordered list li: list index <ol start = 6> <LI> This is Point one <LI> This is Point one <LI> This is Point one </ol> Unordered List ul: 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 | 6. This is Point One | 7. This is Point One | 8. 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>
Links in HTML
There are 2 types of Links 1. Inter-document links (between 2 pages) 2. Intra-document links (within a page) To create links HTML provides <a>.....</a> Attributes: Name : Specifies anchor name href : Specifies hypertext reference target : Specifies target frame To create intra document link 1. 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 file border: specifies border width width: specifies width of image height: specifies height of image alt: 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 width cellspacing: Specifies space between 2 cells cellpadding: Specifies space within a cell bgcolor: Specifies background color border: Specifies border width
Frames
<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 details cols : 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 name method: GET or POST GET is used to fetch details from server POST 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 text 2. TextArea: To accept multiline text 3. Password: To accept passwords 4. Button: To Trigger an action 5. 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 form 7. Hidden: To create a hidden form field. 8. Checkbox: To select one or more options 9. Radio: To select one out of multiple
10. 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> + It is used to create multiline text. Attributes are: rows: specifies no. of rows columns: specifies no. of columns name: specifies name of textarea + It is used as substitute for radio & checkbox. Attributes are: Name: specifies select name Multiple: specifies that more than one option can be selected. Size: specifies visible no. of rows.
Servlets
+ 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.0 This includes Java application server that is capable to execute both web & enterprise applications and a database called Derby database.
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 NEW Variable Name CLASSPATH Variable Value <paste the path>\servlet.jar;.; To verify Start | Run | cmd C:\Windows\Desktop >echo %CLASSPATH%
1. Open notepad. 2. Type the program import java.io.*; import javax.servlet.*; 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.java 4. 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 Browser http://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
+ 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.
Server Client
request
Receives request
Browser
response
Web Server
calls
DB A
Makes use of
Servlets
+ 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.
Servlet Basics
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 request telnet:// telnet request http:// 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.jar Tomcat 5.5 servlet-api.jar Sun Application Server j2ee.jar + + + +
There are 3 methods in the lifecycle of Servlet public void init() // It is used for initialization // called only once when the Servlet is loaded in Web Servers memory public void service(ServletRequest req, ServletResponse res) // it is called for each Request public 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. Directly Store: <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 Hyperlink Store (Servlet): <web server-root> | WebApps | examples | web-inf | classes Store (HTML): <web server-root> | WebApps | examples | servlets In HTML form: <a href = ../servlet/ServletName>link</a> Execute: http://localhost:8080/examples/servlets/HTMLFile.html
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: String x = request.getMethod(); String y = request.getHeader(Method); String x = request.getContentType(); String y = reuest.getHeader(ContentType); Various Headers Accept: 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
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 Identifier Ex. http://www.yahoo.com/images/abc.gif URL: Universal Resource Locator Ex. http:// www.yahoo.com/images .
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. Data 2. 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 + 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 there 1) General 2) Specific General Method setHeader(String name, String value) setIntHeader(String name, int value) setDateHeader(String name, int value) Specific Methods setContentType(String contenttype) setContentLength(int length)
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 Customization Benefits 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 Cookies Tools | Internet Options | Temporary internet files | Delete Cookies Sending Cookies 1. Create a cookie object Cookie 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 cant be used in cookie value: []()=/?@:; Reading Cookies from Client 1. Call request.getCookies method Cookie 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 Cookies 1. Session Cookie 2. Persistent Cookie + If no maxage is defined the maxage is -1 and it is a session cookie. Constructor Cookie(String name, String value) Method setValue(String value)
getValue() String getName() setComment(String comment) String getComment() setMaxAge(int age) int getMaxAge() setVersion(int version) int getVersion() setSecure(boolean) // def: false boolean getSecure()
Session Tracking
Objective: To transfer data between pages Methods of Session Tracking 1. Cookies 2. URL Rewriting 3. Hidden form fields Basics of Session Tracking 1. 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 request Two methods fetch or create HttpSession session = request.getSession(); //false This means fetch the session and dont create a new session. HttpSession session = request.getSession(true); This means create a new session, data in the session will be lost. HttpSession session = request.getSession(false); This means fetch the session and dont create a new session. 2. Looking up the information associated with a session Object value = session.getAttribute(Name); 3. Storing information in a session session.setAttribute(Name, Value); 4. Discarding session data session.removeAttribute(Name); //one variable & value session.invalidate(); //all values session.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.
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 RequestDispatcher 2. Forward the control. RequestDispatcher rd = request.getRequestDispatcher(../servlet/Abc); rd.forward(request, response); Collaboration ------------------ Include + Works as a substitute to server side includes SSi. 1. Fetch the RequestDispatcher 2. Include another servlet RequestDispatcher rd = request.getRequestDispatcher(../servlet/Abc); rd.include(request, response);
1. 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.java String name = Manish; request.setAttribute(Name, name); RequestDispatcher rd = request .getRequestDispatcher(../servlet/B); rd.forward(request, response); + B.java String 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.java HttpSession session = request.getSession(); String name =(String) session.getAttribute(Name); + Application Scope + To work on Application scope ServletContext class is used. + This class comes from javax.servlet.http package. + To fetch SevletContext getServletContext() This method comes from HttpServlet class + A.java String name = Manish; ServletContext sc = getServletContext(); sc.setAttribute(Name, name); RequestDispatcher rd = request .getRequestDispatcher(../servlet/B); rd.forward(request, response); + B.java ServletContext sc = getServletContext(); String name =(String) sc.getAttribute(Name);
Resource Bundle
+ Based on unicode character System that java supports.
+ 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
Listeners
Application Scope
+ Servlets 2.3 provides listeners for working on application scope. These listeners are: javax.servlet.ServletContectListener provides handlers for context creation and destroy javax.servlet.ServletContextAttributeListener provides 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.ServletContextAttributeListener public 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 destroy javax.servlet.http.HttpSessionAttributeListener provides handlers for session attributes added, removed and replaced. javax.servlet.http.HttpSession Listener public void sessionCreated(HttpSession Event hse) public void sessionDestroyed(HttpSession Event hse) javax.servlet.http.HttpSessionAttributeListener public void attributeAdded(HttpSessionBindingEvent hsbe) public void attributeRemoved(HttpSessionBindingEvent hsbe) public void attributeReplaced(HttpSessionBindingEvent hsbe) HttpSessionBindingEvent class HttpSession getSession() String getName() Object getValue()
Filters
Requirements: Execution
1. Tracing inputs in form of request 2. Tracing outputs in form of Response + They are executed prior the request is given to servlet + They are executed pror the response is delivered to client.
<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>
Benefits 1. It is easier to write & maintain HTML. 2. You can make use of standard HTML tools. 3. You can divide up development team.
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
LifeCycle of JSP
JSP operations in various Scenarios
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
+ These packages are stored inside Webapps | root | web-inf | classes To import classes syntax is: <%@page import = package.class%> <%@page import = package.class1, package.class2, ... , package.class3%>
+ 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.
<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%>
Using beans basic Syntax JSP:USEBEAN + It is used to create a bean object. Attributes are: id: specifies bean name
JSP:GETPROPERTY
+ This element reads and outputs the value of a bean property. Attributes are: name: specifies bean object name property: 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 name property: specifies property name value: specifies new value <jsp:setProperty name = beanName property = PropertyName value = propertyValue /> Installing Bean Classes NOTE: All beans should be packaged. Webapps | root | web-inf | classes | package
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. Evaluating 2. 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.
${varname} http://localhost:8080/servlet/coreservlets.ScopedVars
${beanName.propertyName}
# EL Operators
+ Arithmetic Operators +, -, *, / or div, % or mod + Relational Operators == or eq, != or ne, < or lt, > or gt, <= or le, >= or ge + Empty Operators This operator returns true if value is null else false + Logical Operators && and, || or, ! not
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 table o Updating data already existing in table o Viewing of data available in table o 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.*; 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("{"); 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"); 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 +")"; 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) { 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(); 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>"); 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
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.