JSP – Sending Email

JSP – Sending Email ”; Previous Next In this chapter, we will discuss how to send emails using JSP. To send an email using a JSP, you should have the JavaMail API and the Java Activation Framework (JAF) installed on your machine. You can download the latest version of JavaMail (Version 1.2) from the Java”s standard website. You can download the latest version of JavaBeans Activation Framework JAF (Version 1.0.2) from the Java”s standard website. Download and unzip these files, in the newly-created top-level directories. You will find a number of jar files for both the applications. You need to add the mail.jar and the activation.jar files in your CLASSPATH. Send a Simple Email Here is an example to send a simple email from your machine. It is assumed that your localhost is connected to the Internet and that it is capable enough to send an email. Make sure all the jar files from the Java Email API package and the JAF package are available in CLASSPATH. <%@ 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 = “[email protected]”; // Sender”s email ID needs to be mentioned String from = “[email protected]”; // Assuming you are sending email from localhost String host = “localhost”; // Get system properties object Properties properties = System.getProperties(); // Setup mail server properties.setProperty(“mail.smtp.host”, host); // Get the default Session object. Session mailSession = Session.getDefaultInstance(properties); try { // Create a default MimeMessage object. MimeMessage message = new MimeMessage(mailSession); // Set From: header field of the header. message.setFrom(new InternetAddress(from)); // Set To: header field of the header. message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); // Set Subject: header field message.setSubject(“This is the Subject Line!”); // Now set the actual message message.setText(“This is actual message”); // Send message Transport.send(message); result = “Sent message successfully….”; } catch (MessagingException mex) { mex.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> Let us now put the above code in SendEmail.jsp file and call this JSP using the URL http://localhost:8080/SendEmail.jsp. This will help send an email to the given email ID [email protected]. You will receive the following response − Send Email using JSP Result: Sent message successfully…. If you want to send an email to multiple recipients, then use the following methods to specify multiple email IDs − void addRecipients(Message.RecipientType type, Address[] addresses) throws MessagingException Here is the description of the parameters − type − This would be set to TO, CC or BCC. Here CC represents Carbon Copy and BCC represents Black Carbon Copy. Example Message.RecipientType.TO addresses − This is the array of email ID. You would need to use the InternetAddress() method while specifying email IDs Send an HTML Email Here is an example to send an HTML email from your machine. It is assumed that your localhost is connected to the Internet and that it is capable enough to send an email. Make sure all the jar files from the Java Email API package and the JAF package are available in CLASSPATH. This example is very similar to the previous one, except that here we are using the setContent() method to set content whose second argument is “text/html” to specify that the HTML content is included in the message. Using this example, you can send as big an HTML content as you require. <%@ 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 = “[email protected]”; // Sender”s email ID needs to be mentioned String from = “[email protected]”; // Assuming you are sending email from localhost String host = “localhost”; // Get system properties object Properties properties = System.getProperties(); // Setup mail server properties.setProperty(“mail.smtp.host”, host); // Get the default Session object. Session mailSession = Session.getDefaultInstance(properties); try { // Create a default MimeMessage object. MimeMessage message = new MimeMessage(mailSession); // Set From: header field of the header. message.setFrom(new InternetAddress(from)); // Set To: header field of the header. message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); // Set Subject: header field message.setSubject(“This is the Subject Line!”); // Send the actual HTML message, as big as you like message.setContent(“<h1>This is actual message</h1>”, “text/html” ); // Send message Transport.send(message); result = “Sent message successfully….”; } catch (MessagingException mex) { mex.printStackTrace(); result = “Error: unable to send message….”; } %> <html> <head> <title>Send HTML 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> Let us now use the above JSP to send HTML message on a given email ID. Send Attachment in Email Following is an example to send an email with attachment from your machine − <%@ 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 = “[email protected]”; // Sender”s email ID needs to be mentioned String from = “[email protected]”; // Assuming you are sending email from localhost String host = “localhost”; // Get system properties object Properties properties = System.getProperties(); // Setup mail server properties.setProperty(“mail.smtp.host”, host); // Get the default Session object. Session mailSession = Session.getDefaultInstance(properties); try { // Create a default MimeMessage object. MimeMessage message = new MimeMessage(mailSession); // Set From: header field of the header. message.setFrom(new InternetAddress(from)); // Set To: header field of the header. message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); // Set Subject: header field message.setSubject(“This is the Subject Line!”); // Create the message part BodyPart messageBodyPart = new MimeBodyPart(); // Fill the message messageBodyPart.setText(“This is message body”); // Create a multipart message Multipart multipart = new MimeMultipart(); // Set text message part multipart.addBodyPart(messageBodyPart); // Part two is attachment messageBodyPart = new MimeBodyPart(); String filename = “file.txt”; DataSource source = new FileDataSource(filename); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(filename);

JSP – Auto Refresh

