Você está na página 1de 25

Create your first Tomcat Web application

In this section we will show you how to create first web application using Servlet on the tomcat server. We first make a class named as HelloWorld that extends the abstract HttpServlet class. The code written inside the doGet() method takes two arguments, first one is the reference of HttpServletRequest interface and the second one is the HttpServletResponse interface. This method can throw ServletException. This method calls the getWriter() method of the PrintWriter class. Set the classpath of the relevant jar files to compile the servlet i.e.Setting the classpath of the servlet-api.jar file in the variable CLASSPATH inside the environment variable by using the following steps. Now create a java source file as described further in this tutorial and a web.xml file in a directory structure. Compile the java source file, put the compiled file (.class file) in the classes folder of your application and deploy the directory of your application in the webapps folder inside the tomcat directory.
Package myservlets; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloWorld extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<body>"); out.println("<head>"); out.println("<title>Hello World!</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>Hello World!</h1>"); out.println("</body>"); out.println("</html>"); out.close(); } }

XML File for this program: <?xml version="1.0" encoding="ISO-8859-1"?> <web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation= http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd version="2.4"> <description>Examples</description> <display-name>Examples</display-name> <servlet> <servlet-name>hello</servlet-name> <servlet-class>myservlets.HelloWorld</servlet-class> </servlet> <servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern> /hello</url-pattern> </servlet-mapping> </web-app> The output of the program is given below:

A JSP page is a web page that contains Java code along within the HTML tags. JSP application is used for developing dynamic web sites.

Introduction to JSP
Java Server Pages or JSP is Sun's solution used for developing dynamic web sites. JSP stands for Java Server Pages, a technology invented by Sun Microsystems to allow the easy creation of server side HTML pages. A JSP page is a web page that contains Java code embeded within the HTML tags.

JSP is used for developing dynamic web sites. JSP is used for developing user interfaces for web applications. It is used for creating database driven web applications. However it is recommended to use JSP only for developing user interface of web application. JSP can be used as both a kind of Dynamic HTML and a CGI replacement. But most of time it is simple HTML file saved with jsp extension. JSP scripting language is a high performance alternative to CGI scripts. It is used for creating dynamic web content for a web applications. JSP makes it easy to mix static HTML parts with dynamic Java servlet code.

Syntax of JSP Tags


In JSP all the jsp tags begin with < and ends >. These tags allows to embed a huge amount of java code in the JSP Scriptlets.e.g.

Syntax of JSP scripting language:


<% //java codes %> JSP Engine places these code in the _jspService() method. Variables available to the JSP Scriptlets are: request represents the clients request and is a subclass of HttpServletRequest. These variables are used to retrieve the data submitted along the request. Example: <% //java codes String endusers=null; userName=request.getParameter("endusers"); %>

Display the current date with a Servlet

This servlet program is going to show you how to display a current date and current time on the client browser. It is very easy to display current date with the help of a servlet program using the Date class of the java.util package. Servlet extends the HttpServlet and overrides the doGet() method that comes from the HttpServlet class. Then server invokes the doGet() method in the case, if the web server receives the GET request from the client. Then the doGet() method passes two arguments first one is HttpServletRequest and second one is HttpServletResponse object. When the client sends the request to the server, in that case server invokes these two objects i.e. HttpServletRequest object and HttpServletResponse object. HttpServletRequest object shows the client's request and the HttpServletResponse object shows the servlet's response. The doGet() method works like this: The Servlet program first uses the setContentType() method that comes from the response object this sets the content type of the response that is text/html i.e. standard MIME content type of the Html pages. The MIME type inform the browser that what type of data to receive. Then used the method getWriter() from the response object to retrieve the PrintWriter object. To display the output on the browser use the println() method that is come from PrintWriter class. The code the program is given below: package myservlets; import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; public class DateServlet extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ PrintWriter pw = response.getWriter(); Date today = new Date(); pw.println("<html>"+"<body bgcolor=\"#999966\"> <h1>Date and Time with Servlet</h1>"); pw.println("<b>"+ today+"</b></body>"+ "</html>"); } } XML File for this program:

