JavaBeat

  • Home
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Privacy

Exception Handling in JSP

January 25, 2014 by Krishna Srinivasan Leave a Comment

  • Java EE Tutorials
  • JSP Tutorials
  • Recommended Books for Java Server Pages (JSP)

An exception is problem that occurs during the execution of any program. Exception can be categorized as:

  • Runtime Exception – It is an exception that occurs during running (executing) the program.
  • Checked Exception – It is a user error in the code. It cannot be necessarily detected by testing.
  • Errors – This cannot be handled either at compile time or runtime. It’s problem beyond the control of the user.

Exception Object is an instance of class java.lang.Throwable. Following are methods in the java.lang.Throwable class:

Code Description
public void printStackTrace() This method is used to print the http exception and its stack trace to the standard error stream.
public StackTraceElement[] getStackTrace This method returns an array of stack elements, each represent one stack frame. The zeroth element of the array will be present at the top of the stack.
public String toString() This method returns the textual representation of String object.
public Throwable getCause() This method returns the cause of exception if the cause is unknown.
public String getMessage() This method returns the detail message about the exception.

We need to use the tag to make JSP page exception handler. In the following example we have link to an error page as errorpage.jsp to set the exception that occurs during execution of the program.

Listing 1: example.jsp

[code lang=”html”]
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1" errorPage="errorpage.jsp" import="java.util.*"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Calculation</title>
</head>
<body>
<% int a,b;
a=6;
b=4;

if(a<=b)
out.print("a is less then b");
else
{
throw new RuntimeException("Error condition!!!");
}

%>
</body>
</html>
[/code]

We have written an errorpage.jsp program. In which it include tag isErrorPage=”true”.

[code lang=”html”]
<%@ page language="java” pageEncoding="ISO-8859-1" import="java.util.*";
isErrorPage="true" %>

<html>
<head>
<title>Error Handling</title>
</head>
<body>
<h1>Hey some error occurred !!!</h1>

<p>Your page generates an exception</p>
<% exception.printStackTrace(response.getWriter()); %>
</body>
</html>
[/code]

Execute the JSP file example.jsp in Eclipse by selecting Run As > Run On Server and output would be as seen below:

jsp_exceptionhandling_demo

Previous Tutorial : Cookies Handling in JSP

Filed Under: Java EE Tagged With: JSP Tutorials

JSP Tutorials

January 24, 2014 by Krishna Srinivasan Leave a Comment

Java Server Pages (JSP) is a view technology bundled with the Java Enterprise Edition (Java EE) specifications. It was considered as the default view technology for Java EE applications and alternative for the servlet applications. Where as servlet is a Java program which helps to write the plain Java class, JSP jelps you to write the HTML page with the Java code. Servlet and JSP worked for the different purposes. Prior to JSP, only the servlet classes used for the logic and presentation purposes. The first version of the JSP 1.1 released with the J2EE 1.1 on December 1999. The latest version of JSP is JSP 2.2 released with Java EE 6.

The importance of JSP started faded away when the different view technologies taken as the alternative for the JSP. It makes important for the Java EE specification to improve the view technology and JSP looked very much outdated.  In the year of 2004, first specification of Java Server Faces (JSF) 1.0 release as another view technology within the Java EE package. Later JSF got the much significance and most of the projects adopted the alternative view technologies.

JSP pages can be run in any of the Java Web servers like Tomcat, Jetty, etc. When JSP pages are compiled by the servlet container, it is first translated to the servlets and then executed by the server. In short, JSPs are abstraction of the servlets. There are many popular frameworks developed using the JSP and Servlet as the core technologies including Apache Struts.

  • Introduction to JSP : A basic tutorial for JSP and it explains what is thhis technology.
  • JSP Architecture + Lifecycle : This tutorial highlights the JSP architecture and lifecycle methods init(), service() and destroy. Also the different phases of a JSP file when deployed to the server. First it converts to servlet, then compiled and executed.
  • Create JSP Page in Eclipse : It is a simple example to create your own Java Server Page (JSP) using the eclipse IDE. WIth neat screenshots, this post would be a step-by-step guide to create the web project.
  • JSP Syntax : How to write the web pages using JSP?. There are different syntax for initialization block, scriptlets, expressions, directives,etc. This article highlights each syntax with suitable example snippet.
  • JSP Actions : JSP actions are one of the important component for dynamically running the application.
  • JSP Directives :
  • JSP Implicit Objects : There are nine implicit objects, namingly page, session, request, out, pageContext, exception, object, application. This post details out the each object with the simple to understand examples.
  • JSP Redirect
  • JSP API : List of most widely used JSP APIs and brief description about the each classes and interafces.
  • Session Tracking in JSP :
  • How To Use JavaBeans in JSP?
  • Auto Refresh a Web Page In JSP
  • How To Debug JSP Page?
  • How to Send Mail using JSP?
  • Upload a File Using JSP
  • JSP Expression Language (EL)
  • Cookies Handling in JSP
  • Exception Handling in JSP