JSP – Auto Refresh ”; Previous Next In this chapter, we will discuss Auto Refresh in JSP. Consider a webpage which is displaying live game score or stock market status or currency exchange ration. For all such type of pages, you would need to refresh your Webpage regularly using refresh or reload button with your browser. JSP makes this job easy by providing you a mechanism where you can make a webpage in such a way that it would refresh automatically after a given interval. The simplest way of refreshing a Webpage is by using the setIntHeader() method of the response object. Following is the signature of this method − public void setIntHeader(String header, int headerValue) This method sends back the header “Refresh” to the browser along with an integer value which indicates time interval in seconds. Auto Page Refresh Example In the following example, we will use the setIntHeader() method to set Refresh header. This will help simulate a digital clock − <%@ page import = “java.io.*,java.util.*” %> <html> <head> <title>Auto Refresh Header Example</title> </head> <body> <center> <h2>Auto Refresh Header Example</h2> <% // Set refresh, autoload time as 5 seconds response.setIntHeader(“Refresh”, 5); // Get current time Calendar calendar = new GregorianCalendar(); String am_pm; int hour = calendar.get(Calendar.HOUR); int minute = calendar.get(Calendar.MINUTE); int second = calendar.get(Calendar.SECOND); if(calendar.get(Calendar.AM_PM) == 0) am_pm = “AM”; else am_pm = “PM”; String CT = hour+”:”+ minute +”:”+ second +” “+ am_pm; out.println(“Crrent Time: ” + CT + “n”); %> </center> </body> </html> Now put the above code in main.jsp and try to access it. This will display the current system time after every 5 seconds as follows. Just run the JSP and wait to see the result − Auto Refresh Header Example Current Time is: 9:44:50 PM Print Page Previous Next Advertisements ”;

JSP – Java Beans

JSP – JavaBeans ”; Previous Next A JavaBean is a specially constructed Java class written in the Java and coded according to the JavaBeans API specifications. Following are the unique characteristics that distinguish a JavaBean from other Java classes − It provides a default, no-argument constructor. It should be serializable and that which can implement the Serializable interface. It may have a number of properties which can be read or written. It may have a number of “getter” and “setter” methods for the properties. JavaBeans Properties A JavaBean property is a named attribute that can be accessed by the user of the object. The attribute can be of any Java data type, including the classes that you define. A JavaBean property may be read, write, read only, or write only. JavaBean properties are accessed through two methods in the JavaBean”s implementation class − S.No. Method & Description 1 getPropertyName() For example, if property name is firstName, your method name would be getFirstName() to read that property. This method is called accessor. 2 setPropertyName() For example, if property name is firstName, your method name would be setFirstName() to write that property. This method is called mutator. A read-only attribute will have only a getPropertyName() method, and a write-only attribute will have only a setPropertyName() method. JavaBeans Example Consider a student class with few properties − package com.tutorialspoint; public class StudentsBean implements java.io.Serializable { private String firstName = null; private String lastName = null; private int age = 0; public StudentsBean() { } public String getFirstName(){ return firstName; } public String getLastName(){ return lastName; } public int getAge(){ return age; } public void setFirstName(String firstName){ this.firstName = firstName; } public void setLastName(String lastName){ this.lastName = lastName; } public void setAge(Integer age){ this.age = age; } } Accessing JavaBeans The useBean action declares a JavaBean for use in a JSP. Once declared, the bean becomes a scripting variable that can be accessed by both scripting elements and other custom tags used in the JSP. The full syntax for the useBean tag is as follows − <jsp:useBean id = “bean”s name” scope = “bean”s scope” typeSpec/> Here values for the scope attribute can be a page, request, session or application based on your requirement. The value of the id attribute may be any value as a long as it is a unique name among other useBean declarations in the same JSP. Following example shows how to use the useBean action − <html> <head> <title>useBean Example</title> </head> <body> <jsp:useBean id = “date” class = “java.util.Date” /> <p>The date/time is <%= date %> </body> </html> You will receive the following result − − The date/time is Thu Sep 30 11:18:11 GST 2010 Accessing JavaBeans Properties Along with <jsp:useBean…> action, you can use the <jsp:getProperty/> action to access the get methods and the <jsp:setProperty/> action to access the set methods. Here is the full syntax − <jsp:useBean id = “id” class = “bean”s class” scope = “bean”s scope”> <jsp:setProperty name = “bean”s id” property = “property name” value = “value”/> <jsp:getProperty name = “bean”s id” property = “property name”/> ……….. </jsp:useBean> The name attribute references the id of a JavaBean previously introduced to the JSP by the useBean action. The property attribute is the name of the get or the set methods that should be invoked. Following example shows how to access the data using the above syntax − <html> <head> <title>get and set properties Example</title> </head> <body> <jsp:useBean id = “students” class = “com.tutorialspoint.StudentsBean”> <jsp:setProperty name = “students” property = “firstName” value = “Zara”/> <jsp:setProperty name = “students” property = “lastName” value = “Ali”/> <jsp:setProperty name = “students” property = “age” value = “10”/> </jsp:useBean> <p>Student First Name: <jsp:getProperty name = “students” property = “firstName”/> </p> <p>Student Last Name: <jsp:getProperty name = “students” property = “lastName”/> </p> <p>Student Age: <jsp:getProperty name = “students” property = “age”/> </p> </body> </html> Let us make the StudentsBean.class available in CLASSPATH. Access the above JSP. the following result will be displayed − Student First Name: Zara Student Last Name: Ali Student Age: 10 Print Page Previous Next Advertisements ”;

JSP – Exception Handling

