You are on page 1of 20

Pragma Infotech

JSP July-2009(ITA)
5(b) i) Scriptlet for delete cookie from a JSP page html> < head> < title>< /title> < script language="Javascript"> function loaded() { document.cookie = "v0=1;"; document.cookie = "v1=2;"; alert(document.cookie); } function deletecook() { var d = new Date(); document.cookie = "v0=1;expires=" + d.toGMTString() + ";" + ";"; alert(document.cookie); } < /script> < /head>

Pragma Infotech < body onload="loaded();"> < a href="javascript:deletecook();">delete cookie< /a> < /body> < /html> ii) Read a file from a JSP code: <%@page import="java.io.*"%> <%@page import="java.io.FileInputStream"%> <% BufferedReader input = new FileReader("D:/aa.txt")); String line = ""; while ((line = input.readLine()) != null) { out.println(line); } input.close(); %>

BufferedReader(new

May-June-2008(ITA)
4(b)
1)
Include directives(< @ include file= relativeURL >) It include static resource at translation time.When using the include directive, the combined contents of the original JSP page and all its included resources are translated into the same implementation servlet i.e. the contents of the included resource is copy pasted before translation to a servlet. The important thing here is that all this happens during translation time and only static content is supported. jsp:include(<jsp:include page=?relativeURL? />) It include static or dynamic contant at run time. This allows us to include both static and dynamic content into the JSP page. Using the jsp action also allows you to explicitly pass parameters to the included page.

Pragma Infotech

4) JSP Scripting Elements i)JSP Expressions A JSP expression is used to insert Java values directly into the output. It has the following form: <%= Java Expression %> ii) JSP Scriptlets If you want to do something more complex than insert a simple expression, JSP scriptlets let you insert arbitrary code into the servlet method that will be built to generate the page. Scriptlets have the following form: <% Java Code %> iii) JSP Declarations A JSP declaration lets you define methods or fields that get inserted into the main body of the servlet class (outside of the service method processing the request). It has the following form: <%! Java Code %>

5)(a) Model±view±controller (MVC) is a software architecture, currently considered an architectural pattern used in software engineering. The pattern isolates "domain logic" (the application logic for the user) from the user interface (input and presentation), permitting independent development, testing and maintenance of each. Introduction to MVC(Model View Controler) Struts : Struts is an open source framework from Jakartha Project designed for developing the web applications with Java SERVLET API and Java Server Pages Technologies.Struts conforms the

Pragma Infotech Model View Controller design pattern. Struts package provides unified reusable components (such as action servlet) to build the user interface that can be applied to any web connection. It encourages software development following the MVC design pattern. Overview of MVC Architecture The MVC design pattern divides applications into three components: * The Model maintains the state and data that the application represents . * The View allows the display of information about the model to the user. * The Controller allows the user to manipulate the application . Example: Example Here is a simple application of the pattern, implementing Java Servlets and JavaServer Pages from Java EE: Model The model is a collection of Java classes that form a software application intended to store, and optionally separate, data. A single front end class that can communicate with any user interface (for example: a console, a graphical user interface, or a web application). View The view is represented by a JavaServer Page, with data being transported to the page in the HttpServletRequest or HttpSession. Controller

Pragma Infotech The Controller servlet communicates with the front end of the model and loads the HttpServletRequest or HttpSession with appropriate data, before forwarding the HttpServletRequest and Response to the JSP using a RequestDispatcher. The Servlet is a Java class, and it communicates and interacts with the model, but does not need to generate HTML or XHTML output; the JSPs do not have to communicate with the model because the Servlet provides them with the information²they can concentrate on creating output. In Struts, the view is handled by JSPs and presentation components, the model is represented by Java Beans and the controller uses Servlets to perform its action. By developing a familiar Web-based shopping cart, you'll learn how to utilize the Model-View-Controller (MVC) design pattern and truly separate presentation from content when using Java Server Pages. Applying MVC in Servlets and JSP Many web applications are JSP-only or Servlets-only. With JSP, Java code is embedded in the HTML code; with Servlets the Java code calls println methods to generate the HTML code. Both approaches have their advantages and drawbacks; Struts gathers their strengths to get the best of their association. View on JSP The early JSP specification follows two approaches for building applications using JSP technology. These two approaches are called as JSP Model 1 and JSP Model 2 architectures.