Filed Under: Tutorials Tagged With: JSP Tutorials

Cookies Handling in JSP

January 24, 2014 by Krishna Srinivasan Leave a Comment

  • Java EE Tutorials
  • JSP Tutorials
  • Recommended Books for Java Server Pages (JSP)

Cookie is simple information stored by server on client side. Some of the features of cookie are:

  • It allows servers to store user’s information on user machine. Cookies are stored in the partition assigned to the web server’s domain.
  • All cookies for that domain are sent in every request to that web server. Cookies help in to identify user uniquely for session management.
  • Cookies have lifespan and flushed by the client browser at the end of that lifespan. The purpose of cookie is to recognize user on server.

We can create cookies using Cookie class in the servlet API. We can add cookies to response object using addCookie () method. We can access cookies using getCookies () method. For Example: If we want to store user’s name on our web site then we can use following simple code to store that cookie.

[code lang=”java”]
String name=request.getParameter (“username”);
Cookie c=new Cookie (“yourname”, name);
response.addCookie(c);
[/code]

Cookie working

  • We can use HTTP cookies to perform session management. The web container stores the session ID on the client machine. When the getSession () method is called, the web container uses session ID cookie information to find the session object.
  • The cookie mechanism is the default HttpSession strategy. Some browsers do not support cookies or some users turn off cookies on their browsers. If that happens then cookie based session management fails.
  • We can detect if cookies are being used for session management using isRequestSessionIdFromCookie method in the HttpServletRequest interface. It returns true if cookies are used.
  • A similar method isRequestSessionIdFromURL method returns true if URL-rewriting is used for session management.

Cookie class has following methods:

  • getComment () : Returns comment describing the purpose of the cookie.
  • getMaxAge () : Returns maximum specified age of the cookie.
  • getName() : Returns name of the cookie.
  • getPath() : Returns URL for which cookie is targeted.
  • gatValue() :Returns value of the cookie.
  • setComment(String) : Cookie’s purpose will be described using this comment.
  • setMaxAge(int) : Sets maximum age of the cookie. A zero value causes the cookie to be deleted.
  • setPath(String) : It determines Cookie should begin with this URL .
  • setValue(String) : Sets the value of the cookie.

Cookie Example

First we will create html file as cookie1.html. In this html file we are using <form> tag with method and action attributes. In method attribute we are defining HTTP method called post which do not stores requests in the browser history and action tag will redirect to another JSP file called cookie2.jsp.

Listing 1:cookie1.html

[code lang=”html”]
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Cooking Tracking Example</title>
</head>
<body>
<form method = "post" action="cookie2.jsp">
User Name : <input type = "text" name = "uname">
input type="submit" value="submit" >
</form>
</body>
</html>
[/code]

Now create JSP file as cookie2.jsp.This file is what us referred in cookie1.html file. In this JSP file we are using cookie object. Writing data to cookie object is done while loading new page. Means when submit button is pressed in cookie1.html page it would store value in a cookie.
Listing 2:cookie2.jsp

[code lang=”html”]
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
String name=request.getParameter("uname");
Cookie cookie = new Cookie ("uname",name);
response.addCookie(cookie);
cookie.setMaxAge(50 * 50); //Time is in Minutes
%>
<p>Display the value of the Cookie</p>
User Name is :<%= request.getParameter("uname")%>
</body>
</html>
[/code]

Execute the jsp file cookies1.htm in Eclipse by selecting Run As > Run On Server an output as below would be seen:
jsp_sessiontrack_1
Now enter “javabeat” and click on submit button:
jsp_sessiontrack_2

Previous Tutorial : JSP Expression Language : Next Tutorial : Exception Handling in JSP

Filed Under: Java EE Tagged With: JSP Tutorials

JSP Expression Language (EL)

January 24, 2014 by Krishna Srinivasan Leave a Comment

  • Java EE Tutorials
  • JSP Tutorials
  • Recommended Books for Java Server Pages (JSP)

Expression Language(EL) is to access application data stored in JavaBeans components.