JSP – Exception Handling ”; Previous Next In this chapter. we will discuss how to handle exceptions in JSP. When you are writing a JSP code, you might make coding errors which can occur at any part of the code. There may occur the following type of errors in your JSP code − Checked exceptions A checked exception is an exception that is typically a user error or a problem that cannot be foreseen by the programmer. For example, if a file is to be opened, but the file cannot be found, an exception occurs. These exceptions cannot simply be ignored at the time of compilation. Runtime exceptions A runtime exception is an exception that probably could have been avoided by the programmer. As opposed to the checked exceptions, runtime exceptions are ignored at the time of compliation. Errors These are not exceptions at all, but problems that arise beyond the control of the user or the programmer. Errors are typically ignored in your code because you can rarely do anything about an error. For example, if a stack overflow occurs, an error will arise. They are also ignored at the time of compilation. We will further discuss ways to handle run time exception/error occuring in your JSP code. Using Exception Object The exception object is an instance of a subclass of Throwable (e.g., java.lang. NullPointerException) and is only available in error pages. Following table lists out the important methods available in the Throwable class. S.No. Methods & Description 1 public String getMessage() Returns a detailed message about the exception that has occurred. This message is initialized in the Throwable constructor. 2 public Throwable getCause() Returns the cause of the exception as represented by a Throwable object. 3 public String toString() Returns the name of the class concatenated with the result of getMessage(). 4 public void printStackTrace() Prints the result of toString() along with the stack trace to System.err, the error output stream. 5 public StackTraceElement [] getStackTrace() Returns an array containing each element on the stack trace. The element at index 0 represents the top of the call stack, and the last element in the array represents the method at the bottom of the call stack. 6 public Throwable fillInStackTrace() Fills the stack trace of this Throwable object with the current stack trace, adding to any previous information in the stack trace. JSP gives you an option to specify Error Page for each JSP. Whenever the page throws an exception, the JSP container automatically invokes the error page. Following is an example to specifiy an error page for a main.jsp. To set up an error page, use the <%@ page errorPage = “xxx” %> directive. <%@ page errorPage = “ShowError.jsp” %> <html> <head> <title>Error Handling Example</title> </head> <body> <% // Throw an exception to invoke the error page int x = 1; if (x == 1) { throw new RuntimeException(“Error condition!!!”); } %> </body> </html> We will now write one Error Handling JSP ShowError.jsp, which is given below. Notice that the error-handling page includes the directive <%@ page isErrorPage = “true” %>. This directive causes the JSP compiler to generate the exception instance variable. <%@ page isErrorPage = “true” %> <html> <head> <title>Show Error Page</title> </head> <body> <h1>Opps…</h1> <p>Sorry, an error occurred.</p> <p>Here is the exception stack trace: </p> <pre><% exception.printStackTrace(response.getWriter()); %></pre> </body> </html> Access the main.jsp, you will receive an output somewhat like the following − java.lang.RuntimeException: Error condition!!! …… Opps… Sorry, an error occurred. Here is the exception stack trace: Using JSTL Tags for Error Page You can make use of JSTL tags to write an error page ShowError.jsp. This page has almost same logic as in the above example, with better structure and more information − <%@ taglib prefix = “c” uri = “http://java.sun.com/jsp/jstl/core” %> <%@page isErrorPage = “true” %> <html> <head> <title>Show Error Page</title> </head> <body> <h1>Opps…</h1> <table width = “100%” border = “1”> <tr valign = “top”> <td width = “40%”><b>Error:</b></td> <td>${pageContext.exception}</td> </tr> <tr valign = “top”> <td><b>URI:</b></td> <td>${pageContext.errorData.requestURI}</td> </tr> <tr valign = “top”> <td><b>Status code:</b></td> <td>${pageContext.errorData.statusCode}</td> </tr> <tr valign = “top”> <td><b>Stack trace:</b></td> <td> <c:forEach var = “trace” items = “${pageContext.exception.stackTrace}”> <p>${trace}</p> </c:forEach> </td> </tr> </table> </body> </html> Access the main.jsp, the following will be generated − Opps… Error: java.lang.RuntimeException: Error condition!!! URI: /main.jsp Status code: 500 Stack trace: org.apache.jsp.main_jsp._jspService(main_jsp.java:65) org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:68) javax.servlet.http.HttpServlet.service(HttpServlet.java:722) org.apache.jasper.servlet.JspServlet.service(JspServlet.java:265) javax.servlet.http.HttpServlet.service(HttpServlet.java:722) Using Try…Catch Block If you want to handle errors within the same page and want to take some action instead of firing an error page, you can make use of the try….catch block. Following is a simple example which shows how to use the try…catch block. Let us put the following code in main.jsp − <html> <head> <title>Try…Catch Example</title> </head> <body> <% try { int i = 1; i = i / 0; out.println(“The answer is ” + i); } catch (Exception e) { out.println(“An exception occurred: ” + e.getMessage()); } %> </body> </html> Access the main.jsp, it should generate an output somewhat like the following − An exception occurred: / by zero Print Page Previous Next Advertisements ”;

JSP – Expression Language

