Sie sind auf Seite 1von 33

Introduction to JSP

JavaServer Pages (JSP) is a technology based on the Java language and enables the development of dynamic web sites. JSP was developed by Sun Microsystems to allow server side development. JSP files are HTML files with special Tags containing Java source code that provide the dynamic content. The following shows the Typical Web server, different clients connecting via the Internet to a Web server. In this example, the Web server is running on Unix and is the very popular Apache Web server

`First static web pages were displayed. Typically these were people?s first experience with making web pages so consisted of My Home Page sites and company marketing information. Afterwards Perl and C were languages used on the web server to provide dynamic content. Soon most languages including Visualbasic,Delphi,C and Java could be used to write applications that provided dynamic content using data from text files or database requests. These were known as CGI server side applications. ASP was developed by Microsoft to allow HTML developers to easily provide dynamic content supported as standard by Microsoft?s free Web Server,Internet Information Server (IIS). JSP is the equivalent from Sun Microsystems,a comparison of ASP and JSP will be presented in the following section. The following diagram shows a web server that supports JSP files. Notice that the web server also is connected to a database.

JSP source code runs on the web server in the JSP Servlet Engine. The JSP Servlet engine dynamically generates the HTML and sends the HTML output to the client?s web browser. Why use JSP? JSP is easy to learn and allows developers to quickly produce web sites and applications in an open and standard way. JSP is based on Java,an object-oriented language. JSP offers a robust platform for web development. Main reasons to use JSP: Multi platform Component reuse by using Javabeans and EJB. Advantages of Java. You can take one JSP file and move it to another platform,web server or JSP Servlet engine.

HTML and graphics displayed on the web browser are classed as the presentation layer. The Java code (JSP) on the server is classed as the implementation. By having a separation of presentation and implementation, web designers work only on the presentation and Java developers concentrate on implementing the application. JSP compared to ASP JSP and ASP are fairly similar in the functionality that they provide. JSP may have slightly higher learning curve. Both allow embedded code in an HTML page,session variables and database access and manipulation. Whereas ASP is mostly found on Microsoft platforms i.e. NT,JSP can operate on any platform that conforms to the J2EE specification. JSP allow component reuse by using Javabeans and EJBs. ASP provides the use of COM / ActiveX controls. JSP compared to ASP.NET ASP.NET is based on the Microsoft .NET framework. The .NET framework allows applications to be developed using different programming languages such as Visual Basic,C# and JavaScript. JSP and Java still has the advantage that it is supported on

many different platforms and the Java community has many years of experience in designing and developing Enterprise quality scalable applications. This is not to say that ASP.NET is bad,actually it is quite an improvement over the old ASP code. JSP compared to Servlets A Servlet is a Java class that provides special server side service. It is hard work to write HTML code in Servlets. In Servlets you need to have lots of println statements to generate HTML. JSP pages are converted to Servlets so actually can do the same thing as old Java Servlets. JSP architecture JSPs are built on top of SUN Microsystems' servlet technology. JSPs are essential an HTML page with special JSP tags embedded. These JSP tags can contain Java code. The JSP file extension is .jsp rather than .htm or .html. The JSP engine parses the .jsp and creates a Java servlet source file. It then compiles the source file into a class file,this is done the first time and this why the JSP is probably slower the first time it is accessed. Any time after this the special compiled servlet is executed and is therefore returns faster.

Steps required for a JSP request: 1. The user goes to a web site made using JSP. The user goes to a JSP page (ending with .jsp). The web browser makes the request via the Internet. 2. The JSP request gets sent to the Web server. 3. The Web server recognises that the file required is special (.jsp),therefore passes the JSP file to the JSP Servlet Engine.

4. If the JSP file has been called the first time,the JSP file is parsed,otherwise go to step 7. 5. The next step is to generate a special Servlet from the JSP file. All the HTML required is converted to println statements. 6. 7. 8. 9. The Servlet source code is compiled into a class. The Servlet is instantiated,calling the init and service methods. HTML from the Servlet output is sent via the Internet. HTML results are displayed on the user's web browser.

Creating your first JSP page <html> <head> <title>My first JSP page </title> </head> <body> <%@ page language="java" %> <% out.println("Hello World"); %> </body> </html> Type the code above into a text file. Name the file helloworld.jsp. Place this in the correct directory on your JSP web server and call through ur web browser. Using JSP tags There are five main tags: 1. Declaration tag 2. Expression tag 3. Directive tag 4. Scriptlet tag 5. Action tag Declaration tag ( <%! %> ) This tag allows the developer to declare variables or methods. Before the declaration you must have <%! At the end of the declaration,the developer must have %> Code placed in this tag must end in a semicolon ( ; ).

Declarations do not generate output so are used with JSP expressions or scriptlets. For Example, <%! private int counter = 0 ; private String get Account ( int accountNo) ; %> Expression tag ( <%= %>) This tag allows the developer to embed any Java expression and is short for out.println(). A semicolon ( ; ) does not appear at the end of the code inside the tag. For example,to show the current date and time. Date : <%= new java.util.Date() %> Scriplet Tags Between <% and %> tags,any valid Java code is called a Scriptlet. This code can access any variable or bean declared. For example,to print a variable. <% String username = "visualbuilder" ; out.println ( username ) ; %> Variables available to the JSP Scriptlets are: request: request represents the clients request and is a subclass of HttpServletRequest. Use this variable to retrieve the data submitted along the request. Example: <% //java codes String userName=null; userName=request.getParameter("userName"); %> response: response is subclass of HttpServletResponse.

session: session represents the HTTP session object associated with the request.

out: out is an object of output stream and is used to send any output to the client. Other variable available to the scriptlets are pageContext, application,config and exception. Directive tag ( <%@ directive ... %>)

A JSP directive gives special information about the page to the JSP Engine. There are three main types of directives: 1) page - processing information for this page. 2) Include - files to be included. 3) Tag library - tag library to be used in this page. Directives do not produce any visible output when the page is requested but change the way the JSP Engine processes the page. For example,you can make session data unavailable to a page by setting a page directive (session) to false. 1. Page directive:-This directive has 11 optional attributes that provide the JSP Engine with special processing information. The following table lists the 11 different attributes with a brief description: language extends Which language the file uses. Superclass used by the JSP engine for the translated Servlet. Import all the classes in a java package into the current JSP page. This allows the JSP page to use other java classes. <%@ page language = "java" %> <%@ page extends = "com.taglib... %> <%@ page import = "java.util.*" %>

import

session

Does the page make use of sessions. By default all JSP pages have session data Default is set to true. available. There are performance benefits to switching session to false. Controls the use of buffered output for a JSP page. Default is 8kb <%@ page buffer = "none" %>

buffer

Flush output buffer when full. autoFlush

<%@ page autoFlush = "true" %>

Can the generated Servlet deal with isThreadSafe multiple requests? If true a new thread is started so requests are handled simultaneously. Developer uses info attribute to add information/document for a page. Typically used to add author,version,copyright and date info. <%@ page info = "visualbuilder.com test page,copyright 2001. " %>

info

errorPage

Different page to deal with errors. Must <%@ page errorPage = be URL to error page. "/error/error.jsp" %>

IsErrorPage

contentType

This flag is set to true to make a JSP page a special Error Page. This page has access to the implicit object exception Set the mime type and character set of the JSP.

Where directive may be: 1. page: page is used to provide the information about it. Example: <%@page language="java" %> 2. include: include is used to include a file in the JSP page. Example: <%@ include file="/header.jsp" %> 3. taglib: taglib is used to use the custom tags in the JSP pages (custom tags allows us to defined our own tags). Example: <%@ taglib uri="tlds/taglib.tld" prefix="mytag" %> and attribute may be: 1. language="java" This tells the server that the page is using the java language. Current JSP specification supports only java language. Example: <%@page language="java" %> 2. extends="mypackage.myclass" This attribute is used when we want to extend any class. We can use comma(,) to import more than one packages. Example: <%@page language="java" import="java.sql.*,mypackage.myclass" %> 3. session="true" When this value is true session data is available to the JSP page otherwise not. By default this value is true. Example: <%@page language="java" session="true" %> 4. errorPage="error.jsp" errorPage is used to handle the un-handled exceptions in the page. Example: <%@page language="java" session="true" errorPage="error.jsp" %>

5. contentType="text/html;charset=ISO-8859-1" Use this attribute to set the mime type and character set of the JSP. Example: <%@page language="java" session="true" contentType="text/html;charset=ISO-8859-1" %>

2.

Include directive Allows a JSP developer to include contents of a file inside another. Typically include files are used for navigation, tables, headers and footers that are common to multiple pages. Two examples of using include files: This includes the html from privacy.html found in the include directory into the current jsp page. <%@ include file = "include/privacy.html" %> or to include a naviagation menu (jsp file) found in the current directory. <%@ include file = "navigation.jsp" %> 3. Tag Lib directive A tag lib is a collection of custom tags that can be used by the page. <%@ taglib uri = "tag library URI" prefix = "tag Prefix" %> Custom tags were introduced in JSP 1.1 and allow JSP developers to hide complex server side code from web designers.

5.

Action tags

There are three main roles of action tags : 1) enable the use of server side Javabeans 2) 3) transfer control between pages browser independent support for applets.

Javabeans

A Javabean is a special type of class that has a number of methods. The JSP page can call these methods so can leave most of the code in these Javabeans. For example, if you wanted to make a feedback form that automatically sent out an email. By having a JSP page with a form, when the visitor presses the submit button this sends the details to a Javabean that sends out the email. This way there would be no code in the JSP page dealing with sending emails (JavaMail API) and your Javabean could be used in another page (promoting reuse). (Code Reusability)

To use a Javabean in a JSP page use the following syntax:

<jsp : usebean id = " ...." scope = "application" class = "com..." />

The following is a list of Javabean scopes:

page - valid until page completes. request - bean instance lasts for the client request session - bean lasts for the client session. application - bean instance created and lasts until application ends.

Creating your second JSP page

For the second example,we will make use of the different tags we have learnt. This example will declare two variables; one string used to stored the name of a website and an integer called counter that displays the number of times the page has been accessed. There is also a private method declared to increment the counter. The website name and counter value are displayed.

<HTML> <HEAD> <!-- Example2 --> <TITLE> JSP loop</TITLE> </HEAD> <BODY> <font face=verdana color=darkblue> JSP loop <BR> <BR>

<%! public String writeThis(int x) { String myText=""; for (int i = 1; i < x; i ) myText = myText "<font size=" i " color=darkred face=verdana>VisualBuilder JSP Tutorial</font><br>" ; return myText; } %>

This is a loop example from the

<br> <%= writeThis(8) %> </font> </BODY> </HTML>

JSP Date Example (Exercise) <%@page contentType="text/html" import="java.util.*" %> <!-http://www.roseindia.net/jsp --> <html> <body> <p>&nbsp;</p> <div align="center"> <center> <table border="0" cellpadding="0" cellspacing ="0" width="460" bgcolor="#EEFFCA"> <tr> <td width="100%"><font size="6" color ="#008000">&nbsp;Date Example</font></td> </tr> <tr> <td width="100%"><b>&nbsp;Current Date and time is:&nbsp; <font color="#FF0000">

<%= new java.util.Date() %> </font></b></td> </tr> </table> </center> </div> </body> </html> The heart of this example is Date() function of the java.util package which returns the current data and time. In the JSP Declaratives %@page contentType="text/html" import="java.util.*" % we are importing the java.util package and following JSP Expression code <%= new java.util.Date() %> prints the current date on the page.

Implicit Objects
So far we know that the developer can create Javabeans and interact with Java objects. There are several objects that are automatically available in JSP called implicit objects.

Of type Variable

Javax.servlet.http.httpservletrequest Request

Response

Javax.servlet.http. httpservletresponse

Javax.servlet.jsp.JspWriter Out

Javax.servlet.http.httpsession Session

Javax.servlet.jsp.pagecontext PageContent

Javax.servlet.http.ServletContext Application

Javax.servlet.http.ServletConfig Config

Java.lang.Object Page

Page object Represents the JSP page and is used to call any methods defined by the servlet class. Config object Stores the Servlet configuration data. Request object Access to information associated with a request. This object is normally used in looking up parameter values and cookies. <% String devStr = request.getParameter("dev"); %> Development language = <%= devStr %>

This code snippet is storing the parameter "dev" in the string devStr. The result is displayed underneath.

HTTP Request about the browser When an HTTP client such as web browser sends a request to a web server, along with the request it also sends some HTTP variables like Remote address, Remote host, Content type etc. In some cases these variables are useful to the programmers. So here is the code of the jsp file which prints the HTTP request information: <%@page contentType="text/html" import="java.util.*" %> <!-http://www.roseindia.net/jsp --> <html> <body> <p><font size="5" color="#800000">Request Information:</font></p> <div align="left"> <table border="0" cellpadding="0" cellspacing="0" width="70%" bgcolor="#EEFFCA"> <tr> <td width="33%"><b><font color="#800000">Request

Method:</font></b></td> <td width="67%"><font color="#FF0000"><%=request.getMethod()%></font></td> </tr> <tr> <td width="33%"><b><font color="#800000">Request URI:</font></b></td> <td width="67%"><font color="#FF0000"><%=request.getRequestURI()%></font></td> </tr> <tr> <td width="33%"><b><font color="#800000">Request Protocol:</font></b></td> <td width="67%"><font color="#FF0000"><%=request.getProtocol()%></font></td> </tr> <tr> <td width="33%"><b><font color="#800000">Path Info:</font></b></td> <td width="67%"><font color="#FF0000"><%=request.getPathInfo()%></font></td> </tr> <tr> <td width="33%"><b><font color="#800000">Path translated:</font></b></td> <td width="67%"><font color="#FF0000"><%=request.getPathTranslated()%></font></td> </tr> <tr> <td width="33%"><b><font color="#800000">Query

String:</font></b></td> <td width="67%"><font color="#FF0000"><%=request.getQueryString()%></font></td> </tr> <tr> <td width="33%"><b><font color="#800000">Content length:</font></b></td> <td width="67%"><font color="#FF0000"><%=request.getContentLength()%></font></td> </tr> <tr> <td width="33%"><b><font color="#800000">Content type:</font></b></td> <td width="67%"><font color="#FF0000"><%=request.getContentType()%></font></td> </tr> <tr> <td width="33%"><b><font color="#800000">Server name:</font></b></td> <td width="67%"><font color="#FF0000"><%=request.getServerName()%></font></td> </tr> <tr> <td width="33%"><b><font color="#800000">Server port:</font></b></td> <td width="67%"><font color="#FF0000"><%=request.getServerPort()%></font></td> </tr> <tr> <td width="33%"><b><font color="#800000">Remote

user:</font></b></td> <td width="67%"><font color="#FF0000"><%=request.getRemoteUser()%></font></td> </tr> <tr> <td width="33%"><b><font color="#800000">Remote address:</font></b></td> <td width="67%"><font color="#FF0000"><%=request.getRemoteAddr()%></font></td> </tr> <tr> <td width="33%"><b><font color="#800000">Remote host:</font></b></td> <td width="67%"><font color="#FF0000"><%=request.getRemoteHost()%></font></td> </tr> <tr> <td width="33%"><b><font color="#800000">Authorization scheme:</font></b></td> <td width="67%"><font color="#FF0000"><%=request.getAuthType()%></font></td> </tr> </table> </div> </body> </html>
Copy the code below and place in

Creating a Form

Here we show how to create and process an html form. a file named: myform.jsp

<html> <head> <!-- Example4 --> <title>VisualBuilder.com</title> </head> <body> <form action="myformconfirm.jsp" method="post"> Enter in a website name:<br> <input type="text" name="website"><br> <input type="submit" name="submit"> </form> </body> </html> Processing a Form Here we show how to process the html form your just created. Copy the code below and place in a file named: myformconfirm.jsp Go to myform.jsp Fill in some details and submit the form You should see the results of your submission <html> <head> <!-- Example4 --> <title>VisualBuilder.com</title> </head> <body> <font size=3> Your info has been received:

<br><br> <% String sName = request.getParameter("website"); out. print(sName); %> </font> </body> </html

Creating a Form (more elements) This example shows how to create and process more form elements. Copy the code below and place in a file named: fullform.jsp <html> <head> <!-- Example5 --> <title>VisualBuilder.com</title> </head> <body> <h1> Website submission form </h1> <form action="fullformconfirm.jsp" method="post"> Enter in the website name: <input type="text" name="website"> <br>

<br> Enter in the url: <input type="text" name="url"> <br> <br> category: <select name="category" size="1"> <option selected value="java">java</option> <option value="ejb">ejb</option> <option value="servlet">servlet</option> <option value="jsp">jsp</option> <option value="jdbc">jdbc</option> </select> <br> <br> Description: <textarea rows="4" cols='42' name="desc"></textarea> <br> <br> Search engines: <input type="checkbox" name="yahoo" value="T">Yahoo <input type="checkbox" name="google" value="T" CHECKED>Google <input type="checkbox" name="altavista" value="T">Altavista <br> <br>

<input type="submit" name="submit" value="Go"> </form> </body> </html>

Processing a Form (more elements) Here we show how to process the html form your just created. Copy the code below and place in a file named: fullformconfirm.jsp Go to fullform.jsp Fill in some details and submit the form You should see the results of your submission <html>

<head> <!-- Example4 --> <title>VisualBuilder.com</title>

</head> <body>

<font size=3> Thank you for your submission,it has been successfully received: <br><br> <% String sName = request.getParameter("website");

String sUrl = request.getParameter("url"); String sCategory = request.getParameter("category"); String sDesc = request.getParameter("desc"); String sGoogle = request.getParameter("google"); String sYahoo = request.getParameter("yahoo"); String sAltavista = request.getParameter("altavista"); %>

Name:<%=sName%><br> Url:<%=sUrl%><br> Desc:<%=sDesc%><br> Category:<%=sCategory%><br> Desc:<%=sDesc%><br> Google:<%=sGoogle%><br> Yahoo:<%=sYahoo%><br> Altavista:<%=sAltavista%><br>

</font>

</body> </html>

JavaBeans are reusable components. It represents a simple Java class with some properties. The bean properties are accessed by Getter and Setter method. They are used to separate Business logic from the Presentation logic. Internally, a bean is just an instance of a class. The JSP specification provides three basic tags for working with Beans :-

jsp:useBean id="bean name" class="bean class" scope = "page | request | session |application "/>

<jsp:setProperty name = "bean name" property = "someProperty" value = "someValue" /> <jsp:getProperty name = "bean name" property = "someProperty" />

Where bean name = the name that refers to the bean. Bean class = name of the java class that defines the bean. property = name of the property to be passed to the bean. value = value of that particular property. The following is the explanation for the different scopes of a bean object in jsp:

Page scope:- This scope helps to keep the data available while the page is loading. Any object whose scope is defined as page scope will disappear as soon as the response is sent to the browser. The object with a page scope may be modified as often as desired within the particular page but the changes are lost as soon as the user moves away from the page. By default all beans have page scope.

1. Request scope:- Any object created in the request scope will be available as long as the request object is valid. For example if the JSP page uses a <jsp:forward> tag, then the bean will be accessed in the forwarded page and if redirect is used then the bean is destroyed. 2. The Session scope:- In JSP terms, the data associated with the user has session scope. A session does not correspond directly to the user; rather, it corresponds with a particular period of time the user spends at a site. Typically, this period is defined as all the hits a user makes to a website between starting and exiting his browser. 3. Application Scope:- The bean associated with the application scope will be accessible to all the users and all the pages in the application. The following example will demonstrate the various bean scopes for the JSP application. All the examples will use the Counter bean which has only one property counter of type int . . (1) Page Scope Note:- This is the default scope for the bean object. So in the following JSP example "bean1" is accessed only in this page and not anywhere else

<HTML> <BODY>

<H1>Using Beans and Page Scope</H1> <jsp:useBean id="bean1" class="com.visualbuilder.Counter" scope="page" /> <%bean1.setCounter(bean1.getCounter() + 1);%> The counter value is: <jsp:getProperty name="bean1" property="counter" /> </BODY> </HTML> (1) Request Scope index.jsp <jsp:useBean id="counter" scope="request" class="com.visualbuilder.Counter" /> <html> <head> <title>Request Bean Example</title> </head> <body> <% counter.setCounter(10); %> <jsp:forward page="request.jsp" /> </body> </html> request.jsp <jsp:useBean id="counter" scope="request" class="com.visualbuilder.Counter" /> <html> <body> <H3>Request Bean Example</H3> <center><b>The current count for the counter bean is: </b> <%=counter.getCounter() %></center> </body> </html> (3) Session Scope Example for Session Scope. <HTML> <BODY> <jsp:useBean id="bean1" class="com.visualbuilder.Counter" scope="session" /> <%bean1.setCounter(bean1.getCounter() + 1);%> The counter value is: <jsp:getProperty name="bean1" property="counter" /> </BODY> </HTML>

(3) Application Scope <jsp:useBean id="counter" scope="application" class="com.visualbuilder.Counter" /> <html> <body> <center> &nbsp;&nbsp;<b>The current count for the counter bean is: </b> <%=counter.getCounter() %> </center> </body> </html Uploading application The request object is used to send the raw data in form of key/value pair to the server from the browser. What if, we want to send the multipart data i.e. images, files and binary data to the server. The below example will demonstrate the multiple type data send to the server. <%@ page import="java.io.*"%> <% String contentType = request.getContentType(); if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0)) { DataInputStream in = new DataInputStream(request.getInputStream()); int formDataLength = request.getContentLength(); byte dataBytes[] = new byte[formDataLength]; int byteRead = 0; int totalBytesRead = 0; while (totalBytesRead < formDataLength) { byteRead = in.read(dataBytes, totalBytesRead, formDataLength); totalBytesRead += byteRead; } String file = new String(dataBytes); String saveFile = file.substring(file.indexOf("filename=\"") + 10); saveFile = saveFile.substring(0, saveFile.indexOf("\n")); saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1,saveFile.indexOf("\"")); int lastIndex = contentType.lastIndexOf("="); String boundary = contentType.substring(lastIndex + 1,contentType.length()); int pos; pos = file.indexOf("filename=\""); pos = file.indexOf("\n", pos) + 1; pos = file.indexOf("\n", pos) + 1; pos = file.indexOf("\n", pos) + 1; int boundaryLocation = file.indexOf(boundary, pos) - 4; int startPos = ((file.substring(0, pos)).getBytes()).length;

int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length; String filepath=session.getServletContext().getRealPath("/")+saveFile; FileOutputStream fileOut = new FileOutputStream(filepath); fileOut.write(dataBytes, startPos, (endPos - startPos)); fileOut.flush(); fileOut.close(); out.println("File saved as " +saveFile); } %> <!-- Starts Here --> <form method="post" ACTION="upload.jsp" name="uploadForm" ENCTYPE='multipart/form-data'> <input type="file" name="uploadfile" /> <p> <input type="submit" name="Submit" value="Submit"> <input type="reset" name="Reset" value="Reset"> <input type="hidden" name="action" value="upload"> </p> </form> <!-- Ends Here --> Database Connectivity

the connectivity from MYSQL database with JSP.we take a example of Books database. This database contains a table named books_details. This table contains three fields- id, book_name& author. we starts from very beginning. First we learn how to create tables in MySQl database after that we write a html page for inserting the values in 'books_details' table in database. After submitting values a table will be showed that contains the book name and author name. Database The database in example consists of a single table of three columns or fields. The database name is "books" and it contains information about books names & authors. Table:books_details ID 1. 2.

Book Name Java I/O Java & XML,2 Edition

Author Tim Ritchey Brett McLaughlin

3. Java Swing, 2nd Edition Dave Wood, Marc Loy, Start MYSQL prompt and type this SQL statement & press EnterMYSQL>CREATE DATABASE `books` ; This will create "books" database. Now we create table a table "books_details" in database "books". MYSQL>CREATE TABLE `books_details` ( `id` INT( 11 ) NOT NULL AUTO_INCREMENT , `book_name` VARCHAR( 100 ) NOT NULL , `author` VARCHAR( 100 ) NOT NULL , PRIMARY KEY ( `id` ) ) TYPE = MYISAM ; This will create a table "books_details" in database "books" JSP Code The following code contains html for user interface & the JSP backend<%@ page language="java" import="java.sql.*" %> <% String driver = "org.gjt.mm.mysql.Driver"; Class.forName(driver).newInstance(); Connection con=null; ResultSet rst=null; Statement stmt=null; try{ String url="jdbc:mysql://localhost/books?user=<user>&password =<password>"; con=DriverManager.getConnection(url); stmt=con.createStatement(); } catch(Exception e){ System.out.println(e.getMessage()); } if(request.getParameter("action") != null){ String bookname=request.getParameter("bookname"); String author=request.getParameter("author"); stmt.executeUpdate("insert into books_details(book_name, author) values('"+bookname+"','"+author+"')"); rst=stmt.executeQuery("select * from books_details"); %>

Fill the book name and author fields and press Submit button. A page will open and show a table of book name and authors like...

<%@page contentType="text/html"%> <%@page pageEncoding="UTF-8"%> <%@ page language="java" import="java.sql.*" errorPage="" %> <%@ page import="java.sql.*" %> <%@ page import="java.io.*" %> <%! Connection con=null; %> <%! Statement st= null; %> <%! ResultSet rs= null; %> <%! boolean found =false; %> <% Class.forName("com.mysql.jdbc.Driver").newInstance(); try { con = DriverManager.getConnection("jdbc:mysql://localhost/test","root","mysql"); out.println("System connected\n"); st = con.createStatement();

String s1=request.getParameter("uname"); out.println(s1); rs=st.executeQuery("select * from user where name='"+s1+"'"); session.setAttribute("name",s1); String s2=request.getParameter("pswd"); out.println("After Executing the Query" + rs); while(rs.next()) { out.println(rs.getString(s1)); String rs1=rs.getString(1); //session.setAttribute("user"); String rs2=rs.getString("pswd"); if(s2.equalsIgnoreCase(rs2)) { int id=rs.getInt("userid"); out.println("After Executing the Query" ); int userid=rs.getInt("userid"); out.println(userid); } } } catch(Exception e) { System.out.println("validation failure"+e); } finally { st.close(); rs.close(); con.close(); } %>

Working with Sessions This JSP Tutorial shows you how to track the session between different JSP pages. In any web application user moves from one page to another and it becomes necessary to track the user data and objects throughout the application. JSP provide an implicit object "session", which can be use to save the data specific the particular to the user. In this tutorial we will create an application that takes the user name from the user and then saves into the user session. We will display the saved data to the user in another page. Here is the code of the JSP file (savenameform.jsp) that takes the input from user: <%@ page language="java" %> <html>

<head> <title>Name Input Form</title> </head> <body> <form method="post" action="savenametosession.jsp"> <p><b>Enter Your Name: </b><input type="text" name="username"><br> <input type="submit" value="Submit"> </form> </body> The above page prompts the user to enter his/her name. Once the user clicks on the submit button, savenametosession.jsp is called. The JSP savenametosession.jsp retrieves the user name from request attributes and saves into the user session using the function session.setAttribute("username",username);. Here is the code of savenametosession.jsp: <%@ page language="java" %> <% String username=request.getParameter("username"); if(username==null) username=""; session.setAttribute("username",username); %> <html> <head> <title>Name Saved</title> </head> <body> <p><a href="showsessionvalue.jsp">Next Page to view the session value</a><p> </body> The above JSP saves the user name into the session object and displays a link to next pages (showsessionvalue.jsp). When user clicks on the "Next Page to view session value" link, the JSP page showsessionvalue.jsp displays the user name to the user. Here is the code of showsessionvalue.jsp: <%@ page language="java" %> <% String username=(String) session.getAttribute("username"); if(username==null) username=""; %> <html> <head>

<title>Show Saved Name</title> </head> <body> <p>Welcome: <%=username%><p> </body> The function session.getAttribute("username") is used to retrieve the user name saved in the session. Disabling Sessions In this tutorial you will learn how to disable session creation in the JSP pages. Disabling the session in some pages will improve the performance of your JSP container.Every time a JSP is requested, JSP creates an HttpSession object to maintain state for each unique client. The session data is accessible in the JSP as the implicit session object. In JSPs, sessions are enabled by default. Session object uses the server resources. Each session object uses up a small amount of system resources as it is stored on the server side. This also increases the traffic as the session ID is sent from server to client. Client also sends the same session ID along with each request. If some of the JSP pages on your web site are getting thousands of hits from internet browser and there is not need to identify the user, so its better to disable the session in that JSP page. You can tell the container to disable session in the JSP file by setting the session attribute to false. Set the session attribute of the page directive to false, as shown in the following example: <%@ page session="false" %> Here is the full code of jsp file in which session is disabled: <%@ page language="java" session="false"%> <html> <head> <title>Session Disabled</title> </head> <body> <p>Session is Disabled in this page </body> </html>

JSP Cookies This tutorial shows how to handle cookies in JSP pages. In this tutorial you will learn how to add cookies through jsp page and then show the value of the same cookie in another JSP page.

Let's understand the cookies. Cookies are short pieces of data sent by web servers to the client browser. The cookies are saved to clients hard disk in the form of small text file. Cookies helps the web servers to identify web users, by this way server tracks the user. Cookies pay very important role in the session tracking. Cookie Class In JSP cookie are the object of the class javax.servlet.http.Cookie. This class is used to creates a cookie, a small amount of information sent by a servlet to a Web browser, saved by the browser, and later sent back to the server. A cookie's value can uniquely identify a client, so cookies are commonly used for session management. A cookie has a name, a single value, and optional attributes such as a comment, path and domain qualifiers, a maximum age, and a version number. The getCookies() method of the request object returns an array of Cookie objects. Cookies can be constructed using the following code: Cookie(java.lang.String name, java.lang.String value) Cookie objects have the following methods. Method Description Returns the comment describing the purpose of this cookie, or getComment() null if no such comment has been defined. getMaxAge() Returns the maximum specified age of the cookie. getName() Returns the name of the cookie. getPath() Returns the prefix of all URLs for which this cookie is targeted. getValue() Returns the value of the cookie. If a web browser presents this cookie to a user, the cookie's setComment(String) purpose will be described using this comment. Sets the maximum age of the cookie. The cookie will expire after that many seconds have passed. Negative values indicate setMaxAge(int) the default behavior: the cookie is not stored persistently, and will be deleted when the user web browser exits. A zero value causes the cookie to be deleted This cookie should be presented only with requests beginning setPath(String) with this URL. Sets the value of the cookie. Values with various special characters (white space, brackets and parentheses, the equals setValue(String) sign, comma, double quote, slashes, question marks, the "at" sign, colon, and semicolon) should be avoided. Empty values may not behave the same way on all browsers. Example Using Cookies No we will write code in JSP file to set and then display the cookie. Create Form

Here is the code of the form (cookieform.jsp) which prompts the user to enter his/her name. <%@ page language="java" %> <html> <head> <title>Cookie Input Form</title> </head> <body> <form method="post" action="setcookie.jsp"> <p><b>Enter Your Name: </b><input type="text" name="username"><br> <input type="submit" value="Submit"> </form> </body> Above form prompts the user to enter the user name. User input are posted to the setcookie.jsp file, which sets the cookie. Here is the code of setcookie.jsp file: <%@ page language="java" import="java.util.*"%> <% String username=request.getParameter("username"); if(username==null) username="";

Date now = new Date(); String timestamp = now.toString(); Cookie cookie = new Cookie ("username",username); cookie.setMaxAge(365 * 24 * 60 * 60); response.addCookie(cookie); %> <html> <head> <title>Cookie Saved</title> </head> <body> <p><a href="showcookievalue.jsp">Next Page to view the cookie value</a><p> </body> Above code sets the cookie and then displays a link to view cookie page. Here is the code of display cookie page (showcookievalue.jsp): <%@ page language="java" %> <%

String cookieName = "username"; Cookie cookies [] = request.getCookies (); Cookie myCookie = null; if (cookies != null) { for (int i = 0; i < cookies.length; i++) { if (cookies [i].getName().equals (cookieName)) { myCookie = cookies[i]; break; } } } %> <html> <head> <title>Show Saved Cookie</title> </head> <body>

<% if (myCookie == null) { %> No Cookie found with the name <%=cookieName%> <% } else { %> <p>Welcome: <%=myCookie.getValue()%>. <% } %> </body> When user navigates to the above the page, cookie value is displayed.

Das könnte Ihnen auch gefallen