The Syntax of EL in a Jsp is:

[code]
${expression}
[/code]

General Example for EL

Let us create two files namely as expr.jsp and expprocess.jsp.

Listing 1:expr.jsp

[code lang=”html”]
<html>
<head>

<title>Expression Example</title>
</head>
<body><h3>welcome to javabeats</h3>

<%
session.setAttribute("abc","javabeats");
%>

<a href="expprocess.jsp">visit</a>

</body>
</html>
[/code]

This file is used to get input from user. We have used sessionscope object for printing the data that is saved in session scope using EL. The sessionScope object will been explained in next sections.

Listing 2:expprocess.jsp

[code lang=”html”]
<html>
<head>

<title>Insert title here</title>
</head>
<body>
Value is ${sessionScope.abc }

</body>
</html>
[/code]

This file is a process file where in user sends request , which in turn prints the name of the user using EL. Here ${sessionScope.adc} is a expression Language(EL)tag.

Execute the jsp file expr.jsp in Eclipse by selecting Run As > Run On Server an output as below would be seen:
jsp_el1_demo

Now click on the link and the you would be take to the screen:

jsp_el2_demo

Basic Operator of EL

Expression language in JSP supports most of operators supported by Java.

Types of Operator:

  • Arithmetic operators
  • Relational Operators
  • Logical Operators
  • Empty Operators

Arithmetic operators

This table lists all the arithmetic operators supported by JSP EL.

Operator Symbol Description
+ Addition
– Unary operator or minus
/ and div Division
* Multiplication
% and mod Remainder

Relational Operator

This table lists all the relarional operators supported by JSP EL.

Operator Symbol Description
= = and eq Equals
!= and ne Not equals
< and lt Less than
> and gt Greater than
<= and le Less than or equal
>= and ge Greater than or equal

Logical Operator

This table lists all the logical operators supported by JSP EL.

Operator Symbol Description
&& and AND and
|| and or Or
! and not not

Implicit Object in JSP EL

JSP developers can directly use implicit objects in an EL Expression.

Implicit Object Description
pageContext It is used to manipulate page attributes and access object request, session etc
param Request parameter to a single string parameter value.
paramValues Request parameter to an array of values
Header Request Header names to a single string header value
headerValues Request Header names to an array of values
pageScope Request page-scoped attribute names to the to their values
requestScope Request request-scoped attribute names to the to their values
sessionScope Request session-scoped attribute names to the to their values
applicationScope Request application-scoped attribute names to the to their values
cookie Request cookie names to a single Cookie value
initParam Context initialization parameter names to their string parameter values

Previous Tutorial : Send Mail using JSP || Next Tutorial : Cookie Handling in JSP

Filed Under: Java EE Tagged With: JSP Tutorials

Upload a File Using JSP

January 24, 2014 by Krishna Srinivasan Leave a Comment

  • Java EE Tutorials
  • JSP Tutorials
  • Recommended Books for Java Server Pages (JSP)

In general file upload means to receive data from a remote system to a local system. So coming to programming language a JSP can upload file on server by using html form tag. An uploaded file could be text file, image file or any document file.

In JSP we can upload files using multipart/form –data. This can be used to when we need to upload files on server. If we upload large files of mime-types or content types then JSP doesn’t process the request. So we should set maximum file size of in the property files. To upload single file we use single tag with attribute type =”file”. If we want upload multiple files then we should use more than one tag with different values with name attribute.

Creating a File Upload Form

To upload a file on server we can make use of <form> tag. It can be written as follows:

[code lang=”html”]
<form action="UploadFile.jsp" method="post" enctype="multipart/form-data">
[/code]

where:

  • action attribute: It is url of the script the content should be sent to, means it is used to forward request to another resource.
  • method attribute: it specifies HTTP method to be used when sending form data. It can be post or get. But here we are setting it to post method.
  • enctype attribute: It is used to upload files on server using method called “multipart/form-data”

Upload File Example

  1. First we will create one Jsp file called index.jsp. It contains <form> which is used to upload file and forward request to another resource and HTTP method type post.
  2. FileUploader Servlet and handles the request for file upload and uses Apache FileUpload library to parse multipart form data.
  3. Configure servlet and JSP details in web.xml
  4. Create second Jsp file called as result.jsp . It will display the message whether the file is uploaded successfully or not using requestScope[“message”] method.
  5. To execute this program you would need to include in your WEB-INF/lib folder.
    • commons-fileupload-1.3.jar
    • commons-io-2.4.jar
    • javax.servlet-api-3.0.1.jar