JSP – Expression Language (EL) ”; Previous Next JSP Expression Language (EL) makes it possible to easily access application data stored in JavaBeans components. JSP EL allows you to create expressions both (a) arithmetic and (b) logical. Within a JSP EL expression, you can use integers, floating point numbers, strings, the built-in constants true and false for boolean values, and null. Simple Syntax Typically, when you specify an attribute value in a JSP tag, you simply use a string. For example − <jsp:setProperty name = “box” property = “perimeter” value = “100”/> JSP EL allows you to specify an expression for any of these attribute values. A simple syntax for JSP EL is as follows − ${expr} Here expr specifies the expression itself. The most common operators in JSP EL are . and []. These two operators allow you to access various attributes of Java Beans and built-in JSP objects. For example, the above syntax <jsp:setProperty> tag can be written with an expression like − <jsp:setProperty name = “box” property = “perimeter” value = “${2*box.width+2*box.height}”/> When the JSP compiler sees the ${} form in an attribute, it generates code to evaluate the expression and substitues the value of expresson. You can also use the JSP EL expressions within template text for a tag. For example, the <jsp:text> tag simply inserts its content within the body of a JSP. The following <jsp:text> declaration inserts <h1>Hello JSP!</h1> into the JSP output − <jsp:text> <h1>Hello JSP!</h1> </jsp:text> You can now include a JSP EL expression in the body of a <jsp:text> tag (or any other tag) with the same ${} syntax you use for attributes. For example − <jsp:text> Box Perimeter is: ${2*box.width + 2*box.height} </jsp:text> EL expressions can use parentheses to group subexpressions. For example, ${(1 + 2) * 3} equals 9, but ${1 + (2 * 3)} equals 7. To deactivate the evaluation of EL expressions, we specify the isELIgnored attribute of the page directive as below − <%@ page isELIgnored = “true|false” %> The valid values of this attribute are true and false. If it is true, EL expressions are ignored when they appear in static text or tag attributes. If it is false, EL expressions are evaluated by the container. Basic Operators in EL JSP Expression Language (EL) supports most of the arithmetic and logical operators supported by Java. Following table lists out the most frequently used operators − S.No. Operator & Description 1 . Access a bean property or Map entry 2 [] Access an array or List element 3 ( ) Group a subexpression to change the evaluation order 4 + Addition 5 – Subtraction or negation of a value 6 * Multiplication 7 / or div Division 8 % or mod Modulo (remainder) 9 == or eq Test for equality 10 != or ne Test for inequality 11 < or lt Test for less than 12 > or gt Test for greater than 13 <= or le Test for less than or equal 14 >= or ge Test for greater than or equal 15 && or and Test for logical AND 16 || or or Test for logical OR 17 ! or not Unary Boolean complement 18 empty Test for empty variable values Functions in JSP EL JSP EL allows you to use functions in expressions as well. These functions must be defined in the custom tag libraries. A function usage has the following syntax − ${ns:func(param1, param2, …)} Where ns is the namespace of the function, func is the name of the function and param1 is the first parameter value. For example, the function fn:length, which is part of the JSTL library. This function can be used as follows to get the length of a string. ${fn:length(“Get my length”)} To use a function from any tag library (standard or custom), you must install that library on your server and must include the library in your JSP using the <taglib> directive as explained in the JSTL chapter. JSP EL Implicit Objects The JSP expression language supports the following implicit objects − S.No Implicit object & Description 1 pageScope Scoped variables from page scope 2 requestScope Scoped variables from request scope 3 sessionScope Scoped variables from session scope 4 applicationScope Scoped variables from application scope 5 param Request parameters as strings 6 paramValues Request parameters as collections of strings 7 header HTTP request headers as strings 8 headerValues HTTP request headers as collections of strings 9 initParam Context-initialization parameters 10 cookie Cookie values 11 pageContext The JSP PageContext object for the current page You can use these objects in an expression as if they were variables. The examples that follow will help you understand the concepts − The pageContext Object The pageContext object gives you access to the pageContext JSP object. Through the pageContext object, you can access the request object. For example, to access the incoming query string for a request, you can use the following expression − ${pageContext.request.queryString} The Scope Objects The pageScope, requestScope, sessionScope, and applicationScope variables provide access to variables stored at each scope level. For example, if you need to explicitly access the box variable in the application scope, you can access it through the applicationScope variable as applicationScope.box. The param and paramValues Objects The param and paramValues objects give you access to the parameter values normally available through the request.getParameter and request.getParameterValues methods. For example, to access a parameter named order, use the expression ${param.order} or ${param[“order”]}. Following is the example to access a request parameter named username − <%@ page import = “java.io.*,java.util.*” %> <%String title = “Accessing Request Param”;%> <html> <head> <title><% out.print(title); %></title> </head> <body> <center> <h1><% out.print(title); %></h1> </center> <div align = “center”> <p>${param[“username”]}</p> </div> </body> </html> The param object returns single string values, whereas the paramValues object returns string arrays. header and headerValues Objects The header and headerValues objects give you access to the header values normally available through the request.getHeader and the request.getHeaders methods. For example, to access a header named

JSP – Custom Tags