<?xml version="1.0" encoding="ISO-8859-1"?> <web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_5.xsd" version="2.5"> <description> Display current date with help of Servlet </description> <display-name>Display current date with help of Servlet</displayname> <servlet> <servlet-name>DateServlet</servlet-name> <servlet-class>myservlets.DateServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>DateServlet</servlet-name> <url-pattern>/DateServlet</url-pattern> </servlet-mapping> </web-app> The output of the program is given below:

User Registration Form in JSP

In this example we are going to work with a user registration page and saving the data into the database. To store the data in the database table, create a table in which the values will be inserted. Now make one user registration jsp page. In this example we will create a simple registration form which will insert the entered data into the

database successfully with the help of a servlet. When submit button is clicked the data will be inserted into the database. Firstly the registration form data will go to the controller servlet and search for the variables submitted in the form using the method getParameter() method at the request object. Subsequently it passes a query statement to the database to insert the data retrieved from the registration form. To stored the data into the database it uses setString() method and to retrieve the data from the database it uses the getString() method of PreparedStatement object. The code of the program is given below: <html> <body bgcolor="#999966">

<form action="/userregister/Registration " method=post> <table cellpadding=4 cellspacing=2 border=0> <th bgcolor="#999966" colspan=2> <font size=5>REGISTRATION</font> <br><font size=1><sup></sup></font><hr> </th><tr bgcolor="#999966"><td valign=top> <b>First Name<sup>*</sup></b> <br><input type="text" name="firstname" value="" size=15 maxlength=20> </td><td valign=top><b>Last Name<sup>*</sup></b> <br><input type="text" name="surname" value="" size=15 maxlength=20></td> </tr><tr bgcolor="#999966"> <td valign=top><b>E-Mail<sup>*</sup></b> <br><input type="text" name="email" value="" size=25 maxlength=125><br></td><td valign=top> <b>Zip Code<sup>*</sup></b> <br> <input type="text" name="zipcode" value="" size=5 maxlength=6></td> </tr><tr bgcolor="#999966"><td valign=top colspan=2> <b>User Name<sup>*</sup></b><br> <input type="text" name="userId" size=10 value="" maxlength=10> </td></tr><tr bgcolor="#999966"> <td valign=top><b>Password<sup>*</sup></b> <br><input type="password" name="address1" size=10 value="" maxlength=10></td><td valign=top> <b>Confirm Password<sup>*</sup></b> <br><input type="password" name="address2" size=10 value="" maxlength=10></td><br> </tr><td valign=top> <b>Town:<sup>*</sup></b> <br><input type="text" name="town" size=10 value="" maxlength=10></td> <br></tr><td valign=top> <b>City:<sup>*</sup></b> <br><input type="text" name="country" size=10 value="" maxlength=10></td><br> </tr><tr bgcolor="#663300"> <td align=center colspan=2><hr> <input type="submit" value="Submit"></td></tr></table></center>

</form> </body> </html> Registration .java package myservlets; import java.io.*; import java.sql.*; import javax.servlet.*; import javax.servlet.http.*; public class Registration extends HttpServlet{ public void init(ServletConfig config) throws ServletException{ super.init(config); } public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException{ String connectionURL = "jdbc:mysql://localhost/jsp"; Connection connection=null; ResultSet rs; res.setContentType("text/html"); PrintWriter out = res.getWriter(); String uId = req.getParameter("userId"); String fname = req.getParameter("firstname"); String sname = req.getParameter("surname"); String address1 = req.getParameter("address1"); String address2 = req.getParameter("address2"); String town = req.getParameter("town"); String county = req.getParameter("country"); String zipcode = req.getParameter("zipcode"); try { Class.forName("org.gjt.mm.mysql.Driver"); connection = DriverManager.getConnection(connectionURL, "root", "root"); String sql = "insert into userprofile values (?,?,?,?,?,?,?,?)"; PreparedStatement pst = connection.prepareStatement(sql); pst.setString(1, uId); pst.setString(2, fname); pst.setString(3, sname); pst.setString(4, address1); pst.setString(5, address2); pst.setString(6, town); pst.setString(7, county); pst.setString(8, zipcode); int numRowsChanged = pst.executeUpdate(); out.println(" Welcome : "); out.println(" '"+fname+"'"); pst.close(); } catch(ClassNotFoundException e){ out.println("Couldn't load database driver: " + e.getMessage()); } catch(SQLException e){

out.println("SQLException caught: " + e.getMessage()); } catch (Exception e){ out.println(e); } finally { try { if (connection != null) connection.close(); } catch (SQLException ignored){ out.println(ignored); } } } } web.xml file for this program: <?xml version="1.0" encoding="ISO-8859-1"?> <web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_5.xsd" version="2.5"> <description> User Registration and Login Example. </description> <display-name>User Registration and Login Example</display-name> <servlet> <servlet-name>Registration</servlet-name> <servlet-class>myservlets.Registration</servlet-class> </servlet> <servlet-mapping> <servlet-name>Registration</servlet-name> <url-pattern>/Registration</url-pattern> </servlet-mapping> </web-app> The output of the program is given below:

The output of the input data:

Servlet to add the data into database

In this program we are going to insert the data in the database table from a html form. This servlet program works with HTML form in which there are two fields one is for name and the other one is for entering password. In HTML form there is a submit button, clicking on which the values will be passed to the server. The data entered from the HTML form will be retrieved by the server side program i.e. servlet. For servlet program we first need to make a class named as DataInsertionIntoDatabase that extends the abstract HttpServlet class, By the name of the class other person can understand what the program is going to perform. The servlet code written inside the doGet() method takes two arguments, first is HttpServletRequest and the second one is the HttpServletResponse, this method can throw ServletException. This method calls the getWriter() method of PrintWriter class. The data can be inserted in the database that reacquired connection between database and java program. Database connection between database and the java program need the method forName() that is static in nature, this takes one argument which informs about the database driver that is to be used. Now work of static method getConnection() that is from DriverManager class. This method returns the connection object. The method preparedStatement() obtained from the Connection object, returns the PreparedStatement object. It procces the SQL query. HTML form passes the input to be set in the database with help of setString() method. In the case if data is inserted successfully in the table then the output looks like this "Data has been inserted" otherwise "failed to insert the data". The code of the program is given below: <html> <head> <title>New Page 1</title> </head> <body bgcolor="#999966"> <form method="POST" action="/userregister/DataInsertionIntoDatabase"> <!--webbot bot="SaveResults" U-File="fpweb:///_private/form_results.txt" S-Format="TEXT/CSV" S-Label-Fields="TRUE" --> <% int count= 0;%> <input type="hidden" name="id" value="count"> <p>Enter Name:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <input type="text" name="uname" size="20"></p> <p>Enter Password: <input type="text" name="password" size="20"></p> <p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp; <input type="submit" value="Submit" name="B1"></p>

</form> </body> </html> DataInsertionIntoDatabase .java package myservlets; import java.io.*; import java.lang.*; import java.sql.*; import javax.servlet.*; import javax.servlet.http.*; public class DataInsertionIntoDatabase extends HttpServlet{ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ response.setContentType("text/html"); PrintWriter pw = response.getWriter(); String connectionURL = "jdbc:mysql://localhost/jsp"; Connection connection; try{ String id = request.getParameter("id"); String uname = request.getParameter("uname"); String password = request.getParameter("password"); pw.println(uname); pw.println(password); Class.forName("org.gjt.mm.mysql.Driver"); connection = DriverManager.getConnection(connectionURL, "root", "root"); PreparedStatement pst = connection.prepareStatement("insert into login values(?,?,?)"); pst.setString(1,id); pst.setString(2,uname); pst.setString(3,password); int i = pst.executeUpdate(); if(i!=0){ pw.println("<br>Date has been inserted in to Datebase"); } else{ pw.println("failed to insert the data"); } } catch (Exception e){ pw.println(e); } } } web.xml file for this program: <?xml version="1.0" encoding="ISO-8859-1"?> <web-app xmlns="http://java.sun.com/xml/ns/j2ee"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_5.xsd" version="2.5"> <description> Servlet to add the data into database </description> <display-name>Servlet to add the data into database</display-name> <context-param> <param-name>User</param-name> <param-value>RoseIndia</param-value> </context-param> <servlet-name>DataInsertionIntoDatabase</servlet-name> <servlet-class>myservlets.DataInsertionIntoDatabase</servlet-class> </servlet> <servlet-mapping> <servlet-name>DataInsertionIntoDatabase</servlet-name> <url-pattern>/DataInsertionIntoDatabase</url-pattern> </servlet-mapping> </web-app> The output of the program is given below:

This is the output of the above input.

Login Form with jsp


Now for your confidence with JSP syntax, following example of login form will really help to understand jsp page. In this example we will create a simple dynamic JSP page that prints the user information into next page. With the help of this example we are going to show- how to display a logged-in information on to the browser. In this example it is very easy to display it on our browser with the help of java.util package. In this example we are going to insert the data in the login form which will be displayed onto the next page. This jsp program works with html tags in which there are two fields one is for name and the other one is for entering password and there is a submit button, that works on clicking. The code the program is given below: <html> <head> <title>Enter your name and password</title> </head> <body bgcolor="#999966"> <p>&nbsp;</p> <form method="POST" action="loginaction.jsp"> <p><font color="#800000" size="5">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Enter your name:</font><input type="text" name="username" size="20"></p> <p><font color="#800000" size="5"> Enter your password:</font><input type="text" name="password" size="20"></p> <p><input type="submit" value="Submit" name="B1"></p> </form> </body> </html> Here is the code of "loginaction.jsp" file: <%@page contentType="text/html" %> <html> <body bgcolor="#999966"> <p><font size="6">Welcome :&nbsp; <%=request.getParameter("username")%></font></p> </body> </html> The output of the program is given below:

This is the output of the above input:

Session Tracking Basics


Session Tracking Session tracking is a process that servlets use to maintain state about the series of requests from users across some period of time. In session tracking client first make a request for any servlet, container receives the request and generate a unique session track ID and gives it back to the client along with the response. This session tracking ID gets stored on the client machine. when the client request again for the same request session, then the browser looks for that ID and sends it to the server. In this case container find the Id and sends back the response to the client. Session Tracking can be done in three ways: 1.Hidden Form Fields 2.URL Rewriting 3.Cookies Hidden form field is sent back to the server when the form is submitted. In hidden form fields the html entry will be like this : <input type ="hidden" name = "name" value="">. This means that when you submit the form, the specified name and value will be get included in get or post

method. Here the session ID information would be embedded within the form as a hidden field and submitted with the Http POST command. URL Rewriting can be used in place where we don't want to use cookies. This is used to maintain the session. In case the browser sends a request then it is always interpreted as a new request because http protocol is a stateless protocol as it is not persistent. In the case of session tracking cookies are a way for a server to send some message to a client to store, and for the server to later retrieve its data from that client. Servlets send cookies to clients by adding fields to HTTP response headers. Clients automatically return cookies by adding fields to HTTP request headers. The code of the program is given below: package myservlets; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.util.*; public class ShowSession extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String title = "Session Tracking Example"; HttpSession session = request.getSession(true); String heading; Integer count = (Integer)session.getAttribute("count"); if (count == null) { count = new Integer(0); heading = "Session Tracking Example"; } else { heading = "Session Tracking Example"; count = new Integer(count.intValue() + 1); } session.setAttribute("count", count); out.println("</html><head><title>"+title+"</title></head><body>" + "<h1 align=\"\">" + heading + "</H1>\n" + "<h2></h2>\n" + "<table border=1 align=\"\">\n" + "<tr>"+"<TR bgcolor=\"#9999966\">\n"+ "<th>SessionTracking</th>"+ "<th>Time period</th>" + "</tr>" + "<tr>" + "<td>ID</td>" + "<td>" + session.getId() + "</td>" + "</tr>" + "<tr>" +