Listing 1: FileUploadHandler

[code lang=”java”]
package javabeat.net.jsp.file;

import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class FileUploadHandler extends HttpServlet{
private final String UPLOAD_DIRECTORY = "/home/manisha/Desktop";

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

//process only if its multipart content
if(ServletFileUpload.isMultipartContent(request)){
try {
List<FileItem> multiparts = new ServletFileUpload(
new DiskFileItemFactory()).parseRequest(request);

for(FileItem item : multiparts){
if(!item.isFormField()){
String name = new File(item.getName()).getName();
System.out.println("name "+name);
item.write(
new File(UPLOAD_DIRECTORY + File.separator + name));
}
}

//File uploaded successfully
request.setAttribute("message", "File Uploaded Successfully");
} catch (Exception ex) {
request.setAttribute("message", "File Upload Failed due to " + ex);
}

}else{
request.setAttribute("message",
"Sorry this Servlet only handles file upload request");
}

request.getRequestDispatcher("/result.jsp").forward(request, response);

}

}
[/code]

Listing 2: web.xml

[code lang=”xml”]
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>HelloWorldJSP</display-name>
<servlet>
<servlet-name>FileUploadHandler</servlet-name>
<servlet-class>javabeat.net.jsp.file.FileUploadHandler</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FileUploadHandler</servlet-name>
<url-pattern>/upload</url-pattern>
</servlet-mapping>

<session-config>
<session-timeout>
30
</session-timeout>
</session-config>

<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>

<context-param>
<description>Location to store uploaded file</description>
<param-name>file-upload</param-name>
<param-value>
/home/manisha
</param-value>
</context-param>

</web-app>
[/code]

Listing 3: hello.jsp

[code lang=”html”]
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<div>
<h3> Choose File to Upload in Server </h3>
<form action="upload" method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" value="upload" />
</form>
</div>

</body>
</html>

[/code]

Listing 4: result.jsp

[code lang=”html”]
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<div id="result">
<h3>${requestScope["message"]}</h3>
</div>
</body>
</html>
[/code]

Execute the jsp file hello.jsp in Eclipse by selecting Run As > Run On Server.

Previous Tutorial : Auto Refresh using JSP || Next Tutorial : How to send mail in JSP

Filed Under: Java EE Tagged With: JSP Tutorials

How to Send Mail using JSP?

January 24, 2014 by Krishna Srinivasan Leave a Comment

  • Java EE Tutorials
  • JSP Tutorials
  • Recommended Books for Java Server Pages (JSP)

Java Mail API needs to be used to send mail using JSP. Java Mail API is used to compose, read and write messages.You need to include jars javax.mail and javax.mail.activation to send email using JSP. These packages contain core classes of Java Mail API. Java Mail API provides classes which constitute a mail system. Java Mail is used to receive email via SMTP, POP3 and IMAP protocols.

  • SMTP Protocol: It stands for Simple Mail Transfer Protocol which is used for transmission of mail across Internet Protocol (IP).It is also used for sending mail between servers. It can send messages to one server to another using POP or IMAP.
  • POP Protocol: It stands for Post Office Protocol. It is used to retrieve mail from remote server. There are two types in POP. The First one is called POP2 which can be used to send mail using SMTP protocol. The second one is called POP3 which can be used to send mail with or without SMTP protocol.
  • IMAP Protocol: It stands for Internet Message Access Protocol. Like POP protocol it is also used to retrieve mail from remote server.

Following steps are used to send mail using Java Mail API.

  • Get the Session Object: To send email Java Mail API uses send () method on Transport class. This can be achieved by using JAVAMail Session object.
  • Compose the message: Here we can write contents of message in body .The setSubject () method is used to set subject line and the setText () method is used to set content of the body. The javax.mail. Message package is used to compose the message.
  • Send the message: We can send the message by using package javax.mail. Transport.

Now let us write a simple program to send an email. Write a JSP called sendemail.jsp. This file contains the logic to send email. Include jars activation.jar and javax.mail.jar in the WEB-INF/lib folder.

To send email you need to have a SMTP server that is responsible foe sending emails. Using JangoSMPT server (online) is one of the methods to get SMTP server. Other method may be install a SMPT server like postfix on your machine or use SMTP server provided by gmail,yahoo etc.
Via JangoSMPT server server emails are sent to our destination email address. You can create an account by visiting this site and configure your email adress.

Listing 1: sendemail.jsp