JSP – Custom Tags ”; Previous Next In this chapter, we will discuss the Custom Tags in JSP. A custom tag is a user-defined JSP language element. When a JSP page containing a custom tag is translated into a servlet, the tag is converted to operations on an object called a tag handler. The Web container then invokes those operations when the JSP page”s servlet is executed. JSP tag extensions lets you create new tags that you can insert directly into a JavaServer Page. The JSP 2.0 specification introduced the Simple Tag Handlers for writing these custom tags. To write a custom tag, you can simply extend SimpleTagSupport class and override the doTag() method, where you can place your code to generate content for the tag. Create “Hello” Tag Consider you want to define a custom tag named <ex:Hello> and you want to use it in the following fashion without a body − <ex:Hello /> To create a custom JSP tag, you must first create a Java class that acts as a tag handler. Let us now create the HelloTag class as follows − package com.tutorialspoint; import javax.servlet.jsp.tagext.*; import javax.servlet.jsp.*; import java.io.*; public class HelloTag extends SimpleTagSupport { public void doTag() throws JspException, IOException { JspWriter out = getJspContext().getOut(); out.println(“Hello Custom Tag!”); } } The above code has simple coding where the doTag() method takes the current JspContext object using the getJspContext() method and uses it to send “Hello Custom Tag!” to the current JspWriter object Let us compile the above class and copy it in a directory available in the environment variable CLASSPATH. Finally, create the following tag library file: <Tomcat-Installation-Directory>webappsROOTWEB-INFcustom.tld. <taglib> <tlib-version>1.0</tlib-version> <jsp-version>2.0</jsp-version> <short-name>Example TLD</short-name> <tag> <name>Hello</name> <tag-class>com.tutorialspoint.HelloTag</tag-class> <body-content>empty</body-content> </tag> </taglib> Let us now use the above defined custom tag Hello in our JSP program as follows − <%@ taglib prefix = “ex” uri = “WEB-INF/custom.tld”%> <html> <head> <title>A sample custom tag</title> </head> <body> <ex:Hello/> </body> </html> Call the above JSP and this should produce the following result − Hello Custom Tag! Accessing the Tag Body You can include a message in the body of the tag as you have seen with standard tags. Consider you want to define a custom tag named <ex:Hello> and you want to use it in the following fashion with a body − <ex:Hello> This is message body </ex:Hello> Let us make the following changes in the above tag code to process the body of the tag − package com.tutorialspoint; import javax.servlet.jsp.tagext.*; import javax.servlet.jsp.*; import java.io.*; public class HelloTag extends SimpleTagSupport { StringWriter sw = new StringWriter(); public void doTag() throws JspException, IOException { getJspBody().invoke(sw); getJspContext().getOut().println(sw.toString()); } } Here, the output resulting from the invocation is first captured into a StringWriter before being written to the JspWriter associated with the tag. We need to change TLD file as follows − <taglib> <tlib-version>1.0</tlib-version> <jsp-version>2.0</jsp-version> <short-name>Example TLD with Body</short-name> <tag> <name>Hello</name> <tag-class>com.tutorialspoint.HelloTag</tag-class> <body-content>scriptless</body-content> </tag> </taglib> Let us now call the above tag with proper body as follows − <%@ taglib prefix = “ex” uri = “WEB-INF/custom.tld”%> <html> <head> <title>A sample custom tag</title> </head> <body> <ex:Hello> This is message body </ex:Hello> </body> </html> You will receive the following result − This is message body Custom Tag Attributes You can use various attributes along with your custom tags. To accept an attribute value, a custom tag class needs to implement the setter methods, identical to the JavaBean setter methods as shown below − package com.tutorialspoint; import javax.servlet.jsp.tagext.*; import javax.servlet.jsp.*; import java.io.*; public class HelloTag extends SimpleTagSupport { private String message; public void setMessage(String msg) { this.message = msg; } StringWriter sw = new StringWriter(); public void doTag() throws JspException, IOException { if (message != null) { /* Use message from attribute */ JspWriter out = getJspContext().getOut(); out.println( message ); } else { /* use message from the body */ getJspBody().invoke(sw); getJspContext().getOut().println(sw.toString()); } } } The attribute”s name is “message”, so the setter method is setMessage(). Let us now add this attribute in the TLD file using the <attribute> element as follows − <taglib> <tlib-version>1.0</tlib-version> <jsp-version>2.0</jsp-version> <short-name>Example TLD with Body</short-name> <tag> <name>Hello</name> <tag-class>com.tutorialspoint.HelloTag</tag-class> <body-content>scriptless</body-content> <attribute> <name>message</name> </attribute> </tag> </taglib> Let us follow JSP with message attribute as follows − <%@ taglib prefix = “ex” uri = “WEB-INF/custom.tld”%> <html> <head> <title>A sample custom tag</title> </head> <body> <ex:Hello message = “This is custom tag” /> </body> </html> This will produce following result − This is custom tag Consider including the following properties for an attribute − S.No. Property & Purpose 1 name The name element defines the name of an attribute. Each attribute name must be unique for a particular tag. 2 required This specifies if this attribute is required or is an optional one. It would be false for optional. 3 rtexprvalue Declares if a runtime expression value for a tag attribute is valid 4 type Defines the Java class-type of this attribute. By default it is assumed as String 5 description Informational description can be provided. 6 fragment Declares if this attribute value should be treated as a JspFragment. Following is the example to specify properties related to an attribute − ….. <attribute> <name>attribute_name</name> <required>false</required> <type>java.util.Date</type> <fragment>false</fragment> </attribute> ….. If you are using two attributes, then you can modify your TLD as follows − ….. <attribute> <name>attribute_name1</name> <required>false</required> <type>java.util.Boolean</type> <fragment>false</fragment> </attribute> <attribute> <name>attribute_name2</name> <required>true</required> <type>java.util.Date</type> </attribute> ….. Print Page Previous Next Advertisements ”;

JSP – Debugging