"<td>Current Time</td>" + " <td>" + new Date(session.getCreationTime()) + "</td>" + "</tr>" + "<tr>" + "<td>Time of Last Access</td>" + " <td>" + new Date(session.getLastAccessedTime()) + "</td>" + "</tr>" + "<tr>" + "<td>Number of Previous Accesses</td>" + " <td>" + count + "</td>" + "</tr>"+ "</table>" + "</body></html>"); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }

web.xml file for this program: <?xml version="1.0" encoding="ISO-8859-1"?> <web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_5.xsd" version="2.5"> <description> Session tracking Example: </description> <display-name>Session tracking Example</display-name> <context-param> <param-name>User</param-name> <param-value>RoseIndia</param-value> </context-param> <servlet-name>ShowSession</servlet-name> <servlet-class>myservlets.ShowSession</servlet-class> </servlet> <servlet-mapping> <servlet-name>ShowSession</servlet-name> <url-pattern>/ShowSession</url-pattern> </servlet-mapping> </web-app> The output of the program is given below:

Servlet to Authenticate User


For security everyone want to restrict the unauthenticated user for access the web site. Now in this example there is a common way of restricting access to websites is by using a use name and there password to be authenticate the connection that checked to database. When the valid username and password from the database then client will be entered with authenticate user and password. When we want that someone else should handle the response of our servlet, then there we should use sendRedirect() method. In sendRedirect whenever the client send any request it goes to the container, In that case container decides whether concerned servlet can handle the request or not ,If not then the servlet decides that the request can be handle by other the servlet. Then the servlet calls the sendRedirect() method of the response object and sends back the response to the browser. The browser search the status code and look for that servlet which handle the request. If again the browser makes a new request, but with the name of that servlet which handle the request and the result will be displayed to client browser. In this process the client is unaware of the processing. The code of the program is given below: <html> <head> <title>Servlet to authenticate user</title> </head> <body bgcolor="#999966"> <h2 align="">Servlet to Authenticate User</h2> <hr> <form action="/userregister/authenticateUserServlet" method="POST"> <p>Enter User ID:&nbsp;&nbsp;&nbsp;&nbsp; <input type="text" name="username" size="20"></p>

<p>Enter password:&nbsp; <input type="text" name="password" size="20"></p> <p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <input type="submit" value="Submit" name="B1"></p> </form> </body> </html> authenticateUserServlet .java package myservlets; import java.io.*; import java.sql.*; import javax.servlet.*; import javax.servlet.http.*; public class authenticateUserServlet extends HttpServlet{ protected void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { response.setContentType("text/html"); PrintWriter pw = response.getWriter(); String name = request.getParameter("username"); String password = request.getParameter("password"); try{ String driver = "org.gjt.mm.mysql.Driver"; Class.forName(driver).newInstance(); Connection con=null; ResultSet rst=null; Statement stmt=null; String url="jdbc:mysql://localhost/jsp?user=root&password=root"; con=DriverManager.getConnection(url); stmt=con.createStatement(); String query = "select uname from login where uname='"+name+"' and password='"+password+"'"; System.out.println(query); ResultSet rs = stmt.executeQuery(query); if(rs.next()){ response.sendRedirect("/userregister/ValidentryServlet"); }

else{ pw.println("Please insert veiled Username and Password!"); } } catch(Exception e){ System.out.println(e.getMessage()); } } } ValidentryServlet .java package myservlets; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class ValidentryServlet extends HttpServlet{ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter pw = response.getWriter(); pw.println("Welcome to World of Knowledge!" + " "); pw.println("Roseindia Technologies Pvt.Ltd. "); } } web.xml file for this program: <?xml version="1.0" encoding="ISO-8859-1"?> <web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_5.xsd" version="2.5"> <description> Servlet to Authenticate User </description> <display-name>Servlet to Authenticate User</display-name> <servlet> <servlet-name>authenticateUserServlet</servlet-name> <servlet-class>myservlets.authenticateUserServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>authenticateUserServlet</servlet-name> <url-pattern>/authenticateUserServlet</url-pattern> </servlet-mapping> <servlet> <servlet-name>ValidentryServlet</servlet-name>