Pragma Infotech JSP Model 1 Architecture In Model 1 architecture the JSP page is alone responsible for processing the incoming request and replying back to the client. There is still separation of presentation from content, because all data access is performed using beans. Although the JSP Model 1 Architecture is more suitable for simple applications, it may not be desirable for complex implementations.

JSP Model 2 Architecture - MVC The Model 2 Architecture is an approach for serving dynamic content, since it combines the use of both Servlets and JSP. It takes advantages of the predominant strengths of both technologies, using JSP to generate the presentation layer and Servlets to perform process-intensive tasks. Here servlet acts as controller and is in charge of request processing and the creation of any beans or objects used by the JSP as well as deciding depending on the user¶s actions, which JSP page to forward the request to. Note that there is no processing logic within the JSP page itself; it is simply responsible for retrieving any objects or beans that may have been previously created by the servlet, and extracting the dynamic content from that servlet for insertion within static templates. Limitation in traditional MVC approach The main limitation in the traditional MVC approach is, in that there is no separation of business logic (validation/ conditions/ anything related to business rules) from controller (is responsible for controlling of the application flow by using static/dynamic request dispatcher. MVC Model 2 Architecture is Model View Controller 1.Client submits login request to servlet application 2.Servlet application acts as controller it first decides to request validator another servlet program which is responsible for not null

Pragma Infotech checking (business rule) 3.control comes to controller back and based on the validation response, if the response is positive, servlet controller sends the request to model 4.Model requests DB to verify whether the database is having the same user name and password, If found login operation is successful 5.Beans are used to store if any data retrieved from the database and kept into HTTPSession 6.Controller then gives response back to response JSP (view) which uses the bean objects stored in HTTPSession object OR 5)(a)
JSP and ASP often use the same tags: Code <% code in java or VBScript %> Expression <%= expression %>
However, VBScript uses a single quote to start a comment while Java uses two slashes to start a comment on the same line.

Common Expressions:
ComDescription JSP

Writing HTML out.print("Some HTML code"); code Obtaining a request.getParameter("parameterName") parameter value Null value null Nothings ASP Technology JSP Technology

ASP Response.Write "Some HTML code" Request("parameterName")

Pragma Infotech

Reusable, Cross-Platform No Components Security Against System Crashes No

JavaBeans, Enterprise JavaBeans, custom JSP tags Yes

Memory Leak Protection No Scripting Language VBScript, JScript No

Yes Java

Customizable Tags

Yes

Web Server

Microsoft IIS or Personal Web Server Microsoft Windows

Any Web server, including Apache, Netscape, and IIS Most popular platforms, including the Solaris Operating Environment, Microsoft Windows, Mac OS, Linux, and other UNIX platform implementations

Platforms

Reusable, Cross-Platform No Components Security Against System Crashes No

JavaBeans, Enterprise JavaBeans, custom JSP tags Yes

Pragma Infotech

Memory Leak Protection Scripting Language

No VBScript, JScript No

Yes Java

Customizable Tags

Yes

5)(b) y A "cookie" is a small piece of information sent by a web server to store on a web browser so it can later be read back from that browser. This is useful for having the browser remember some specific information y The WWW is built on a very simple, but powerful premise. y All material on the Web is formatted in a general, uniform format called HTML (Hypertext Markup Language), and all information requests and responses conform to a similarly standard protocol. y The Web server will respond to the request by transmitting the desired information to the user's computer. y There, the user's browser will display the received information on the user's screen. Cookies are pieces of information generated by a web server or web hosting sites and stored in the user's computer, ready for future access. y Cookies are embedded in the HTML information flowing back and forth between the user's computer and the servers. y Cookies were implemented to allow user-side customization of Web information. y For example, cookies are used to personalize Web search engines, to allow users to participate in WWW-wide contests (but only once!), and to store shopping lists of items a user has selected while browsing through a virtual shopping mall. Essentially, cookies make use of user-specific information transmitted