JSP – Debugging ”; Previous Next In this chapter, we will discuss Debugging a JSP. It is always difficult testing/debugging a JSP and servlets. JSP and Servlets tend to involve a large amount of client/server interaction, making errors likely but hard to reproduce. The following are a few hints and suggestions that may aid you in your debugging. Using System.out.println() System.out.println() is easy to use as a marker to test whether a certain piece of code is being executed or not. We can print out variable values as well. Consider the following additional points − Since the System object is part of the core Java objects, it can be used everywhere without the need to install any extra classes. This includes Servlets, JSP, RMI, EJB”s, ordinary Beans and classes, and standalone applications. Compared to stopping at breakpoints, writing to System.out doesn”t interfere much with the normal execution flow of the application, which makes it very valuable when the iming is crucial. Following is the syntax to use System.out.println() − System.out.println(“Debugging message”); Following example shows how to use System.out.print() − <%@taglib prefix = “c” uri = “http://java.sun.com/jsp/jstl/core” %> <html> <head><title>System.out.println</title></head> <body> <c:forEach var = “counter” begin = “1” end = “10” step = “1” > <c:out value = “${counter-5}”/></br> <% System.out.println( “counter = ” + pageContext.findAttribute(“counter”) ); %> </c:forEach> </body> </html> Access the above JSP, the browser will show the following result − -4 -3 -2 -1 0 1 2 3 4 5 If you are using Tomcat, you will also find these lines appended to the end of stdout.log in the logs directory. counter = 1 counter = 2 counter = 3 counter = 4 counter = 5 counter = 6 counter = 7 counter = 8 counter = 9 counter = 10 This way you can bring variables and other information into the system log which can be analyzed to find out the root cause of the problem or for various other reasons. Using the JDB Logger The J2SE logging framework is designed to provide logging services for any class running in the JVM. We can make use of this framework to log any information. Let us re-write the above example using JDK logger API − <%@taglib prefix = “c” uri = “http://java.sun.com/jsp/jstl/core” %> <%@page import = “java.util.logging.Logger” %> <html> <head><title>Logger.info</title></head> <body> <% Logger logger = Logger.getLogger(this.getClass().getName());%> <c:forEach var = “counter” begin = “1” end = “10” step = “1” > <c:set var = “myCount” value = “${counter-5}” /> <c:out value = “${myCount}”/></br> <% String message = “counter = ” + pageContext.findAttribute(“counter”) + “myCount = ” + pageContext.findAttribute(“myCount”); logger.info( message ); %> </c:forEach> </body> </html> The above code will generate similar result on the browser and in stdout.log, but you will have additional information in stdout.log. We will use the info method of the logger because and log the message just for informational purpose. Following is a snapshot of the stdout.log file − 24-Sep-2010 23:31:31 org.apache.jsp.main_jsp _jspService INFO: counter = 1 myCount = -4 24-Sep-2010 23:31:31 org.apache.jsp.main_jsp _jspService INFO: counter = 2 myCount = -3 24-Sep-2010 23:31:31 org.apache.jsp.main_jsp _jspService INFO: counter = 3 myCount = -2 24-Sep-2010 23:31:31 org.apache.jsp.main_jsp _jspService INFO: counter = 4 myCount = -1 24-Sep-2010 23:31:31 org.apache.jsp.main_jsp _jspService INFO: counter = 5 myCount = 0 24-Sep-2010 23:31:31 org.apache.jsp.main_jsp _jspService INFO: counter = 6 myCount = 1 24-Sep-2010 23:31:31 org.apache.jsp.main_jsp _jspService INFO: counter = 7 myCount = 2 24-Sep-2010 23:31:31 org.apache.jsp.main_jsp _jspService INFO: counter = 8 myCount = 3 24-Sep-2010 23:31:31 org.apache.jsp.main_jsp _jspService INFO: counter = 9 myCount = 4 24-Sep-2010 23:31:31 org.apache.jsp.main_jsp _jspService INFO: counter = 10 myCount = 5 Messages can be sent at various levels by using the convenience functions severe(), warning(), info(), config(), fine(), finer(), and finest(). Here finest() method can be used to log finest information and the severe() method can be used to log severe information. You can use Log4J Framework to log messages in different files based on their severity levels and importance. Debugging Tools NetBeans is a free and open-source Java Integrated Development Environment that supports the development of standalone Java applications and Web applications supporting the JSP and servlet specifications and includes a JSP debugger as well. NetBeans supports the following basic debugging functionalities − Breakpoints Stepping through code Watchpoints You can refere to NetBeans documentation to understand above debugging functionalities. Using JDB Debugger You can debug JSP and servlets with the same jdb commands you use to debug an applet or an application. To debug a JSP or servlet, you can debug sun.servlet.http.HttpServer, then observe as HttpServer executes the JSP/servlets in response to HTTP requests we make from a browser. This is very similar to how applets are debugged. The difference is that with applets, the actual program being debugged is sun.applet.AppletViewer. Most debuggers hide this detail by automatically knowing how to debug applets. Until they do the same for JSP, you have to help your debugger by considering the following − Set your debugger”s classpath. This helps you find sun.servlet.http.Http-Server and the associated classes. Set your debugger”s classpath. This helps you find your JSP and support classes, typically ROOTWEB-INFclasses. Once you have set the proper classpath, start debugging sun.servlet.http.HttpServer. You can set breakpoints in whatever JSP you”re interested in debugging, then use a web browser to make a request to the HttpServer for the given JSP (http://localhost:8080/JSPToDebug). The execution here stops at breakpoints. Using Comments Comments in your code can help the debugging process in various ways. Comments can be used in lots of other ways in the debugging process. The JSP uses Java comments and single line (// …) and multiple line (/* … */) comments can be used to temporarily remove parts of your Java code. If the bug disappears, take a closer look at the code you just commented and find out the problem. Client and Server Headers Sometimes when a JSP doesn”t behave as expected, it”s useful to look at the raw HTTP request and response. If you”re familiar with the structure of HTTP, you can read the

JSP – Form Processing