[code lang=”html”]
<%@ page import="java.io.*,java.util.*,javax.mail.*"%>
<%@ page import="javax.mail.internet.*,javax.activation.*"%>
<%@ page import="javax.servlet.http.*,javax.servlet.*"%>
<%
String result;
//Recipient’s email ID needs to be mentioned.
String to = "toemailaddress@gmail.com";

// Sender’s email ID needs to be mentioned
String from = "fromemailaddress@gmail.com";
final String username = "someusername";
final String password = "password";

// Assuming you are sending email through relay.jangosmtp.net
String host = "relay.jangosmtp.net";

Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", "25");

//Get the Session object.
Session mailSession = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username,
password);
}
});

try {
// Create a default MimeMessage object.
Message message = new MimeMessage(mailSession);

// Set From: header field of the header.
message.setFrom(new InternetAddress(from));

// Set To: header field of the header.
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to));

// Set Subject: header field
message.setSubject("Testing Subject");

// Now set the actual message
message.setText("Hello, this is sample for to check send "
+ "email using JavaMailAPI in JSP ");

// Send message
Transport.send(message);

System.out.println("Sent message successfully….");
result = "Sent message successfully….";

} catch (MessagingException e) {
e.printStackTrace();
result = "Error: unable to send message….";

}
%>
<html>
<head>
<title>Send Email using JSP</title>
</head>
<body>
<center>
<h1>Send Email using JSP</h1>
</center>
<p align="center">
<%
out.println("Result: " + result + "\n");
%>
</p>
</body>
</html>
[/code]

Execute the jsp file sendemail.jsp in Eclipse by selecting Run As > Run On Server an output as below would be seen:
jsp_sendemail_demo

If you check the inbox of “toemailaddress@gmail.com”, you can see a new message with the text:

[code]
Hello, this is sample for to check send email using JavaMailAPI in JSP
[/code]

Previous Tutorial : Upload File using JSP || Next Tutorial : JSP Expression Language

Filed Under: Java EE Tagged With: JSP Tutorials

How To Debug JSP Page?

January 22, 2014 by Krishna Srinivasan Leave a Comment

  • Java EE Tutorials
  • JSP Tutorials
  • Recommended Books for Java Server Pages (JSP)

Debugging enables a developer to detect and identifies the errors in the application. But testing a JSP/Servlet compared to other programs is often found to be difficult. Following are some of the suggestions which can be used to test you JSP programs:

Using Debugging tools

You can control the execution of a program by

  1. Setting breakpoints– Breakpoints causes the execution of thread should suspend at the location where breakpoint is set.
  2. Stepping through the code– Stepping through the code enables step-by-step debugging when debugging the objects.
  3. Examining the contents of the application -It is possible Examine the contents of application when debugging the application.
  4. Watch points– These are used to set breaks when object is modified. it can be set to break on variable access, variable modification or both.

Using System.out.println ()

System.out.println () can be used at various steps in your JSP and check the results or flow of your program based on the print statements. Let us understand the details of System.out.println ():

  • System is a built in class present in java.lang package. It contains pre-defined methods. These methods provide facilities like standard input, output and more.
  • out is static final field in System class which is of type PrintStream class.
  • println() is a public method in PrintStream to print values. To access in PrintStream class we use out.println().

Lisitng 1:System.out.println () example

[code lang=”html”]
<html>
<body>
<%
Java.util.Date date=new java.util.Date();
System.out.println (date);
%>
</body>
</html>
[/code]

By using System.out.println (), it will display result in console and if we are using out.println (), it will display result on browser as html page.

Using JDK Logger

JDK Logger can be used to log messages for specific system or application component. The package java.util.logging provides the classes and interfaces of the Java’s core logging facilities.This can be used in JSP for debugging.Let see this in an example below:

Lisitng 2:JDK Logger example

[code lang=”html”]
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@page import="java.util.logging.Logger" %>

<html>
<head><title>Logger Example</title></head>
<body>
<% Logger logger=Logger.getLogger(this.getClass().getName());%>

<c:forEach var="toll" begin="1" end="10" step="1" >
<c:set var="mytoll" value="${toll-5}" />
<c:out value="${mytoll}"/></br>
<% String message = "toll="
+ pageContext.findAttribute("toll")
+ " mytollt="
+ pageContext.findAttribute("mytoll");
logger.info( message );
%>
</c:forEach>
</body>
</html>
[/code]

Output screen:
jsp_debug_demo
Output on console:

[code]
Jan 22, 2014 10:03:16 AM org.apache.jsp.jskdloggerexample_jsp _jspService
INFO: toll=1 mytollt=-4
Jan 22, 2014 10:03:16 AM org.apache.jsp.jskdloggerexample_jsp _jspService
INFO: toll=2 mytollt=-3
Jan 22, 2014 10:03:16 AM org.apache.jsp.jskdloggerexample_jsp _jspService
INFO: toll=3 mytollt=-2
Jan 22, 2014 10:03:16 AM org.apache.jsp.jskdloggerexample_jsp _jspService
INFO: toll=4 mytollt=-1
Jan 22, 2014 10:03:16 AM org.apache.jsp.jskdloggerexample_jsp _jspService
INFO: toll=5 mytollt=0
Jan 22, 2014 10:03:16 AM org.apache.jsp.jskdloggerexample_jsp _jspService
INFO: toll=6 mytollt=1
Jan 22, 2014 10:03:16 AM org.apache.jsp.jskdloggerexample_jsp _jspService
INFO: toll=7 mytollt=2
Jan 22, 2014 10:03:16 AM org.apache.jsp.jskdloggerexample_jsp _jspService
INFO: toll=8 mytollt=3
Jan 22, 2014 10:03:16 AM org.apache.jsp.jskdloggerexample_jsp _jspService
INFO: toll=9 mytollt=4
Jan 22, 2014 10:03:16 AM org.apache.jsp.jskdloggerexample_jsp _jspService
INFO: toll=10 mytollt=5
[/code]

Using Comments