Pragma Infotech
by the Web server onto the user's computer so that the information might be available for later access by itself or other servers. In most cases, not only does the storage of personal information into a cookie go unnoticed, so does access to it. Web servers automatically gain access to relevant cookies whenever the user establishes a connection to them, usually in the form of Web requests. Cookies are based on a two-stage process. First the cookie is stored in the user's computer without their consent or knowledge. For example, with customizable Web search engines like My Yahoo!, a user selects categories of interest from the Web page. The Web server then creates a specific cookie, which is essentially a tagged string of text containing the user's preferences, and it transmits this cookie to the user's computer. The user's Web browser, if cookie-savvy, receives the cookie and stores it in a special file called a cookie list. This happens without any notification or user consent. As a result, personal information (in this case the user's category preferences) is formatted by the Web server, transmitted, and saved by the user's computer. During the second stage, the cookie is clandestinely and automatically transferred from the user's machine to a Web server. Whenever a user directs her Web browser to display a certain Web page from the server, the browser will, without the user's knowledge, transmit the cookie containing personal information to the Web server. Example: JSP1.jsp takes name and department <%@page contentType="text/html"%> <%@page pageEncoding="UTF-8"%> <%@page import="java.sql.*"%> <%@page import="java.util.*"%> <body> <form name="frm"> <table width="100" border="0" cellspacing="2" cellpadding="2"> <tr>

y y

y

y

y y y