JSP – Form Processing ”; Previous Next In this chapter, we will discuss Form Processing in JSP. You must have come across many situations when you need to pass some information from your browser to the web server and ultimately to your backend program. The browser uses two methods to pass this information to the web server. These methods are the GET Method and the POST Method. The Methods in Form Processing Let us now discuss the methods in Form Processing. GET method The GET method sends the encoded user information appended to the page request. The page and the encoded information are separated by the ? character as follows − http://www.test.com/hello?key1=value1&key2=value2 The GET method is the default method to pass information from the browser to the web server and it produces a long string that appears in your browser”s Location:box. It is recommended that the GET method is better not used. if you have password or other sensitive information to pass to the server. The GET method has size limitation: only 1024 characters can be in a request string. This information is passed using QUERY_STRING header and will be accessible through QUERY_STRING environment variable which can be handled using getQueryString() and getParameter() methods of request object. POST method A generally more reliable method of passing information to a backend program is the POST method. This method packages the information in exactly the same way as the GET method, but instead of sending it as a text string after a ? in the URL it sends it as a separate message. This message comes to the backend program in the form of the standard input which you can parse and use for your processing. JSP handles this type of requests using getParameter() method to read simple parameters and getInputStream() method to read binary data stream coming from the client. Reading Form Data using JSP JSP handles form data parsing automatically using the following methods depending on the situation − getParameter() − You call request.getParameter() method to get the value of a form parameter. getParameterValues() − Call this method if the parameter appears more than once and returns multiple values, for example checkbox. getParameterNames() − Call this method if you want a complete list of all parameters in the current request. getInputStream() − Call this method to read binary data stream coming from the client. GET Method Example Using URL The following URL will pass two values to HelloForm program using the GET method. http://localhost:8080/main.jsp?first_name=ZARA&last_name=ALI Below is the main.jsp JSP program to handle input given by web browser. We are going to use the getParameter() method which makes it very easy to access the passed information − <html> <head> <title>Using GET Method to Read Form Data</title> </head> <body> <h1>Using GET Method to Read Form Data</h1> <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> Now type http://localhost:8080/main.jsp?first_name=ZARA&last_name=ALI in your browser”s Location:box. This will generate the following result − Using GET Method to Read Form Data First Name: ZARA Last Name: ALI GET Method Example Using Form Following is an example that passes two values using the HTML FORM and the submit button. We are going to use the same JSP main.jsp to handle this input. <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 this HTML in a file Hello.htm and put it in <Tomcat-installation-directory>/webapps/ROOT directory. When you would access http://localhost:8080/Hello.htm, you will receive the following output. First Name: Last Name: Try to enter the First Name and the Last Name and then click the submit button to see the result on your local machine where tomcat is running. Based on the input provided, it will generate similar result as mentioned in the above example. POST Method Example Using Form Let us do a little modification in the above JSP to handle both the GET and the POST method. Below is the main.jsp JSP program to handle the input given by web browser using the GET or the POST methods. Infact there is no change in the above JSP because the only way of passing parameters is changed and no binary data is being passed to the JSP program. File handling related concepts will be explained in separate chapter where we need to read the binary data stream. <html> <head> <title>Using GET and POST Method to Read Form Data</title> </head> <body> <center> <h1>Using POST Method to Read Form Data</h1> <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> Following is the content of the Hello.htm file − <html> <body> <form action = “main.jsp” method = “POST”> 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> Let us now keep main.jsp and hello.htm in <Tomcat-installationdirectory>/webapps/ROOT directory. When you access http://localhost:8080/Hello.htm, you will receive the following output. First Name: Last Name: Try to enter the First and the Last Name and then click the submit button to see the result on your local machine where tomcat is running. Based on the input provided, you will receive similar results as in the above examples. Passing Checkbox Data to JSP Program Checkboxes are used when more than one option is required to be selected. Following is an example HTML code, CheckBox.htm, for a form with two checkboxes. <html> <body> <form action = “main.jsp” method = “POST” target = “_blank”> <input type = “checkbox” name = “maths” checked = “checked” /> Maths <input type = “checkbox” name = “physics” /> Physics <input type = “checkbox” name = “chemistry” checked = “checked” /> Chemistry <input type = “submit” value = “Select Subject” /> </form> </body> </html> The above code will generate the following result − Maths Physics

JSP – Http Status Codes

JSP – Http Status Codes ”; Previous Next In this chapter, we will discuss the Http Status Codes in JSP. The format of the HTTP request and the HTTP response messages are similar and will have the following structure − An initial status line + CRLF (Carriage Return + Line Feed ie. New Line) Zero or more header lines + CRLF A blank line ie. a CRLF An optional message body like file, query data or query output. For example, a server response header looks like the following − HTTP/1.1 200 OK Content-Type: text/html Header2: … … HeaderN: … (Blank Line) <!doctype …> <html> <head>…</head> <body> … </body> </html> The status line consists of the HTTP version (HTTP/1.1 in the example), a status code (200 in the example), and a very short message corresponding to the status code (OK in the example). Following table lists out the HTTP status codes and associated messages that might be returned from the Web Server − Code Message Description 100 Continue Only a part of the request has been received by the server, but as long as it has not been rejected, the client should continue with the request 101 Switching Protocols The server switches protocol. 200 OK The request is OK 201 Created The request is complete, and a new resource is created  202 Accepted The request is accepted for processing, but the processing is not complete. 203 Non-authoritative Information 204 No Content 205 Reset Content 206 Partial Content 300 Multiple Choices A link list; the user can select a link and go to that location. Maximum five addresses. 301 Moved Permanently The requested page has moved to a new url. 302 Found The requested page has moved temporarily to a new url. 303 See Other The requested page can be found under a different url. 304 Not Modified 305 Use Proxy 306 Unused This code was used in a previous version. It is no longer used, but the code is reserved. 307 Temporary Redirect The requested page has moved temporarily to a new url. 400 Bad Request The server did not understand the request. 401 Unauthorized The requested page needs a username and a password. 402 Payment Required You can not use this code yet. 403 Forbidden Access is forbidden to the requested page 404 Not Found The server can not find the requested page. 405 Method Not Allowed The method specified in the request is not allowed. 406 Not Acceptable The server can only generate a response that is not accepted by the client. 407 Proxy Authentication Required You must authenticate with a proxy server before this request can be served. 408 Request Timeout The request took longer than the server was prepared to wait. 409 Conflict The request could not be completed because of a conflict. 410 Gone The requested page is no longer available. 411 Length Required The “Content-Length” is not defined. The server will not accept the request without it. 412 Precondition Failed The precondition given in the request evaluated to false by the server. 413 Request Entity Too Large The server will not accept the request, because the request entity is too large. 414 Request-url Too Long The server will not accept the request, because the url is too long. This occurs when you convert a “post” request to a “get” request with a long query information. 415 Unsupported Media Type The server will not accept the request, because the media type is not supported. 417 Expectation Failed 500 Internal Server Error The request was not completed. The server met an unexpected condition. 501 Not Implemented The request was not completed. The server did not support the functionality required. 502 Bad Gateway The request was not completed. The server received an invalid response from the upstream server. 503 Service Unavailable The request was not completed. The server is temporarily overloading or down. 504 Gateway Timeout The gateway has timed out. 505 HTTP Version Not Supported The server does not support the “http protocol” version. Methods to Set HTTP Status Code Following methods can be used to set the HTTP Status Code in your servlet program. These methods are available with the HttpServletResponse object. S.No. Method & Description 1 public void setStatus ( int statusCode ) This method sets an arbitrary status code. The setStatus method takes an int (the status code) as an argument. If your response includes a special status code and a document, be sure to call setStatus before actually returning any of the content with the PrintWriter. 2 public void sendRedirect(String url) This method generates a 302 response along with a Location header giving the URL of the new document. 3 public void sendError(int code, String message) This method sends a status code (usually 404) along with a short message that is automatically formatted inside an HTML document and sent to the client. HTTP Status Code Example Following example shows how a 407 error code is sent to the client browser. After this, the browser would show you “Need authentication!!!” message. <html> <head> <title>Setting HTTP Status Code</title> </head> <body> <% // Set error code and reason. response.sendError(407, “Need authentication!!!” ); %> </body> </html> You will receive the following output − HTTP Status 407 – Need authentication!!! type Status report message Need authentication!!! description The client must first authenticate itself with the proxy (Need authentication!!!). Apache Tomcat/5.5.29 To become more comfortable with HTTP status codes, try to set different status codes and their description. Print Page Previous Next Advertisements ”;