<servlet-class>myservlets.ValidentryServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>ValidentryServlet</servlet-name> <url-pattern>/ValidentryServlet</url-pattern> </servlet-mapping> </web-app> This is the Authenticate User name and password:

This is the output of the above input.

The output of the program is given below:

This is the output of the above input.

The output of the program is given below:

Web Page with jsp


In this example we will show you how to create first web page on tomcat server. JSP simply application that work with Java inside HTML pages. Now we can take any existing HTML page and we change its extension to "Date.jsp" instead of "Date.html". This one the simply exercise for your first application JSP. The HTML file we used in the previous exercise. After modify file extension from ".html" to ".jsp". Then the application load the new file, with the "date.jsp" extension, in your browser.

Following example of date will really help you understand a jsp page. In this example we are going to display a current date and time on client browser. For this we will create a simple dynamic JSP page with java.util.Date class (<%= new java.util.Date() %>). The java.util.Date class is used to get the current date/time for display on JSP page.

Start the tomcat server, open a browser window and type the URL : Start the tomcat server, open a browser window and type the URL http://localhost:8080/date.jsp The code of the program is given below:
<%@page contentType="text/html" import="java.util.*" %> <html> <body> <p>&nbsp;</p> <div align=""> <table border="0" cellpadding="0" cellspacing ="0" width="460" bgcolor="#999999"> <tr> <td width="100%"><font size="6" color ="#800000">&nbsp;Date Example</font></td> </tr> <tr> <td width="100%"><b>&nbsp;Current Date and time is:&nbsp; <font color="#0000ff"> <%= new java.util.Date() %> </font></b></td> </tr> </table> </center> </div> </body> </html>

The output of the program is given below:

Simplest Login and Logout example in JSP


This JSP example shows you how to login and logout the session between JSP pages. JSP provide an implicit object that is session in which use to save the data specific by the particular user. Now in this tutorial we are create application takes an user login from that having user name and password, in this example saves an user session that invalidate with session.invalidate() function. We will display the saved data to the user in another page. Fallowing is the code of the simple JSP file is login.jsp that takes the input from user.

The code of the program is given below:


<html> <head> <title>User Login</title> </head> <br> <body Bgcolor ="#0099cc"><hr><hr> <form method="POST" action="sessionAction.jsp"> <p><b>UserName:</b> <input type="text" name="UserName" size="10"></p> <p><b>Password:</b> &nbsp;&nbsp;<input type="Password" name="Password" size="10"></p> <p><input type="submit" value="Submit" name="submit"><input type= "reset" value="Reset" name="reset"></p><hr><hr> </form> </body> </html>

The above login page prompts the user to enter his or her name. Once the user clicks on the submit button that time sessionAction.jsp is called. The JSP sessionAction.jsp retrieves the user name from request attributes and saves into the user session using the function: session.setAttribute("UserName", request.getParameter("UserName")); The above Action JSP page saves the UserName into the session object and displays a link to next pages that is sessionAction.jsp. When user clicks on the "Next Page to view session value" link, the JSP page sessionAction.jsp displays the user name to the user. Here is the code of sessionAction.jsp:

Here is the code of sessionAction.jsp:


<%@page import="java.util.*" %> <%String str = request.getParameter("UserName"); session.setAttribute("UserName", request.getParameter("UserName"));%> Welcome to <%= session.getAttribute( "UserName" ) %> <% if (session.getAttribute("UserName").equals("")){%> <a href="login.jsp"><b>Login </b></a> <%} else{%> <a href="logout.jsp"><b>Logout</b></a> <%} %>

The function <%= session.getAttribute( "UserName" ) %> is used to retrieve the user name saved in the session. <%= session.getAttribute( "UserName" ) %>

The code of the program is given below:


<%@page import="java.util.*" %> <%session.invalidate();%> You have logged out. Plese <a href="login.jsp"><b>Login</b></a>

The function <%session.invalidate();%> is used to invalidate the user login session.

<%session.invalidate();%>

The output of the program is given below:

The output of the program is given below:

The output of the program is given below:

Você também pode gostar