Pragma Infotech
<h6><th scope="row">Name</th></h6> <td><input type="text" name="txtname" id="txtname" /></td> </tr> <tr> <h6><th scope="row">department</th></h6> <td><input type="text" name="txtdepartment" id="txtdepartment" /></td> </tr> <% String name = request.getParameter("txtname"); String de = request.getParameter("txtdepartment"); Connection con=null; try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); con = DriverManager.getConnection("jdbc:odbc:dsn","",""); String Query=""; Query="select * from tbl where Name='" + name + "' and department= '" + de + "' "; Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(Query); ResultSetMetaData rsmd=rs.getMetaData(); if(rs.next()) { if(Username.toLowerCase().trim().equals("admin") Password.toLowerCase().trim().equals("admin")) { response.sendRedirect("admin_home.jsp"); session.setAttribute("txtname", name); } else { response.sendRedirect("JSP2.jsp"); session.setAttribute("txtname", name); session.setAttribute("txtdepartment", de); }

&&

Pragma Infotech
} } catch(Exception ex) { //out.println(ex.getMessage()); } %> Passes the values to the corosponding JSP2 JSP2.jsp <% String nm = request.getParameter("txtname"); String de = request.getParameter("txtdepartment"); String a = (String)session.getAttribute("nm´); String b = (String)session.getAttribute("de´); %> Values displayed on JSP3.jsp <% String a1 = request.getParameter("a"); String b1 = request.getParameter("b"); String a2 = (String)session.getAttribute("a1´); out.println("Welcome, " +a2); String b2 = (String)session.getAttribute("b1´); out.println("Welcome, " + b2); %> ITA-computer May-june (2010)

Ans 5 (A) <%
String nm=request.getParameter( txtuser );

String d= = new java.util.Date() ; response.addCookie(new cookie(³username´,nm); response.addCookie(new cookie(³last_visit´,d);
Cookie[] c = request.getCookies(); Cookie cookie = new Cookie(c[1].getName(), c[1].getValue()); cookie.setMaxAge(4*24*60*60);

%> ANS 6(4) Standard actions in jsp are:

Pragma Infotech
1.<jsp:include> : Includes the response from a servlet or JSP page during the request processing phase Instead of loading the text of the included file in the original file like "include directive", it actually calls the included target at run-time (the way a browser would call the included target. In practice, this is actually a simulated request rather than a full round-trip between the browser and the server). Following is an example of jsp:include usage
<jsp:include page="hello.jsp"/>

2. <jsp:forward>: Forwards the processing of a request to servlet or JSP page
The <jsp:forward> element forwards the request object containing the client request information from one JSP file to another file. The target file can be an HTML file, another JSP file, or a servlet, as long as it is in the same application context as the forwarding JSP file. The lines in the source JSP file the <jsp:forward> element are not processed. This sample code shows the use of tag. This checks the percentage of free memory and based on that opens new page using this tag.
<jsp:forward page="one.jsp"/>

3. <jsp:param>:Adds a parameter value to a request handed off to another servlet or JSP page using <jsp:include> or <jsp:forward> The jsp:param element is used to provide key/value information.A translation error shall occur if the element is used elsewhere. <jsp:param name="name" value="value" /> This action has two mandatory attributes: name and value. name indicates the name of the parameter, and value, which may be a request-time expression, indicates its value.

NOV/DEC 2008
ANS 4 (A) 4.
Certain objects that are available for the use in JSP documents without being declared first. These objects are parsed by the JSP engine and inserted into the generated servlet. The implicit objects re listed below y request

Pragma Infotech
y y y y y y y y response pageContext session application out config page exception

ANS 5(A)
JSP vs ASP 1. JSP and ASP are both server side scripting languages 2. JSP is from Sun Microsystems while ASP is from Microsoft 3. ASP costs money while JSP is free. 4. ASP code is interpreted while JSP code is compiled at run time 5. JSP code can run faster than ASP if there are fewer changes 6. Majority of Windows users use ASP while users of open source operating systems like Linux use JSP among others.

ComDescription JSP

Writing HTML out.print("Some HTML code"); code Obtaining a parameter request.getParameter("parameterName") value Null value null Nothings
ASP Technology JSP Technology Reusable, Cross-Platform Components Security Against System Crashes Memory Leak Protection Scripting Language No

ASP Response.Write "Some HTML code" Request("parameterName")

JavaBeans, Enterprise JavaBeans, custom JSP tags Yes Yes Java

No No VBScript, Jscript No

Customizable Tags

Yes

Pragma Infotech

Web Server

Microsoft IIS or Personal Web Server

Any Web server, including Apache, Netscape, and IIS Most popular platforms, including the Solaris Operating Environment, Microsoft Windows, Mac OS, Linux, and other UNIX platform implementations JavaBeans, Enterprise JavaBeans, custom JSP tags Yes Yes Java

Platforms

Microsoft Windows

Reusable, Cross-Platform Components Security Against System Crashes Memory Leak Protection Scripting Language

No

No No VBScript, JScript No

Customizable Tags

Yes

or
ANS 5 (A) MVC architecture in jsp/servlet Model±view±controller (MVC) is a software architecture, currently considered an architectural pattern used in software engineering. The pattern isolates "domain logic" (the application logic for the user) from the user interface(input and presentation), permitting independent development, testing and maintenance of each. Introduction to MVC(Model View Controler) Struts : Struts is an open source framework from Jakartha Project designed for developing the web applications with Java SERVLET API and Java Server Pages Technologies.Struts conforms the Model View Controller design pattern. Struts package provides unified reusable components (such as action servlet) to build the user interface that can be applied to any web connection. It encourages software development following the MVC design pattern. Overview of MVC Architecture The MVC design pattern divides applications into three components: * The Model maintains the state and data that the application represents . * The View allows the display of information about the model to the user.

Pragma Infotech
* The Controller allows the user to manipulate the application .

Example: Example Here is a simple application of the pattern, implementing Java Servlets andJavaServer Pages from Java EE: Model The model is a collection of Java classes that form a software application intended to store, and optionally separate, data. A single front end class that can communicate with any user interface (for example: a console, a graphical user interface, or a web application). View The view is represented by a JavaServer Page, with data being transported to the page in the HttpServletRequest or HttpSession. Controller The Controller servlet communicates with the front end of the model and loads the HttpServletRequest or HttpSession with appropriate data, before forwarding the HttpServletRequest and Response to the JSP using a RequestDispatcher.

The Servlet is a Java class, and it communicates and interacts with the model, but does not need to generate HTML or XHTML output; the JSPs do not have to communicate with the model because the Servlet provides them with the information²they can concentrate on creating output. In Struts, the view is handled by JSPs and presentation components, the model is represented by Java Beans and the controller uses Servlets to perform its action. By developing a familiar Web-based shopping cart, you'll learn how to utilize the Model-View-Controller (MVC) design pattern and truly separate presentation from content when using Java Server Pages. Applying MVC in Servlets and JSP Many web applications are JSP-only or Servlets-only. With JSP, Java code is embedded in the HTML code; with Servlets the Java code calls println methods to generate the HTML code. Both approaches have their advantages and drawbacks; Struts gathers their strengths to get the best of their association. View on JSP The early JSP specification follows two approaches for building applications using JSP technology. These two approaches are called as JSP Model 1 and JSP

Pragma Infotech
Model 2 architectures. JSP Model 1 Architecture In Model 1 architecture the JSP page is alone responsible for processing the incoming request and replying back to the client. There is still separation of presentation from content, because all data access is performed using beans. Although the JSP Model 1 Architecture is more suitable for simple applications, it may not be desirable for complex implementations.

JSP Model 2 Architecture - MVC The Model 2 Architecture is an approach for serving dynamic content, since it combines the use of both Servlets and JSP. It takes advantages of the predominant strengths of both technologies, using JSP to generate the presentation layer and Servlets to perform process-intensive tasks. Here servlet acts as controller and is in charge of request processing and the creation of any beans or objects used by the JSP as well as deciding depending on the user¶s actions, which JSP page to forward the request to. Note that there is no processing logic within the JSP page itself; it is simply responsible for retrieving any objects or beans that may have been previously created by the servlet, and extracting the dynamic content from that servlet for insertion within static templates. Limitation in traditional MVC approach The main limitation in the traditional MVC approach is, in that there is no separation of business logic (validation/ conditions/ anything related to business rules) from controller (is responsible for controlling of the application flow by using static/dynamic request dispatcher. MVC Model 2 Architecture is Model View Controller 1.Client submits login request to servlet application 2.Servlet application acts as controller it first decides to request validator another servlet program which is responsible for not null checking (business rule) 3.control comes to controller back and based on the validation response, if the response is positive, servlet controller sends the request to model 4.Model requests DB to verify whether the database is having the same user name and password, If found login operation is successful 5.Beans are used to store if any data retrieved from the database and kept into HTTPSession 6.Controller then gives response back to response JSP (view) which uses the bean objects stored in HTTPSession ANS 6 (1).

Pragma Infotech
Implicit objects in jsp are the objects that are created by the container automatically and the container makes them available to the developers, the developer do not need to create them explicitly. There are nine implicit objects. Here is the list of all the implicit objects: Object Class application javax.servlet.ServletContext Config javax.servlet.ServletConfig exception java.lang.Throwable Out javax.servlet.jsp.JspWriter Page java.lang.Object PageContext javax.servlet.jsp.PageContext Request javax.servlet.ServletRequest response javax.servlet.ServletResponse Session javax.servlet.http.HttpSession
y

Application: These objects has an application scope. These objects are available at the widest context level, that allows to share the same information between the JSP page's servlet and any Web components with in the same application. Config: These object has a page scope and is an instance of javax.servlet.ServletConfig class. Config object allows to pass the initialization data to a JSP page's servlet. Parameters of this objects can be set in the deployment descriptor (web.xml) inside the element <jspfile>. The method getInitParameter() is used to access the initialization parameters. Exception: This object has a page scope and is an instance of java.lang.Throwable class. This object allows the exception data to be accessed only by designated JSP "error pages." Out: This object allows us to access the servlet's output stream and has a page scope. Out object is an instance of javax.servlet.jsp.JspWriter class. It provides the output stream that enable access to the servlet's output stream. Page: This object has a page scope and is an instance of the JSP page's servlet class that processes the current request. Page object represents the current page that is used to call the methods defined by the translated

y

y

y

y

Pragma Infotech
servlet class. First type cast the servlet before accessing any method of the servlet through the page.
y

Pagecontext: PageContext has a page scope. Pagecontext is the context for the JSP page itself that provides a single API to manage the various scoped attributes. This API is extensively used if we are implementing JSP custom tag handlers. PageContext also provides access to several page attributes like including some static or dynamic resource. Request: Request object has a request scope that is used to access the HTTP request data, and also provides a context to associate the requestspecific data. Request object implements javax.servlet.ServletRequest interface. It uses the getParameter() method to access the request parameter. The container passes this object to the _jspService() method. Response: This object has a page scope that allows direct access to theHTTPServletResponse class object. Response object is an instance of the classes that implements the javax.servlet.ServletResponse class. Container generates to this object and passes to the _jspService() method as a parameter. Session: Session object has a session scope that is an instance of javax.servlet.http.HttpSession class. Perhaps it is the most commonly used object to manage the state contexts. This object persist information across multiple user connection.

y

y

y

y y

ANS 6 (4)

y y y y y y y y y

A session is an object associated with a visitor. Data can be put in the session and retrieved from it, much like a Hashtable. A different set of data is kept for each visitor to the site. Html form : name.html
<HTML> <BODY> <FORM METHOD=POST ACTION="SaveName.jsp"> What's your name? <INPUT TYPE=TEXT NAME=username SIZE=20> <P><INPUT TYPE=SUBMIT> </FORM> </BODY> </HTML>

Pragma Infotech
y y y y y y y y y y y y y y y y y y SaveName.jsp saves user¶s name in session <% String name = request.getParameter( "username" ); session.setAttribute( "theName", name ); %> <HTML> <BODY> <A HREF="NextPage.jsp">Continue</A> </BODY> </HTML>

NextPage.jsp shows how to retrieve the saved name.
<HTML> <BODY> Hello, <%= session.getAttribute( "theName" ) %> </BODY> </HTML>