JSP – XML Data

JSP – XML Data ”; Previous Next When you send the XML data via HTTP, it makes sense to use JSP to handle incoming and outgoing XML documents; for example, RSS documents. As an XML document is merely a bunch of text, creating one through a JSP is much easier than creating an HTML document. Sending XML from a JSP You can send the XML content using JSPs the same way you send HTML. The only difference is that you must set the content type of your page to text/xml. To set the content type, use the <%@page%> tag, like this − <%@ page contentType = “text/xml” %> Following example will show how to send XML content to the browser − <%@ page contentType = “text/xml” %> <books> <book> <name>Padam History</name> <author>ZARA</author> <price>100</price> </book> </books> Access the above XML using different browsers to see the document tree presentation of the above XML. Processing XML in JSP Before you proceed with XML processing using JSP, you will need to copy the following two XML and XPath related libraries into your <Tomcat Installation Directory>lib − XercesImpl.jar − Download it from https://www.apache.org/dist/xerces/j/ xalan.jar − Download it from https://xml.apache.org/xalan-j/index.html Let us put the following content in books.xml file − <books> <book> <name>Padam History</name> <author>ZARA</author> <price>100</price> </book> <book> <name>Great Mistry</name> <author>NUHA</author> <price>2000</price> </book> </books> Try the following main.jsp, keeping in the same directory − <%@ taglib prefix = “c” uri=”http://java.sun.com/jsp/jstl/core” %> <%@ taglib prefix = “x” uri=”http://java.sun.com/jsp/jstl/xml” %> <html> <head> <title>JSTL x:parse Tags</title> </head> <body> <h3>Books Info:</h3> <c:import var = “bookInfo” url=”http://localhost:8080/books.xml”/> <x:parse xml = “${bookInfo}” var = “output”/> <b>The title of the first book is</b>: <x:out select = “$output/books/book[1]/name” /> <br> <b>The price of the second book</b>: <x:out select = “$output/books/book[2]/price” /> </body> </html> Access the above JSP using http://localhost:8080/main.jsp, the following result will be displayed − Books Info: The title of the first book is:Padam History The price of the second book: 2000 Formatting XML with JSP Consider the following XSLT stylesheet style.xsl − <?xml version = “1.0”?> <xsl:stylesheet xmlns:xsl = “http://www.w3.org/1999/XSL/Transform” version = “1.0”> <xsl:output method = “html” indent = “yes”/> <xsl:template match = “/”> <html> <body> <xsl:apply-templates/> </body> </html> </xsl:template> <xsl:template match = “books”> <table border = “1” width = “100%”> <xsl:for-each select = “book”> <tr> <td> <i><xsl:value-of select = “name”/></i> </td> <td> <xsl:value-of select = “author”/> </td> <td> <xsl:value-of select = “price”/> </td> </tr> </xsl:for-each> </table> </xsl:template> </xsl:stylesheet> Now consider the following JSP file − <%@ taglib prefix = “c” uri = “http://java.sun.com/jsp/jstl/core” %> <%@ taglib prefix = “x” uri = “http://java.sun.com/jsp/jstl/xml” %> <html> <head> <title>JSTL x:transform Tags</title> </head> <body> <h3>Books Info:</h3> <c:set var = “xmltext”> <books> <book> <name>Padam History</name> <author>ZARA</author> <price>100</price> </book> <book> <name>Great Mistry</name> <author>NUHA</author> <price>2000</price> </book> </books> </c:set> <c:import url = “http://localhost:8080/style.xsl” var = “xslt”/> <x:transform xml = “${xmltext}” xslt = “${xslt}”/> </body> </html> The following result will be displayed − Books Info: Padam History ZARA 100 Great Mistry NUHA 2000 To know more about XML processing using JSTL, you can check JSP Standard Tag Library. Print Page Previous Next Advertisements ”;