Comments can be used in debugging process of a JSP.

  1. You can use single line (//…) comments
  2. multiline comments (/*….*/) comment

Both the above types can be used remove parts of code temporarily. The Jsp comment doesn’t appear in the output produced by the Jsp pages. Jsp comments do not increase size of the file.

Previous Tutorial : How To Use JavaBeans in JSP || Next Tutorial : Auto Refresh JSP Page

Filed Under: Java EE Tagged With: JSP Tutorials

Auto Refresh a Web Page In JSP

January 22, 2014 by Krishna Srinivasan Leave a Comment

  • Java EE Tutorials
  • JSP Tutorials
  • Recommended Books for Java Server Pages (JSP)

Instead of refreshing the web page all the time, JSP includes such a code in which refreshing is done automatically in the web page. setIntHeader method of response object (HttpServletResponse) can be used for refreshing the page.

Signature of this method setIntHeader is as shown below:

[code lang=”java”]
Public void setIntHeader(String name, int headerValue)
[/code]

This method set an integer value for their corresponding header name. if the values is already set, then this method overrides the value.

The following example shows us how we have used auto refresh here.

Listing 1: example.jsp

[code lang=”html”]
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<center>
<h2>Hello javabeat</h2>

<% response.setIntHeader("Refresh", 60);%>
Todays date:<%= new java.util.Date()%>

</center>
</body>
</html>
[/code]

Here <% response.setIntHeader(“Refresh”, 60);%> is used to do Auto refresh the program after 60 ms. Execute the example.jsp. Right click on example.jsp and select Run > Run As. Following output would be seen:
jsp_autorefresh_demo

Previous Tutorial : How To Debug JSP || Next Tutorial : Upload a File Using JSP

Filed Under: Java EE Tagged With: JSP Tutorials

How To Use JavaBeans in JSP?

January 21, 2014 by Krishna Srinivasan Leave a Comment

  • Java EE Tutorials
  • JSP Tutorials
  • Recommended Books for Java Server Pages (JSP)

JavaBeans are simple classes that are used to develop dynamic WebPages. JavaBeans are required to create dynamic web pages by using separate java classes instead of using java code in a JSP page. It provides getter and setter methods to get and set values of the properties. Using JavaBeans it is easy to share objects between multiple WebPages.

Java Bean Properties:

  1. getPropertyName () : It is used to read the property. This method is called accessor.
  2. setPropertyName (): It is used to write the property. This method is called mutator.

useBean Tag

<jsp:useBean> tag is used to instantiate a JavaBean or to locate existing bean instance and assign it to a variable name. Synatx of <jsp:useBean> action tag :

[code lang=”html”]
<jsp:usebean id=”bean name” scope=”scope name” class=”packageName.className” beanName=”packageName.className” type=” packageName.className”/>
[/code]

Where:

  • id: It represents variable name assigned to id attribute of useBean tag
  • scope: It represents scope in which bean instance has to be located.Scopes may be page,request,session, and application.Default scope is page.
    • page : It indicates that bean can be used within JSP page until page sends response to client or forwards request to another resource.
    • request : It Indicates bean can be used from any JSP page that processing same request until JSP page sends response to the client.
    • session : It indicates that bean can be used from any JSP page invoked in the same session .The Page in which we create bean must have page directive with session=”true”.
    • application : It indicates that bean can be used from any JSP page in the same application.
  • class : It takes class name to create a bean instance if bean instance not present in given scope.It should have no-argument constructor and should not be an abstract class.
  • beanName : It takes class name or expression .
  • type : It takes a class or interface name, which can be used with class or beanName attribute. This attribute can be used with or without class or beanName.

useBean Example

Let us create a simple bean class Person.java:
Listing 1:Person.java

[code lang=”java”]
package javabeat.net.jsp.beans;

public class Person {
private String firstName = null;
private String lastName = null;
private int age = 0;

public String getFirstName() {
return firstName;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}

public String getLastName() {
return lastName;
}

public void setLastName(String lastName) {
this.lastName = lastName;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}
}

[/code]

Listing 2: beanExample.jsp

[code lang=”html”]
<%@ page language=’java’ contentType=’text/html; charset=UTF-8′
pageEncoding=’UTF-8’%>
<!DOCTYPE html PUBLIC ‘-//W3C//DTD HTML 4.01 Transitional//EN’ ‘http://www.w3.org/TR/html4/loose.dtd’>
<html>
<head>
<meta http-equiv=’Content-Type’ content=’text/html; charset=UTF-8′>
<title>Use Bean Example</title>
</head>
<body>
<jsp:useBean id=’date’ class=’java.util.Date’/>
<jsp:useBean id=’person’ class=’javabeat.net.jsp.beans.Person’>
<jsp:setProperty name=’person’ property=’firstName’
value=’joe’/>
<jsp:setProperty name=’person’ property=’lastName’
value=’smith’/>
<jsp:setProperty name=’person’ property=’age’
value=’10’/>
</jsp:useBean>

<h2>Simple use of bean calling java.util.Date</h2>
Today is <%=date%>
<h2>Example for Accessing JavaBeans Properties</h2>
<p><b>Person First Name:</b>
<jsp:getProperty name=’person’ property=’firstName’/>
</p>
<p><b>Person Last Name:</b>
<jsp:getProperty name=’person’ property=’lastName’/>
</p>
<p><b>Person Age:</b>
<jsp:getProperty name=’person’ property=’age’/>
</p>
</body>
</html>
[/code]

Execute the beanExample.jsp. Right click on beanExample.jsp and select Run > Run As. Following output would be seen:

jsp_javabeans

Previous Tutorial : Session Tracking in JSP || Next Tutorial : Cookies in JSP

Filed Under: Java EE Tagged With: JSP Tutorials

Session Tracking in JSP

January 21, 2014 by Krishna Srinivasan Leave a Comment

  • Java EE Tutorials
  • JSP Tutorials
  • Recommended Books for Java Server Pages (JSP)

Sessions are mechanism for storing client data across multiple HTTP requests. From one request to another user the HTTP server does not maintain a reference or keep any record of client previous request.

HttpSession Methods

  • getAttribute : it returns stored value from session object. It returns null if no value is associated with name.
  • setAttribute : It associates a value with name.
  • removeAttribute : It removes all the values associated with name.
  • getAttributeNames : It returns all attributes names in the session.
  • getId : it returns unique id in the session.
  • isNew : It determine if session is new to client.
  • getcreationTime : It returns time at which session was created.
  • getlastAccessedTime : It returns time at which session was accessed last by client.
  • getMaxInactiveInterval : It gets maximum amount of time session in seconds that access session before being invalidated.
  • setMaxInaxctiveInterval : It sets maximum amount of time session in seconds between client requests before session being invalidated.

Following ways are used to maintain session between client and web server:

Cookies

A cookie, also known as an HTTP cookie, web cookie, or browser cookie, is a small piece of data sent from a website and stored in a user’s web browser while the user is browsing that website.

A cookie’s value can uniquely identify a client, so cookies are commonly used for session management. Browser stores each message in a small file, called cookie.txt. When you request another page from the server, your browser sends the cookie back to the server. Cookies have lifespan and are flushed by the client browser at the end of lifespan.

Cookie objects have following methods.

  1. getComment () : Returns comment describing the purpose of the cookie.
  2. getMaxAge () : Returns maximum specified age of the cookie.
  3. getName() : Returns name of the cookie.
  4. getPath() : Returns URL for which cookie is targeted.
  5. getValue() :Returns value of the cookie.
  6. setComment(String) : Cookie’s purpose will be described using this comment.
  7. setMaxAge(int) : Sets maximum age of the cookie. A zero value causes the cookie to be deleted.
  8. setPath(String) : It determines Cookie should begin with this URL .
  9. setValue(String) : Sets the value of the cookie. Values with special characters such as white space, brackets, equal sign, comma, double quote, slashes , “at” sign, colon and semicolon should be avoided.

Let’s take example for cookies handling.

First we will create html file as cookie1.jsp. In this html file we are using <form> tag with method and action attributes. In method attribute we are defining HTTP method called post which do not stores requests in browser history and action tag will redirect to another JSP file called cookie2.jsp.
Listing 1: Cookie1.jsp

[code lang=”html”]
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Session Tracking Example</title>
</head>
<body>
<form method = "post" action="cookie2.jsp">
User Name : <input type = "text" name = "uname">
<input type="submit" value="submit" >

</form>
</body>
</html>
[/code]

Now create JSP file as cookie2.jsp. This file name should be as same as in cookie1.html file. In this JSP file we are using cookie object. Writing data to cookie object is done while loading new page. Means when submit button is pressed in cookie1.jsp page it would store value in a cookie.

Lisitng 2: cookie2.jsp

[code lang=”html”]
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
String name=request.getParameter("uname");
Cookie cookie = new Cookie ("uname",name);
response.addCookie(cookie);
cookie.setMaxAge(50 * 50); //Time is in Minutes
%>

<p>Display the value of the Cookie</p>
User Name is :<%= request.getParameter("uname")%>
</body>
</html>
[/code]

Execute the Cookie1.jsp. Right click on Cookie1.jsp and select Run > Run As. Following output would be seen:
jsp_sessiontrack_1
Enter the name and click on submit, the following output would be seen:
jsp_sessiontrack_2

Hidden Form Fields

It is hidden (invisible) text field used for maintaining the state of user. We store the information in the hidden field and get it from another servlet.
Following shows how to store value in hidden field.

[code lang=”html”]
<input type=”hidden” name=”uname” value=”javabeat”>
[/code]

Here, name is hidden field name and javabeat is hidden field value. When the form is submitted, the specified name and value are automatically included in the GET or POST data.

URL Rewriting

A static HTML page or form must be dynamically generated to encode every URL. If you cannot verify that every user of web application uses cookies, then you must consider web container need to use URL-rewriting. If the browser does not support cookies, or if cookies are disabled, you can still enable session tracking using URL rewriting.

A web container attempts to use cookies to store the session ID. If that fails then web container tries to use URL-rewriting. URL rewriting essentially includes the session ID within the link itself as a name/value.

Adding the session ID to a link contain following of methods:

  • response.encodeURL (): Associates a session ID with a given URL.
  • response.encodeRedirectURL () : If you are using redirection, this method can be used

URL Rewriting Example

Take two JSP files. Say hello1.jsp and hello2.jsp, which interact with each other. Basically, we create a new session within hello1.jsp and place an object within this session. The user can then traverse to hello2.jsp by clicking on the link present within the page. Within hello2.jsp, we simply extract the contents. We invoke the encodeURL() within hello1.jsp on the link used to invoke hello2.jsp.

Listing 3: hello1.jsp

[code lang=”html”]
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<%@ page session="true" %>
<%
String url =response.encodeURL ("hello2.jsp");
%>
<a href='<%=url%>’>hello2.jsp</a>
</body>
</html>
[/code]

Listing 4: hello2.jsp

[code lang=”html”]
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

</head>
<body>
<p>today’s date is :<%=new java.util.Date()%></p>
</body>
</html>
[/code]

Execute the hello1.jsp. Right click on hello1.jsp and select Run > Run As. Following output would be seen:

jsp_sessiontrack_3
Click on the link hello2.jsp, the following output would be seen, (current date would printed):

jsp_sessiontrack_4

Previous Tutorial : JSP API || Next Tutorial : JavaBeans in JSP

Filed Under: Java EE Tagged With: JSP Tutorials

  • 1
  • 2
  • Next Page »

Follow Us

  • Facebook
  • Pinterest

As a participant in the Amazon Services LLC Associates Program, this site may earn from qualifying purchases. We may also earn commissions on purchases from other retail websites.

JavaBeat

FEATURED TUTORIALS

Answered: Using Java to Convert Int to String

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Copyright © by JavaBeat · All rights reserved