JSP – Cookies Handling ”; Previous Next In this chapter, we will discuss Cookies Handling in JSP. Cookies are text files stored on the client computer and they are kept for various information tracking purposes. JSP transparently supports HTTP cookies using underlying servlet technology. There are three steps involved in identifying and returning users − Server script sends a set of cookies to the browser. For example, name, age, or identification number, etc. Browser stores this information on the local machine for future use. When the next time the browser sends any request to the web server then it sends those cookies information to the server and server uses that information to identify the user or may be for some other purpose as well. This chapter will teach you how to set or reset cookies, how to access them and how to delete them using JSP programs. The Anatomy of a Cookie Cookies are usually set in an HTTP header (although JavaScript can also set a cookie directly on a browser). A JSP that sets a cookie might send headers that look something like this − HTTP/1.1 200 OK Date: Fri, 04 Feb 2000 21:03:38 GMT Server: Apache/1.3.9 (UNIX) PHP/4.0b3 Set-Cookie: name = xyz; expires = Friday, 04-Feb-07 22:03:38 GMT; path = /; domain = tutorialspoint.com Connection: close Content-Type: text/html As you can see, the Set-Cookie header contains a name value pair, a GMT date, a path and a domain. The name and value will be URL encoded. The expires field is an instruction to the browser to “forget” the cookie after the given time and date. If the browser is configured to store cookies, it will then keep this information until the expiry date. If the user points the browser at any page that matches the path and domain of the cookie, it will resend the cookie to the server. The browser”s headers might look something like this − GET / HTTP/1.0 Connection: Keep-Alive User-Agent: Mozilla/4.6 (X11; I; Linux 2.2.6-15apmac ppc) Host: zink.demon.co.uk:1126 Accept: image/gif, */* Accept-Encoding: gzip Accept-Language: en Accept-Charset: iso-8859-1,*,utf-8 Cookie: name = xyz A JSP script will then have access to the cookies through the request method request.getCookies() which returns an array of Cookie objects. Servlet Cookies Methods Following table lists out the useful methods associated with the Cookie object which you can use while manipulating cookies in JSP − S.No. Method & Description 1 public void setDomain(String pattern) This method sets the domain to which the cookie applies; for example, tutorialspoint.com. 2 public String getDomain() This method gets the domain to which the cookie applies; for example, tutorialspoint.com. 3 public void setMaxAge(int expiry) This method sets how much time (in seconds) should elapse before the cookie expires. If you don”t set this, the cookie will last only for the current session. 4 public int getMaxAge() This method returns the maximum age of the cookie, specified in seconds, By default, -1 indicating the cookie will persist until the browser shutdown. 5 public String getName() This method returns the name of the cookie. The name cannot be changed after the creation. 6 public void setValue(String newValue) This method sets the value associated with the cookie. 7 public String getValue() This method gets the value associated with the cookie. 8 public void setPath(String uri) This method sets the path to which this cookie applies. If you don”t specify a path, the cookie is returned for all URLs in the same directory as the current page as well as all subdirectories. 9 public String getPath() This method gets the path to which this cookie applies. 10 public void setSecure(boolean flag) This method sets the boolean value indicating whether the cookie should only be sent over encrypted (i.e, SSL) connections. 11 public void setComment(String purpose) This method specifies a comment that describes a cookie”s purpose. The comment is useful if the browser presents the cookie to the user. 12 public String getComment() This method returns the comment describing the purpose of this cookie, or null if the cookie has no comment. Setting Cookies with JSP Setting cookies with JSP involves three steps − Step 1: Creating a Cookie object You call the Cookie constructor with a cookie name and a cookie value, both of which are strings. Cookie cookie = new Cookie(“key”,”value”); Keep in mind, neither the name nor the value should contain white space or any of the following characters − [ ] ( ) = , ” / ? @ : ; Step 2: Setting the maximum age You use setMaxAge to specify how long (in seconds) the cookie should be valid. The following code will set up a cookie for 24 hours. cookie.setMaxAge(60*60*24); Step 3: Sending the Cookie into the HTTP response headers You use response.addCookie to add cookies in the HTTP response header as follows response.addCookie(cookie); Example Let us modify our Form Example to set the cookies for the first and the last name. <% // Create cookies for first and last names. Cookie firstName = new Cookie(“first_name”, request.getParameter(“first_name”)); Cookie lastName = new Cookie(“last_name”, request.getParameter(“last_name”)); // Set expiry date after 24 Hrs for both the cookies. firstName.setMaxAge(60*60*24); lastName.setMaxAge(60*60*24); // Add both the cookies in the response header. response.addCookie( firstName ); response.addCookie( lastName ); %> <html> <head> <title>Setting Cookies</title> </head> <body> <center> <h1>Setting Cookies</h1> </center> <ul> <li><p><b>First Name:</b> <%= request.getParameter(“first_name”)%> </p></li> <li><p><b>Last Name:</b> <%= request.getParameter(“last_name”)%> </p></li> </ul> </body> </html> Let us put the above code in main.jsp file and use it in the following HTML page − <html> <body> <form action = “main.jsp” method = “GET”> First Name: <input type = “text” name = “first_name”> <br /> Last Name: <input type = “text” name = “last_name” /> <input type = “submit” value = “Submit” /> </form> </body> </html> Keep the above HTML content in a file hello.jsp and put hello.jsp and main.jsp in <Tomcat-installation-directory>/webapps/ROOT directory. When you will access http://localhost:8080/hello.jsp, here is the actual output of the above form. First Name: Last Name: Try to enter the First Name and the Last Name
Category: jsp
JSP – Environment Setup
JSP – Environment Setup ”; Previous Next A development environment is where you would develop your JSP programs, test them and finally run them. This tutorial will guide you to setup your JSP development environment which involves the following steps − Setting up Java Development Kit This step involves downloading an implementation of the Java Software Development Kit (SDK) and setting up the PATH environment variable appropriately. You can download SDK from Oracle”s Java site − Java SE Downloads. Once you download your Java implementation, follow the given instructions to install and configure the setup. Finally set the PATH and JAVA_HOME environment variables to refer to the directory that contains java and javac, typically java_install_dir/bin and java_install_dir respectively. If you are running Windows and install the SDK in C:jdk1.5.0_20, you need to add the following line in your C:autoexec.bat file. set PATH = C:jdk1.5.0_20bin;%PATH% set JAVA_HOME = C:jdk1.5.0_20 Alternatively, on Windows NT/2000/XP, you can also right-click on My Computer, select Properties, then Advanced, followed by Environment Variables. Then, you would update the PATH value and press the OK button. On Unix (Solaris, Linux, etc.), if the SDK is installed in /usr/local/jdk1.5.0_20 and you use the C shell, you will put the following into your .cshrc file. setenv PATH /usr/local/jdk1.5.0_20/bin:$PATH setenv JAVA_HOME /usr/local/jdk1.5.0_20 Alternatively, if you use an Integrated Development Environment (IDE) like Borland JBuilder, Eclipse, IntelliJ IDEA, or Sun ONE Studio, compile and run a simple program to confirm that the IDE knows where you installed Java. Setting up Web Server: Tomcat A number of Web Servers that support JavaServer Pages and Servlets development are available in the market. Some web servers can be downloaded for free and Tomcat is one of them. Apache Tomcat is an open source software implementation of the JavaServer Pages and Servlet technologies and can act as a standalone server for testing JSP and Servlets, and can be integrated with the Apache Web Server. Here are the steps to set up Tomcat on your machine − Download the latest version of Tomcat from https://tomcat.apache.org/. Once you downloaded the installation, unpack the binary distribution into a convenient location. For example, in C:apache-tomcat-5.5.29 on windows, or /usr/local/apache-tomcat-5.5.29 on Linux/Unix and create CATALINA_HOME environment variable pointing to these locations. Tomcat can be started by executing the following commands on the Windows machine − %CATALINA_HOME%binstartup.bat or C:apache-tomcat-5.5.29binstartup.bat Tomcat can be started by executing the following commands on the Unix (Solaris, Linux, etc.) machine − $CATALINA_HOME/bin/startup.sh or /usr/local/apache-tomcat-5.5.29/bin/startup.sh After a successful startup, the default web-applications included with Tomcat will be available by visiting http://localhost:8080/. Upon execution, you will receive the following output − Further information about configuring and running Tomcat can be found in the documentation included here, as well as on the Tomcat web site − https://tomcat.apache.org/. Tomcat can be stopped by executing the following commands on the Windows machine − %CATALINA_HOME%binshutdown or C:apache-tomcat-5.5.29binshutdown Tomcat can be stopped by executing the following commands on Unix (Solaris, Linux, etc.) machine − $CATALINA_HOME/bin/shutdown.sh or /usr/local/apache-tomcat-5.5.29/bin/shutdown.sh Setting up CLASSPATH Since servlets are not part of the Java Platform, Standard Edition, you must identify the servlet classes to the compiler. If you are running Windows, you need to put the following lines in your C:autoexec.bat file. set CATALINA = C:apache-tomcat-5.5.29 set CLASSPATH = %CATALINA%commonlibjsp-api.jar;%CLASSPATH% Alternatively, on Windows NT/2000/XP, you can also right-click on My Computer, select Properties, then Advanced, then Environment Variables. Then, you would update the CLASSPATH value and press the OK button. On Unix (Solaris, Linux, etc.), if you are using the C shell, you would put the following lines into your .cshrc file. setenv CATALINA = /usr/local/apache-tomcat-5.5.29 setenv CLASSPATH $CATALINA/common/lib/jsp-api.jar:$CLASSPATH NOTE − Assuming that your development directory is C:JSPDev (Windows) or /usr/JSPDev (Unix), then you would need to add these directories as well in CLASSPATH. Print Page Previous Next Advertisements ”;
JSP – Architecture
JSP – Architecture ”; Previous Next The web server needs a JSP engine, i.e, a container to process JSP pages. The JSP container is responsible for intercepting requests for JSP pages. This tutorial makes use of Apache which has built-in JSP container to support JSP pages development. A JSP container works with the Web server to provide the runtime environment and other services a JSP needs. It knows how to understand the special elements that are part of JSPs. Following diagram shows the position of JSP container and JSP files in a Web application. JSP Processing The following steps explain how the web server creates the Webpage using JSP − As with a normal page, your browser sends an HTTP request to the web server. The web server recognizes that the HTTP request is for a JSP page and forwards it to a JSP engine. This is done by using the URL or JSP page which ends with .jsp instead of .html. The JSP engine loads the JSP page from disk and converts it into a servlet content. This conversion is very simple in which all template text is converted to println( ) statements and all JSP elements are converted to Java code. This code implements the corresponding dynamic behavior of the page. The JSP engine compiles the servlet into an executable class and forwards the original request to a servlet engine. A part of the web server called the servlet engine loads the Servlet class and executes it. During execution, the servlet produces an output in HTML format. The output is furthur passed on to the web server by the servlet engine inside an HTTP response. The web server forwards the HTTP response to your browser in terms of static HTML content. Finally, the web browser handles the dynamically-generated HTML page inside the HTTP response exactly as if it were a static page. All the above mentioned steps can be seen in the following diagram − Typically, the JSP engine checks to see whether a servlet for a JSP file already exists and whether the modification date on the JSP is older than the servlet. If the JSP is older than its generated servlet, the JSP container assumes that the JSP hasn”t changed and that the generated servlet still matches the JSP”s contents. This makes the process more efficient than with the other scripting languages (such as PHP) and therefore faster. So in a way, a JSP page is really just another way to write a servlet without having to be a Java programming wiz. Except for the translation phase, a JSP page is handled exactly like a regular servlet. Print Page Previous Next Advertisements ”;
JSP – Handling Date
JSP – Handling Date ”; Previous Next In this chapter, we will discuss how to handle data in JSP. One of the most important advantages of using JSP is that you can use all the methods available in core Java. We will take you through the Date class which is available in the java.util package; this class encapsulates the current date and time. The Date class supports two constructors. The first constructor initializes the object with the current date and time. Date( ) The following constructor accepts one argument that equals the number of milliseconds that have elapsed since midnight, January 1, 1970. Date(long millisec) Once you have a Date object available, you can call any of the following support methods to play with dates − S.No. Methods & Description 1 boolean after(Date date) Returns true if the invoking Date object contains a date that is later than the one specified by date, otherwise, it returns false. 2 boolean before(Date date) Returns true if the invoking Date object contains a date that is earlier than the one specified by date, otherwise, it returns false. 3 Object clone( ) Duplicates the invoking Date object. 4 int compareTo(Date date) Compares the value of the invoking object with that of date. Returns 0 if the values are equal. Returns a negative value if the invoking object is earlier than date. Returns a positive value if the invoking object is later than date. 5 int compareTo(Object obj) Operates identically to compareTo(Date) if obj is of class Date. Otherwise, it throws a ClassCastException. 6 boolean equals(Object date) Returns true if the invoking Date object contains the same time and date as the one specified by date, otherwise, it returns false. 7 long getTime( ) Returns the number of milliseconds that have elapsed since January 1, 1970. 8 int hashCode( ) Returns a hash code for the invoking object. 9 void setTime(long time) Sets the time and date as specified by time, which represents an elapsed time in milliseconds from midnight, January 1, 1970 10 String toString( ) Converts the invoking Date object into a string and returns the result. Getting Current Date and Time With JSP program, it is very easy to get the current date and the time. You can use a simple Date object with the toString() method to print the current date and the time as follows − <%@ page import = “java.io.*,java.util.*, javax.servlet.*” %> <html> <head> <title>Display Current Date & Time</title> </head> <body> <center> <h1>Display Current Date & Time</h1> </center> <% Date date = new Date(); out.print( “<h2 align = “center”>” +date.toString()+”</h2>”); %> </body> </html> Let us now keep the code in CurrentDate.jsp and then call this JSP using the URL http://localhost:8080/CurrentDate.jsp. You will receive the following result − Display Current Date & Time Mon Jun 21 21:46:49 GMT+04:00 2010 Refresh the page with the URL http://localhost:8080/CurrentDate.jsp. You will find difference in seconds everytime you would refresh. Date Comparison As discussed in the previous sections, you can use all the available Java methods in your JSP scripts. In case you need to compare two dates, consider the following methods − You can use getTime( ) method to obtain the number of milliseconds that have elapsed since midnight, January 1, 1970, for both objects and then compare these two values. You can use the methods before( ), after( ), and equals( ) because the 12th of the month comes before the 18th; for example, new Date(99, 2, 12).before(new Date (99, 2, 18)) returns true. You can use the compareTo( ) method; this method is defined by the Comparable interface and implemented by Date. Date Formatting using SimpleDateFormat SimpleDateFormat is a concrete class for formatting and parsing dates in a locale-sensitive manner. SimpleDateFormat allows you to start by choosing any user-defined patterns for date-time formatting. Let us modify the above example as follows − <%@ page import = “java.io.*,java.util.*” %> <%@ page import = “javax.servlet.*,java.text.*” %> <html> <head> <title>Display Current Date & Time</title> </head> <body> <center> <h1>Display Current Date & Time</h1> </center> <% Date dNow = new Date( ); SimpleDateFormat ft = new SimpleDateFormat (“E yyyy.MM.dd ”at” hh:mm:ss a zzz”); out.print( “<h2 align=”center”>” + ft.format(dNow) + “</h2>”); %> </body> </html> Compile the above servlet once again and then call this servlet using the URL http://localhost:8080/CurrentDate. You will receive the following result − Display Current Date & Time Mon 2010.06.21 at 10:06:44 PM GMT+04:00 Simple DateFormat Format Codes To specify the time format, use a time pattern string. In this pattern, all ASCII letters are reserved as pattern letters, which are defined as the following − Character Description Example G Era designator AD y Year in four digits 2001 M Month in year July or 07 d Day in month 0 h Hour in A.M./P.M. (1~12) 2 H Hour in day (0~23) 22 m Minute in hour 30 s Second in minute 55 S Millisecond 234 E Day in week Tuesday D Day in year 360 F Day of week in month 2 (second Wed. in July) w Week in year 40 W Week in month a A.M./P.M. marker PM k Hour in day (1~24) 24 K Hour in A.M./P.M. (0~11) 0 z Time zone Eastern Standard Time ” Escape for text Delimiter “ Single quote ` For a complete list of constant available methods to manipulate date, you can refer to the standard Java documentation. Print Page Previous Next Advertisements ”;
JSP – Discussion
Discuss JSP ”; Previous Next Java Server Pages (JSP) is a server-side programming technology that enables the creation of dynamic, platform-independent method for building Web-based applications. JSP have access to the entire family of Java APIs, including the JDBC API to access enterprise databases. This tutorial will teach you how to use Java Server Pages to develop your web applications in simple and easy steps. Print Page Previous Next Advertisements ”;
JSP – Internationalization
JSP – Internationalization| i18n| l10n ”; Previous Next In this chapter, we will discuss the concept of Internationalization in JSP. Before we proceed, let us understand the following three important terms − Internationalization (i18n) − This means enabling a website to provide different versions of content translated into the visitor”s language or nationality. Localization (l10n) − This means adding resources to a website to adapt it to a particular geographical or cultural region for example Hindi translation to a web site. locale − This is a particular cultural or geographical region. It is usually referred to as a language symbol followed by a country symbol which are separated by an underscore. For example, “en_US” represents english locale for US. There are a number of items which should be taken care of while building up a global Website. This tutorial will not give you complete detail on this but it will give you a good example on how you can offer your Webpage in different languages to the internet community by differentiating their location, i.e., locale. A JSP can pick up appropriate version of the site based on the requester”s locale and provide appropriate site version according to the local language, culture and requirements. Following is the method of request object which returns the Locale object. java.util.Locale request.getLocale() Detecting Locale Following are the important locale methods which you can use to detect requester”s location, language and of course locale. All the below methods display the country name and language name set in the requester”s browser. S.No. Method & Description 1 String getCountry() This method returns the country/region code in upper case for this locale in ISO 3166 2-letter format. 2 String getDisplayCountry() This method returns a name for the locale”s country that is appropriate for display to the user. 3 String getLanguage() This method returns the language code in lower case for this locale in ISO 639 format. 4 String getDisplayLanguage() This method returns a name for the locale”s language that is appropriate for display to the user. 5 String getISO3Country() This method returns a three-letter abbreviation for this locale”s country. 6 String getISO3Language() This method returns a three-letter abbreviation for this locale”s language. Example The following example shows how to display a language and associated country for a request in a JSP − <%@ page import = “java.io.*,java.util.Locale” %> <%@ page import = “javax.servlet.*,javax.servlet.http.* “%> <% //Get the client”s Locale Locale locale = request.getLocale(); String language = locale.getLanguage(); String country = locale.getCountry(); %> <html> <head> <title>Detecting Locale</title> </head> <body> <center> <h1>Detecting Locale</h1> </center> <p align = “center”> <% out.println(“Language : ” + language + “<br />”); out.println(“Country : ” + country + “<br />”); %> </p> </body> </html> Languages Setting A JSP can output a page written in a Western European language such as English, Spanish, German, French, Italian, Dutch etc. Here it is important to set Content-Language header to display all the characters properly. Another important point is to display all the special characters using HTML entities; for example, “ñ” represents “ñ”, and “¡” represents “¡” as follows − <%@ page import = “java.io.*,java.util.Locale” %> <%@ page import = “javax.servlet.*,javax.servlet.http.* “%> <% // Set response content type response.setContentType(“text/html”); // Set spanish language code. response.setHeader(“Content-Language”, “es”); String title = “En Español”; %> <html> <head> <title><% out.print(title); %></title> </head> <body> <center> <h1><% out.print(title); %></h1> </center> <div align = “center”> <p>En Español</p> <p>¡Hola Mundo!</p> </div> </body> </html> Locale Specific Dates You can use the java.text.DateFormat class and its static getDateTimeInstance( ) method to format date and time specific to locale. Following is the example which shows how to format dates specific to a given locale − <%@ page import = “java.io.*,java.util.Locale” %> <%@ page import = “javax.servlet.*,javax.servlet.http.* “%> <%@ page import = “java.text.DateFormat,java.util.Date” %> <% String title = “Locale Specific Dates”; //Get the client”s Locale Locale locale = request.getLocale( ); String date = DateFormat.getDateTimeInstance( DateFormat.FULL, DateFormat.SHORT, locale).format(new Date( )); %> <html> <head> <title><% out.print(title); %></title> </head> <body> <center> <h1><% out.print(title); %></h1> </center> <div align = “center”> <p>Local Date: <% out.print(date); %></p> </div> </body> </html> Locale Specific Currency You can use the java.txt.NumberFormat class and its static getCurrencyInstance( ) method to format a number, such as a long or double type, in a locale specific curreny. Following is the example which shows how to format currency specific to a given locale − <%@ page import = “java.io.*,java.util.Locale” %> <%@ page import = “javax.servlet.*,javax.servlet.http.* “%> <%@ page import = “java.text.NumberFormat,java.util.Date” %> <% String title = “Locale Specific Currency”; //Get the client”s Locale Locale locale = request.getLocale( ); NumberFormat nft = NumberFormat.getCurrencyInstance(locale); String formattedCurr = nft.format(1000000); %> <html> <head> <title><% out.print(title); %></title> </head> <body> <center> <h1><% out.print(title); %></h1> </center> <div align = “center”> <p>Formatted Currency: <% out.print(formattedCurr); %></p> </div> </body> </html> Locale Specific Percentage You can use the java.txt.NumberFormat class and its static getPercentInstance( ) method to get locale specific percentage. Following example shows how to format percentage specific to a given locale − <%@ page import = “java.io.*,java.util.Locale” %> <%@ page import = “javax.servlet.*,javax.servlet.http.* “%> <%@ page import = “java.text.NumberFormat,java.util.Date” %> <% String title = “Locale Specific Percentage”; //Get the client”s Locale Locale locale = request.getLocale( ); NumberFormat nft = NumberFormat.getPercentInstance(locale); String formattedPerc = nft.format(0.51); %> <html> <head> <title><% out.print(title); %></title> </head> <body> <center> <h1><% out.print(title); %></h1> </center> <div align = “center”> <p>Formatted Percentage: <% out.print(formattedPerc); %></p> </div> </body> </html> Print Page Previous Next Advertisements ”;
JSP – Database Access
JSP – Database Access ”; Previous Next In this chapter, we will discuss how to access database with JSP. We assume you have good understanding on how JDBC application works. Before starting with database access through a JSP, make sure you have proper JDBC environment setup along with a database. For more detail on how to access database using JDBC and its environment setup you can go through our JDBC Tutorial. To start with basic concept, let us create a table and create a few records in that table as follows − Create Table To create the Employees table in the EMP database, use the following steps − Step 1 Open a Command Prompt and change to the installation directory as follows − C:> C:>cd Program FilesMySQLbin C:Program FilesMySQLbin> Step 2 Login to the database as follows − C:Program FilesMySQLbin>mysql -u root -p Enter password: ******** mysql> Step 3 Create the Employee table in the TEST database as follows − − mysql> use TEST; mysql> create table Employees ( id int not null, age int not null, first varchar (255), last varchar (255) ); Query OK, 0 rows affected (0.08 sec) mysql> Create Data Records Let us now create a few records in the Employee table as follows − − mysql> INSERT INTO Employees VALUES (100, 18, ”Zara”, ”Ali”); Query OK, 1 row affected (0.05 sec) mysql> INSERT INTO Employees VALUES (101, 25, ”Mahnaz”, ”Fatma”); Query OK, 1 row affected (0.00 sec) mysql> INSERT INTO Employees VALUES (102, 30, ”Zaid”, ”Khan”); Query OK, 1 row affected (0.00 sec) mysql> INSERT INTO Employees VALUES (103, 28, ”Sumit”, ”Mittal”); Query OK, 1 row affected (0.00 sec) mysql> SELECT Operation Following example shows how we can execute the SQL SELECT statement using JTSL in JSP programming − <%@ page import = “java.io.*,java.util.*,java.sql.*”%> <%@ page import = “javax.servlet.http.*,javax.servlet.*” %> <%@ taglib uri=”http://java.sun.com/jsp/jstl/core” prefix = “c”%> <%@ taglib uri=”http://java.sun.com/jsp/jstl/sql” prefix = “sql”%> <html> <head> <title>SELECT Operation</title> </head> <body> <sql:setDataSource var = “snapshot” driver = “com.mysql.jdbc.Driver” url = “jdbc:mysql://localhost/TEST” user = “root” password = “pass123″/> <sql:query dataSource = “${snapshot}” var = “result”> SELECT * from Employees; </sql:query> <table border = “1” width = “100%”> <tr> <th>Emp ID</th> <th>First Name</th> <th>Last Name</th> <th>Age</th> </tr> <c:forEach var = “row” items = “${result.rows}”> <tr> <td><c:out value = “${row.id}”/></td> <td><c:out value = “${row.first}”/></td> <td><c:out value = “${row.last}”/></td> <td><c:out value = “${row.age}”/></td> </tr> </c:forEach> </table> </body> </html> Access the above JSP, the following result will be displayed − Emp ID First Name Last Name Age 100 Zara Ali 18 101 Mahnaz Fatma 25 102 Zaid Khan 30 103 Sumit Mittal 28 INSERT Operation Following example shows how we can execute the SQL INSERT statement using JTSL in JSP programming − <%@ page import = “java.io.*,java.util.*,java.sql.*”%> <%@ page import = “javax.servlet.http.*,javax.servlet.*” %> <%@ taglib uri=”http://java.sun.com/jsp/jstl/core” prefix = “c”%> <%@ taglib uri=”http://java.sun.com/jsp/jstl/sql” prefix = “sql”%> <html> <head> <title>JINSERT Operation</title> </head> <body> <sql:setDataSource var = “snapshot” driver = “com.mysql.jdbc.Driver” url = “jdbc:mysql://localhost/TEST” user = “root” password = “pass123″/> <sql:update dataSource = “${snapshot}” var = “result”> INSERT INTO Employees VALUES (104, 2, ”Nuha”, ”Ali”); </sql:update> <sql:query dataSource = “${snapshot}” var = “result”> SELECT * from Employees; </sql:query> <table border = “1” width = “100%”> <tr> <th>Emp ID</th> <th>First Name</th> <th>Last Name</th> <th>Age</th> </tr> <c:forEach var = “row” items = “${result.rows}”> <tr> <td><c:out value = “${row.id}”/></td> <td><c:out value = “${row.first}”/></td> <td><c:out value = “${row.last}”/></td> <td><c:out value = “${row.age}”/></td> </tr> </c:forEach> </table> </body> </html> Access the above JSP, the following result will be displayed − Emp ID First Name Last Name Age 100 Zara Ali 18 101 Mahnaz Fatma 25 102 Zaid Khan 30 103 Sumit Mittal 28 104 Nuha Ali 2 DELETE Operation Following example shows how we can execute the SQL DELETE statement using JTSL in JSP programming − <%@ page import = “java.io.*,java.util.*,java.sql.*”%> <%@ page import = “javax.servlet.http.*,javax.servlet.*” %> <%@ taglib uri=”http://java.sun.com/jsp/jstl/core” prefix = “c”%> <%@ taglib uri=”http://java.sun.com/jsp/jstl/sql” prefix = “sql”%> <html> <head> <title>DELETE Operation</title> </head> <body> <sql:setDataSource var = “snapshot” driver = “com.mysql.jdbc.Driver” url = “jdbc:mysql://localhost/TEST” user = “root” password = “pass123″/> <c:set var = “empId” value = “103”/> <sql:update dataSource = “${snapshot}” var = “count”> DELETE FROM Employees WHERE Id = ? <sql:param value = “${empId}” /> </sql:update> <sql:query dataSource = “${snapshot}” var = “result”> SELECT * from Employees; </sql:query> <table border = “1” width = “100%”> <tr> <th>Emp ID</th> <th>First Name</th> <th>Last Name</th> <th>Age</th> </tr> <c:forEach var = “row” items = “${result.rows}”> <tr> <td><c:out value = “${row.id}”/></td> <td><c:out value = “${row.first}”/></td> <td><c:out value = “${row.last}”/></td> <td><c:out value = “${row.age}”/></td> </tr> </c:forEach> </table> </body> </html> Access the above JSP, the following result will be displayed − Emp ID First Name Last Name Age 100 Zara Ali 18 101 Mahnaz Fatma 25 102 Zaid Khan 30 UPDATE Operation Following example shows how we can execute the SQL UPDATE statement using JTSL in JSP programming − <%@ page import = “java.io.*,java.util.*,java.sql.*”%> <%@ page import = “javax.servlet.http.*,javax.servlet.*” %> <%@ taglib uri = “http://java.sun.com/jsp/jstl/core” prefix = “c”%> <%@ taglib uri = “http://java.sun.com/jsp/jstl/sql” prefix = “sql”%> <html> <head> <title>DELETE Operation</title> </head> <body> <sql:setDataSource var = “snapshot” driver = “com.mysql.jdbc.Driver” url = “jdbc:mysql://localhost/TEST” user = “root” password = “pass123″/> <c:set var = “empId” value = “102”/> <sql:update dataSource = “${snapshot}” var = “count”> UPDATE Employees SET WHERE last = ”Ali” <sql:param value = “${empId}” /> </sql:update> <sql:query dataSource = “${snapshot}” var = “result”> SELECT * from Employees; </sql:query> <table border = “1” width = “100%”> <tr> <th>Emp ID</th> <th>First Name</th> <th>Last Name</th> <th>Age</th> </tr> <c:forEach var = “row” items = “${result.rows}”> <tr> <td><c:out value = “${row.id}”/></td> <td><c:out value = “${row.first}”/></td> <td><c:out value = “${row.last}”/></td> <td><c:out value = “${row.age}”/></td> </tr> </c:forEach> </table> </body> </html> Access the above JSP, the following result will be displayed − Emp ID First Name Last Name Age 100 Zara Ali 18 101 Mahnaz Fatma 25 102 Zaid Ali 30 Print Page Previous Next Advertisements ”;
JSP – Security
JSP – Security ”; Previous Next JavaServer Pages and servlets make several mechanisms available to Web developers to secure applications. Resources are protected declaratively by identifying them in the application deployment descriptor and assigning a role to them. Several levels of authentication are available, ranging from basic authentication using identifiers and passwords to sophisticated authentication using certificates. Role Based Authentication The authentication mechanism in the servlet specification uses a technique called role-based security. The idea is that rather than restricting resources at the user level, you create roles and restrict the resources by role. You can define different roles in file tomcat-users.xml, which is located off Tomcat”s home directory in conf. An example of this file is shown below − <?xml version = ”1.0” encoding = ”utf-8”?> <tomcat-users> <role rolename = “tomcat”/> <role rolename = “role1″/> <role rolename = “manager”/> <role rolename = “admin”/> <user username = “tomcat” password = “tomcat” roles = “tomcat”/> <user username = “role1” password = “tomcat” roles = “role1″/> <user username = “both” password = “tomcat” roles = “tomcat,role1″/> <user username = “admin” password = “secret” roles = “admin,manager”/> </tomcat-users> This file defines a simple mapping between username, password, and role. Notice that a given user may have multiple roles; for example, username = “both” is in the “tomcat” role and the “role1” role. Once you have identified and defined different roles, role-based security restrictions can be placed on different Web Application resources by using the <security-constraint> element in web.xml file available in the WEB-INF directory. Following is a sample entry in web.xml − <web-app> … <security-constraint> <web-resource-collection> <web-resource-name>SecuredBookSite</web-resource-name> <url-pattern>/secured/*</url-pattern> <http-method>GET</http-method> <http-method>POST</http-method> </web-resource-collection> <auth-constraint> <description> Let only managers use this app </description> <role-name>manager</role-name> </auth-constraint> </security-constraint> <security-role> <role-name>manager</role-name> </security-role> <login-config> <auth-method>BASIC</auth-method> </login-config> … </web-app> The above entries would mean − Any HTTP GET or POST request to a URL matched by /secured/* would be subject to the security restriction. A person with the role of a manager is given access to the secured resources. The login-config element is used to describe the BASIC form of authentication. If you try browsing any URL including the /security directory, the following dialog box will be displayed asking for username and password. If you provide a user “admin” and password “secret”, then you will have access on the URL matched by /secured/* as we have defined the user admin with manager role who is allowed to access this resource. Form Based Authentication When you use the FORM authentication method, you must supply a login form to prompt the user for a username and password. Following is a simple code of login.jsp. This helps create a form for the same purpose − <html> <body bgcolor = “#ffffff”> <form method = “POST” action =”j_security_check”> <table border = “0”> <tr> <td>Login</td> <td><input type = “text” name=”j_username”></td> </tr> <tr> <td>Password</td> <td><input type = “password” name=”j_password”></td> </tr> </table> <input type = “submit” value = “Login!”> </form> </body> </html> Here you have to make sure that the login form must contain the form elements named j_username and j_password. The action in the <form> tag must be j_security_check. POST must be used as the form method. At the same time, you will have to modify the <login-config> tag to specify the auth-method as FORM − <web-app> … <security-constraint> <web-resource-collection> <web-resource-name>SecuredBookSite</web-resource-name> <url-pattern>/secured/*</url-pattern> <http-method>GET</http-method> <http-method>POST</http-method> </web-resource-collection> <auth-constraint> <description>Let only managers use this app</description> <role-name>manager</role-name> </auth-constraint> </security-constraint> <security-role> <role-name>manager</role-name> </security-role> <login-config> <auth-method>FORM</auth-method> <form-login-config> <form-login-page>/login.jsp</form-login-page> <form-error-page>/error.jsp</form-error-page> </form-login-config> </login-config> … </web-app> Now when you try to access any resource with URL /secured/*, it will display the above form asking for the user id and password. When the container sees the “j_security_check” action, it uses some internal mechanism to authenticate the caller. If the login succeeds and the caller is authorized to access the secured resource, then the container uses a session-id to identify a login session for the caller from that point on. The container maintains the login session with a cookie containing the session-id. The server sends the cookie back to the client, and as long as the caller presents this cookie with subsequent requests, then the container will know who the caller is. If the login fails, then the server sends back the page identified by the form-error-page setting Here, j_security_check is the action that applications using form based login have to specify for the login form. In the same form, you should also have a text input control called j_username and a password input control called j_password. When you see this, it means that the information contained in the form will be submitted to the server, which will check name and password. How this is done is server specific. Check Standard Realm Implementations to understand how j_security_check works for Tomcat container.. Programmatic Security in a Servlet/JSP The HttpServletRequest object provides the following methods, which can be used to mine security information at runtime − S.No. Method & Description 1 String getAuthType() The getAuthType() method returns a String object that represents the name of the authentication scheme used to protect the Servlet. 2 boolean isUserInRole(java.lang.String role) The isUserInRole() method returns a boolean value: true if the user is in the given role or false if they are not. 3 String getProtocol() The getProtocol() method returns a String object representing the protocol that was used to send the request. This value can be checked to determine if a secure protocol was used. 4 boolean isSecure() The isSecure() method returns a boolean value representing if the request was made using HTTPS. A value of true means it was and the connection is secure. A value of false means the request was not. 5 Principle getUserPrinciple() The getUserPrinciple() method returns a java.security.Principle object that contains the name of the current authenticated user. For example, for a JavaServer Page that links to pages for managers, you might have the following code − <% if (request.isUserInRole(“manager”)) { %> <a href = “managers/mgrreport.jsp”>Manager Report</a> <a href = “managers/personnel.jsp”>Personnel Records</a> <% } %> By checking the user”s role in a JSP or servlet,
JSP – Lifecycle
JSP – Lifecycle ”; Previous Next In this chapter, we will discuss the lifecycle of JSP. The key to understanding the low-level functionality of JSP is to understand the simple life cycle they follow. A JSP life cycle is defined as the process from its creation till the destruction. This is similar to a servlet life cycle with an additional step which is required to compile a JSP into servlet. Paths Followed By JSP The following are the paths followed by a JSP − Compilation Initialization Execution Cleanup The four major phases of a JSP life cycle are very similar to the Servlet Life Cycle. The four phases have been described below − JSP Compilation When a browser asks for a JSP, the JSP engine first checks to see whether it needs to compile the page. If the page has never been compiled, or if the JSP has been modified since it was last compiled, the JSP engine compiles the page. The compilation process involves three steps − Parsing the JSP. Turning the JSP into a servlet. Compiling the servlet. JSP Initialization When a container loads a JSP it invokes the jspInit() method before servicing any requests. If you need to perform JSP-specific initialization, override the jspInit() method − public void jspInit(){ // Initialization code… } Typically, initialization is performed only once and as with the servlet init method, you generally initialize database connections, open files, and create lookup tables in the jspInit method. JSP Execution This phase of the JSP life cycle represents all interactions with requests until the JSP is destroyed. Whenever a browser requests a JSP and the page has been loaded and initialized, the JSP engine invokes the _jspService() method in the JSP. The _jspService() method takes an HttpServletRequest and an HttpServletResponse as its parameters as follows − void _jspService(HttpServletRequest request, HttpServletResponse response) { // Service handling code… } The _jspService() method of a JSP is invoked on request basis. This is responsible for generating the response for that request and this method is also responsible for generating responses to all seven of the HTTP methods, i.e, GET, POST, DELETE, etc. JSP Cleanup The destruction phase of the JSP life cycle represents when a JSP is being removed from use by a container. The jspDestroy() method is the JSP equivalent of the destroy method for servlets. Override jspDestroy when you need to perform any cleanup, such as releasing database connections or closing open files. The jspDestroy() method has the following form − public void jspDestroy() { // Your cleanup code goes here. } Print Page Previous Next Advertisements ”;
JSP – Hits Counter
JSP – Hits Counter ”; Previous Next In this chapter, we will discuss Hits Counter in JSP. A hit counter tells you about the number of visits on a particular page of your web site. Usually you attach a hit counter with your index.jsp page assuming people first land on your home page. To implement a hit counter you can make use of the Application Implicit object and associated methods getAttribute() and setAttribute(). This object is a representation of the JSP page through its entire lifecycle. This object is created when the JSP page is initialized and will be removed when the JSP page is removed by the jspDestroy() method. Following is the syntax to set a variable at application level − application.setAttribute(String Key, Object Value); You can use the above method to set a hit counter variable and to reset the same variable. Following is the method to read the variable set by the previous method − application.getAttribute(String Key); Every time a user accesses your page, you can read the current value of the hit counter and increase it by one and again set it for future use. Example This example shows how you can use JSP to count the total number of hits on a particular page. If you want to count the total number of hits of your website then you will have to include the same code in all the JSP pages. <%@ page import = “java.io.*,java.util.*” %> <html> <head> <title>Application object in JSP</title> </head> <body> <% Integer hitsCount = (Integer)application.getAttribute(“hitCounter”); if( hitsCount ==null || hitsCount == 0 ) { /* First visit */ out.println(“Welcome to my website!”); hitsCount = 1; } else { /* return visit */ out.println(“Welcome back to my website!”); hitsCount += 1; } application.setAttribute(“hitCounter”, hitsCount); %> <center> <p>Total number of visits: <%= hitsCount%></p> </center> </body> </html> Let us now put the above code in main.jsp and call this JSP using the URL http://localhost:8080/main.jsp. This will display the hit counter value which increases as and when you refresh the page. You can try accessing the page using different browsers and you will find that the hit counter will keep increasing with every hit and you will receive the result as follows − Welcome back to my website! Total number of visits: 12 Hit Counter Resets What when you restart your application, i.e., web server, this will reset your application variable and your counter will reset to zero. To avoid this loss, consider the following points − Define a database table with a single count, let us say hitcount. Assign a zero value to it. With every hit, read the table to get the value of hitcount. Increase the value of hitcount by one and update the table with new value. Display new value of hitcount as total page hit counts. If you want to count hits for all the pages, implement above logic for all the pages. Print Page Previous Next Advertisements ”;