JSP – Internationalization

JSP – Internationalization| i18n| l10n ”; Previous Next In this chapter, we will discuss the concept of Internationalization in JSP. Before we proceed, let us understand the following three important terms − Internationalization (i18n) − This means enabling a website to provide different versions of content translated into the visitor”s language or nationality. Localization (l10n) − This means adding resources to a website to adapt it to a particular geographical or cultural region for example Hindi translation to a web site. locale − This is a particular cultural or geographical region. It is usually referred to as a language symbol followed by a country symbol which are separated by an underscore. For example, “en_US” represents english locale for US. There are a number of items which should be taken care of while building up a global Website. This tutorial will not give you complete detail on this but it will give you a good example on how you can offer your Webpage in different languages to the internet community by differentiating their location, i.e., locale. A JSP can pick up appropriate version of the site based on the requester”s locale and provide appropriate site version according to the local language, culture and requirements. Following is the method of request object which returns the Locale object. java.util.Locale request.getLocale() Detecting Locale Following are the important locale methods which you can use to detect requester”s location, language and of course locale. All the below methods display the country name and language name set in the requester”s browser. S.No. Method & Description 1 String getCountry() This method returns the country/region code in upper case for this locale in ISO 3166 2-letter format. 2 String getDisplayCountry() This method returns a name for the locale”s country that is appropriate for display to the user. 3 String getLanguage() This method returns the language code in lower case for this locale in ISO 639 format. 4 String getDisplayLanguage() This method returns a name for the locale”s language that is appropriate for display to the user. 5 String getISO3Country() This method returns a three-letter abbreviation for this locale”s country. 6 String getISO3Language() This method returns a three-letter abbreviation for this locale”s language. Example The following example shows how to display a language and associated country for a request in a JSP − <%@ page import = “java.io.*,java.util.Locale” %> <%@ page import = “javax.servlet.*,javax.servlet.http.* “%> <% //Get the client”s Locale Locale locale = request.getLocale(); String language = locale.getLanguage(); String country = locale.getCountry(); %> <html> <head> <title>Detecting Locale</title> </head> <body> <center> <h1>Detecting Locale</h1> </center> <p align = “center”> <% out.println(“Language : ” + language + “<br />”); out.println(“Country : ” + country + “<br />”); %> </p> </body> </html> Languages Setting A JSP can output a page written in a Western European language such as English, Spanish, German, French, Italian, Dutch etc. Here it is important to set Content-Language header to display all the characters properly. Another important point is to display all the special characters using HTML entities; for example, “&#241;” represents “ñ”, and “&#161;” represents “¡” as follows − <%@ page import = “java.io.*,java.util.Locale” %> <%@ page import = “javax.servlet.*,javax.servlet.http.* “%> <% // Set response content type response.setContentType(“text/html”); // Set spanish language code. response.setHeader(“Content-Language”, “es”); String title = “En Español”; %> <html> <head> <title><% out.print(title); %></title> </head> <body> <center> <h1><% out.print(title); %></h1> </center> <div align = “center”> <p>En Español</p> <p>¡Hola Mundo!</p> </div> </body> </html> Locale Specific Dates You can use the java.text.DateFormat class and its static getDateTimeInstance( ) method to format date and time specific to locale. Following is the example which shows how to format dates specific to a given locale − <%@ page import = “java.io.*,java.util.Locale” %> <%@ page import = “javax.servlet.*,javax.servlet.http.* “%> <%@ page import = “java.text.DateFormat,java.util.Date” %> <% String title = “Locale Specific Dates”; //Get the client”s Locale Locale locale = request.getLocale( ); String date = DateFormat.getDateTimeInstance( DateFormat.FULL, DateFormat.SHORT, locale).format(new Date( )); %> <html> <head> <title><% out.print(title); %></title> </head> <body> <center> <h1><% out.print(title); %></h1> </center> <div align = “center”> <p>Local Date: <% out.print(date); %></p> </div> </body> </html> Locale Specific Currency You can use the java.txt.NumberFormat class and its static getCurrencyInstance( ) method to format a number, such as a long or double type, in a locale specific curreny. Following is the example which shows how to format currency specific to a given locale − <%@ page import = “java.io.*,java.util.Locale” %> <%@ page import = “javax.servlet.*,javax.servlet.http.* “%> <%@ page import = “java.text.NumberFormat,java.util.Date” %> <% String title = “Locale Specific Currency”; //Get the client”s Locale Locale locale = request.getLocale( ); NumberFormat nft = NumberFormat.getCurrencyInstance(locale); String formattedCurr = nft.format(1000000); %> <html> <head> <title><% out.print(title); %></title> </head> <body> <center> <h1><% out.print(title); %></h1> </center> <div align = “center”> <p>Formatted Currency: <% out.print(formattedCurr); %></p> </div> </body> </html> Locale Specific Percentage You can use the java.txt.NumberFormat class and its static getPercentInstance( ) method to get locale specific percentage. Following example shows how to format percentage specific to a given locale − <%@ page import = “java.io.*,java.util.Locale” %> <%@ page import = “javax.servlet.*,javax.servlet.http.* “%> <%@ page import = “java.text.NumberFormat,java.util.Date” %> <% String title = “Locale Specific Percentage”; //Get the client”s Locale Locale locale = request.getLocale( ); NumberFormat nft = NumberFormat.getPercentInstance(locale); String formattedPerc = nft.format(0.51); %> <html> <head> <title><% out.print(title); %></title> </head> <body> <center> <h1><% out.print(title); %></h1> </center> <div align = “center”> <p>Formatted Percentage: <% out.print(formattedPerc); %></p> </div> </body> </html> Print Page Previous Next Advertisements ”;

JSP – Implicit Objects

JSP – Implicit Objects ”; Previous Next In this chapter, we will discuss the Implicit Objects in JSP. These Objects are the Java objects that the JSP Container makes available to the developers in each page and the developer can call them directly without being explicitly declared. JSP Implicit Objects are also called pre-defined variables. Following table lists out the nine Implicit Objects that JSP supports − S.No. Object & Description 1 request This is the HttpServletRequest object associated with the request. 2 response This is the HttpServletResponse object associated with the response to the client. 3 out This is the PrintWriter object used to send output to the client. 4 session This is the HttpSession object associated with the request. 5 application This is the ServletContext object associated with the application context. 6 config This is the ServletConfig object associated with the page. 7 pageContext This encapsulates use of server-specific features like higher performance JspWriters. 8 page This is simply a synonym for this, and is used to call the methods defined by the translated servlet class. 9 Exception The Exception object allows the exception data to be accessed by designated JSP. The request Object The request object is an instance of a javax.servlet.http.HttpServletRequest object. Each time a client requests a page the JSP engine creates a new object to represent that request. The request object provides methods to get the HTTP header information including form data, cookies, HTTP methods etc. We can cover a complete set of methods associated with the request object in a subsequent chapter − JSP – Client Request. The response Object The response object is an instance of a javax.servlet.http.HttpServletResponse object. Just as the server creates the request object, it also creates an object to represent the response to the client. The response object also defines the interfaces that deal with creating new HTTP headers. Through this object the JSP programmer can add new cookies or date stamps, HTTP status codes, etc. We will cover a complete set of methods associated with the response object in a subsequent chapter − JSP – Server Response. The out Object The out implicit object is an instance of a javax.servlet.jsp.JspWriter object and is used to send content in a response. The initial JspWriter object is instantiated differently depending on whether the page is buffered or not. Buffering can be easily turned off by using the buffered = ”false” attribute of the page directive. The JspWriter object contains most of the same methods as the java.io.PrintWriter class. However, JspWriter has some additional methods designed to deal with buffering. Unlike the PrintWriter object, JspWriter throws IOExceptions. Following table lists out the important methods that we will use to write boolean char, int, double, object, String, etc. S.No. Method & Description 1 out.print(dataType dt) Print a data type value 2 out.println(dataType dt) Print a data type value then terminate the line with new line character. 3 out.flush() Flush the stream. The session Object The session object is an instance of javax.servlet.http.HttpSession and behaves exactly the same way that session objects behave under Java Servlets. The session object is used to track client session between client requests. We will cover the complete usage of session object in a subsequent chapter − JSP – Session Tracking. The application Object The application object is direct wrapper around the ServletContext object for the generated Servlet and in reality an instance of a javax.servlet.ServletContext object. This object is a representation of the JSP page through its entire lifecycle. This object is created when the JSP page is initialized and will be removed when the JSP page is removed by the jspDestroy() method. By adding an attribute to application, you can ensure that all JSP files that make up your web application have access to it. We will check the use of Application Object in JSP – Hits Counter chapter. The config Object The config object is an instantiation of javax.servlet.ServletConfig and is a direct wrapper around the ServletConfig object for the generated servlet. This object allows the JSP programmer access to the Servlet or JSP engine initialization parameters such as the paths or file locations etc. The following config method is the only one you might ever use, and its usage is trivial − config.getServletName(); This returns the servlet name, which is the string contained in the <servlet-name> element defined in the WEB-INFweb.xml file. The pageContext Object The pageContext object is an instance of a javax.servlet.jsp.PageContext object. The pageContext object is used to represent the entire JSP page. This object is intended as a means to access information about the page while avoiding most of the implementation details. This object stores references to the request and response objects for each request. The application, config, session, and out objects are derived by accessing attributes of this object. The pageContext object also contains information about the directives issued to the JSP page, including the buffering information, the errorPageURL, and page scope. The PageContext class defines several fields, including PAGE_SCOPE, REQUEST_SCOPE, SESSION_SCOPE, and APPLICATION_SCOPE, which identify the four scopes. It also supports more than 40 methods, about half of which are inherited from the javax.servlet.jsp.JspContext class. One of the important methods is removeAttribute. This method accepts either one or two arguments. For example, pageContext.removeAttribute (“attrName”) removes the attribute from all scopes, while the following code only removes it from the page scope − pageContext.removeAttribute(“attrName”, PAGE_SCOPE); The use of pageContext can be checked in JSP – File Uploading chapter. The page Object This object is an actual reference to the instance of the page. It can be thought of as an object that represents the entire JSP page. The page object is really a direct synonym for the this object. The exception Object The exception object is a wrapper containing the exception thrown from the previous page. It is typically used to generate an appropriate response to the error condition. We will cover the complete usage of this object in JSP – Exception Handling chapter.

JSP – Client Request

JSP – Client Request ”; Previous Next In this chapter, we will discuss Client Request in JSP. When a browser requests for a Webpage, it sends a lot of information to the web server. This information cannot be read directly because this information travels as a part of header of HTTP request. You can check HTTP Protocol for more information on this. Following table lists out the important header information which comes from the browser. This information is frequently used in web programming − S.No. Header & Description 1 Accept This header specifies the MIME types that the browser or other clients can handle. Values of image/png or image/jpeg are the two most common possibilities. 2 Accept-Charset This header specifies the character sets that the browser can use to display the information. For example, ISO-8859-1. 3 Accept-Encoding This header specifies the types of encodings that the browser knows how to handle. Values of gzip or compress are the two most common possibilities. 4 Accept-Language This header specifies the client”s preferred languages in case the servlet can produce results in more than one language. For example en, en-us, ru, etc. 5 Authorization This header is used by clients to identify themselves when accessing password-protected webpages. 6 Connection This header indicates whether the client can handle persistent HTTP connections. Persistent connections permit the client or other browser to retrieve multiple files with a single request. A value of Keep-Alive means that persistent connections should be used. 7 Content-Length This header is applicable only to POST requests and gives the size of the POST data in bytes. 8 Cookie This header returns cookies to servers that previously sent them to the browser. 9 Host This header specifies the host and port as given in the original URL. 10 If-Modified-Since This header indicates that the client wants the page only if it has been changed after the specified date. The server sends a code, 304 which means Not Modified header if no newer result is available. 11 If-Unmodified-Since This header is the reverse of If-Modified-Since; it specifies that the operation should succeed only if the document is older than the specified date. 12 Referer This header indicates the URL of the referring webpages. For example, if you are at Webpage 1 and click on a link to Webpage 2, the URL of Webpage 1 is included in the Referer header when the browser requests Webpage 2. 13 User-Agent This header identifies the browser or other client making the request and can be used to return different content to different types of browsers. The HttpServletRequest Object The request object is an instance of a javax.servlet.http.HttpServletRequest object. Each time a client requests a page, the JSP engine creates a new object to represent that request. The request object provides methods to get HTTP header information including form data, cookies, HTTP methods, etc. Following table lists out the important methods that can be used to read HTTP header in your JSP program. These methods are available with HttpServletRequest object which represents client request to webserver. S.No. Method & Description 1 Cookie[] getCookies() Returns an array containing all of the Cookie objects the client sent with this request. 2 Enumeration getAttributeNames() Returns an Enumeration containing the names of the attributes available to this request. 3 Enumeration getHeaderNames() Returns an enumeration of all the header names this request contains. 4 Enumeration getParameterNames() Returns an enumeration of String objects containing the names of the parameters contained in this request. 5 HttpSession getSession() Returns the current session associated with the this request, or if the request does not have a session, creates one. 6 HttpSession getSession(boolean create) Returns the current HttpSession associated with the this request or, if if there is no current session and create is true, returns a new session. 7 Locale getLocale() Returns the preferred Locale that the client will accept content in, based on the Accept-Language header. 8 Object getAttribute(String name) Returns the value of the named attribute as an Object, or null if no attribute of the given name exists. 9 ServletInputStream getInputStream() Retrieves the body of the request as binary data using a ServletInputStream. 10 String getAuthType() Returns the name of the authentication scheme used to protect the servlet, for example, “BASIC” or “SSL,” or null if the JSP was not protected. 11 String getCharacterEncoding() Returns the name of the character encoding used in the body of this request. 12 String getContentType() Returns the MIME type of the body of the request, or null if the type is not known. 13 String getContextPath() Returns the portion of the request URI that indicates the context of the request. 14 String getHeader(String name) Returns the value of the specified request header as a String. 15 String getMethod() Returns the name of the HTTP method with which this request was made, for example, GET, POST, or PUT. 16 String getParameter(String name) Returns the value of a request parameter as a String, or null if the parameter does not exist. 17 String getPathInfo() Returns any extra path information associated with the URL the client sent when it made this request. 18 String getProtocol() Returns the name and version of the protocol the request uses. 19 String getQueryString() Returns the query string that is contained in the request URL after the path. 20 String getRemoteAddr() Returns the Internet Protocol (IP) address of the client that sent the request. 21 String getRemoteHost() Returns the fully qualified name of the client that sent the request. 22 String getRemoteUser() Returns the login of the user making this request, if the user has been authenticated, or null if the user has not been authenticated. 23 String getRequestURI() Returns the part of this request”s URL from the protocol name up to the query string in the first line of the HTTP request. 24 String getRequestedSessionId() Returns the session ID specified by the client. 25 String getServletPath() Returns the part of this request”s URL that calls the JSP. 26 String[] getParameterValues(String name)

JSP – Page Redirect

JSP – Page Redirecting ”; Previous Next In this chapter, we will discuss page redirecting with JSP. Page redirection is generally used when a document moves to a new location and we need to send the client to this new location. This can be because of load balancing, or for simple randomization. The simplest way of redirecting a request to another page is by using sendRedirect() method of response object. Following is the signature of this method − public void response.sendRedirect(String location) throws IOException This method sends back the response to the browser along with the status code and new page location. You can also use the setStatus() and the setHeader() methods together to achieve the same redirection example − …. String site = “http://www.newpage.com” ; response.setStatus(response.SC_MOVED_TEMPORARILY); response.setHeader(“Location”, site); …. Example This example shows how a JSP performs page redirection to an another location − <%@ page import = “java.io.*,java.util.*” %> <html> <head> <title>Page Redirection</title> </head> <body> <center> <h1>Page Redirection</h1> </center> <% // New location to be redirected String site = new String(“http://www.photofuntoos.com”); response.setStatus(response.SC_MOVED_TEMPORARILY); response.setHeader(“Location”, site); %> </body> </html> Let us now put the above code in PageRedirect.jsp and call this JSP using the URL http://localhost:8080/PageRedirect.jsp. This would take you to the given URL http://www.photofuntoos.com. Print Page Previous Next Advertisements ”;

JSP – Useful Resources

JSP – Useful Resources ”; Previous Next The following resources contain additional information on JSP. Please use them to get more in-depth knowledge on this topic. Useful Video Courses Complete Java Course – Core Java, JSP & Servlets Most Popular 241 Lectures 30 hours Anand Mahajan More Detail JSP, Servlet, JSLT + Hibernate: A Complete Course 109 Lectures 11 hours Chaand Sheikh More Detail Full Stack Java Developer – Java + JSP + Restful WS + Spring Most Popular 518 Lectures 57 hours Chaand Sheikh More Detail Servlets and JSP Course For Beginners! Best Seller 42 Lectures 4.5 hours Karthikeya T More Detail JSP and Servlets – The Complete Course 43 Lectures 5.5 hours TELCOMA Global More Detail JSP and Servlets Bootcamp: Web Applications for Beginners 16 Lectures 3 hours TELCOMA Global More Detail Print Page Previous Next Advertisements ”;

JSP – Actions

JSP – Actions ”; Previous Next In this chapter, we will discuss Actions in JSP. These actions use constructs in XML syntax to control the behavior of the servlet engine. You can dynamically insert a file, reuse JavaBeans components, forward the user to another page, or generate HTML for the Java plugin. There is only one syntax for the Action element, as it conforms to the XML standard − <jsp:action_name attribute = “value” /> Action elements are basically predefined functions. The following table lists out the available JSP actions − S.No. Syntax & Purpose 1 jsp:include Includes a file at the time the page is requested. 2 jsp:useBean Finds or instantiates a JavaBean. 3 jsp:setProperty Sets the property of a JavaBean. 4 jsp:getProperty Inserts the property of a JavaBean into the output. 5 jsp:forward Forwards the requester to a new page. 6 jsp:plugin Generates browser-specific code that makes an OBJECT or EMBED tag for the Java plugin. 7 jsp:element Defines XML elements dynamically. 8 jsp:attribute Defines dynamically-defined XML element”s attribute. 9 jsp:body Defines dynamically-defined XML element”s body. 10 jsp:text Used to write template text in JSP pages and documents. Common Attributes There are two attributes that are common to all Action elements: the id attribute and the scope attribute. Id attribute The id attribute uniquely identifies the Action element, and allows the action to be referenced inside the JSP page. If the Action creates an instance of an object, the id value can be used to reference it through the implicit object PageContext. Scope attribute This attribute identifies the lifecycle of the Action element. The id attribute and the scope attribute are directly related, as the scope attribute determines the lifespan of the object associated with the id. The scope attribute has four possible values: (a) page, (b)request, (c)session, and (d) application. The <jsp:include> Action This action lets you insert files into the page being generated. The syntax looks like this − <jsp:include page = “relative URL” flush = “true” /> Unlike the include directive, which inserts the file at the time the JSP page is translated into a servlet, this action inserts the file at the time the page is requested. Following table lists out the attributes associated with the include action − S.No. Attribute & Description 1 page The relative URL of the page to be included. 2 flush The boolean attribute determines whether the included resource has its buffer flushed before it is included. Example Let us define the following two files (a)date.jsp and (b) main.jsp as follows − Following is the content of the date.jsp file − <p>Today”s date: <%= (new java.util.Date()).toLocaleString()%></p> Following is the content of the main.jsp file − <html> <head> <title>The include Action Example</title> </head> <body> <center> <h2>The include action Example</h2> <jsp:include page = “date.jsp” flush = “true” /> </center> </body> </html> Let us now keep all these files in the root directory and try to access main.jsp. You will receive the following output − The include action Example Today”s date: 12-Sep-2010 14:54:22 The <jsp:useBean> Action The useBean action is quite versatile. It first searches for an existing object utilizing the id and scope variables. If an object is not found, it then tries to create the specified object. The simplest way to load a bean is as follows − <jsp:useBean id = “name” class = “package.class” /> Once a bean class is loaded, you can use jsp:setProperty and jsp:getProperty actions to modify and retrieve the bean properties. Following table lists out the attributes associated with the useBean action − S.No. Attribute & Description 1 class Designates the full package name of the bean. 2 type Specifies the type of the variable that will refer to the object. 3 beanName Gives the name of the bean as specified by the instantiate () method of the java.beans.Beans class. Let us now discuss the jsp:setProperty and the jsp:getProperty actions before giving a valid example related to these actions. The <jsp:setProperty> Action The setProperty action sets the properties of a Bean. The Bean must have been previously defined before this action. There are two basic ways to use the setProperty action − You can use jsp:setProperty after, but outside of a jsp:useBean element, as given below − <jsp:useBean id = “myName” … /> … <jsp:setProperty name = “myName” property = “someProperty” …/> In this case, the jsp:setProperty is executed regardless of whether a new bean was instantiated or an existing bean was found. A second context in which jsp:setProperty can appear is inside the body of a jsp:useBean element, as given below − <jsp:useBean id = “myName” … > … <jsp:setProperty name = “myName” property = “someProperty” …/> </jsp:useBean> Here, the jsp:setProperty is executed only if a new object was instantiated, not if an existing one was found. Following table lists out the attributes associated with the setProperty action − S.No. Attribute & Description 1 name Designates the bean the property of which will be set. The Bean must have been previously defined. 2 property Indicates the property you want to set. A value of “*” means that all request parameters whose names match bean property names will be passed to the appropriate setter methods. 3 value The value that is to be assigned to the given property. The the parameter”s value is null, or the parameter does not exist, the setProperty action is ignored. 4 param The param attribute is the name of the request parameter whose value the property is to receive. You can”t use both value and param, but it is permissible to use neither. The <jsp:getProperty> Action The getProperty action is used to retrieve the value of a given property and converts it to a string, and finally inserts it into the output. The getProperty action has only two attributes, both of which are required. The syntax of the getProperty action is as follows − <jsp:useBean id = “myName” … /> … <jsp:getProperty name = “myName” property = “someProperty” …/> Following table lists out the required attributes associated

JSP – File Uploading

JSP – File Uploading ”; Previous Next In this chapter, we will discuss File Uploading in JSP. A JSP can be used with an HTML form tag to allow users to upload files to the server. An uploaded file can be a text file or a binary or an image file or just any document. Creating a File Upload Form Let us now understand how to create a file upload form. The following HTML code creates an uploader form. Following are the important points to be noted down − The form method attribute should be set to POST method and GET method can not be used. The form enctype attribute should be set to multipart/form-data. The form action attribute should be set to a JSP file which would handle file uploading at backend server. Following example is using uploadFile.jsp program file to upload file. To upload a single file you should use a single <input …/> tag with attribute type = “file”. To allow multiple files uploading, include more than one input tag with different values for the name attribute. The browser associates a Browse button with each of them. <html> <head> <title>File Uploading Form</title> </head> <body> <h3>File Upload:</h3> Select a file to upload: <br /> <form action = “UploadServlet” method = “post” enctype = “multipart/form-data”> <input type = “file” name = “file” size = “50” /> <br /> <input type = “submit” value = “Upload File” /> </form> </body> </html> This will display the following result. You can now select a file from the local PC and when the user clicks “Upload File”, the form gets submitted along with the selected file − File Upload − Select a file to upload − NOTE − Above form is just dummy form and would not work, you should try above code at your machine to make it work. Writing Backend JSP Script Let us now define a location where the uploaded files will be stored. You can hard code this in your program or this directory name can also be added using an external configuration such as a context-param element in web.xml as follows − <web-app> …. <context-param> <description>Location to store uploaded file</description> <param-name>file-upload</param-name> <param-value> c:apache-tomcat-5.5.29webappsdata </param-value> </context-param> …. </web-app> Following is the source code for UploadFile.jsp. This can handle uploading of multiple files at a time. Let us now consider the following before proceeding with the uploading of files. The following example depends on FileUpload; make sure you have the latest version of commons-fileupload.x.x.jar file in your classpath. You can download it from https://commons.apache.org/fileupload/. FileUpload depends on Commons IO; make sure you have the latest version of commons-io-x.x.jar file in your classpath. You can download it from https://commons.apache.org/io/. While testing the following example, you should upload a file which is of less size than maxFileSize otherwise the file will not be uploaded. Make sure you have created directories c:temp and c:apache-tomcat5.5.29webappsdata well in advance. <%@ page import = “java.io.*,java.util.*, javax.servlet.*” %> <%@ page import = “javax.servlet.http.*” %> <%@ page import = “org.apache.commons.fileupload.*” %> <%@ page import = “org.apache.commons.fileupload.disk.*” %> <%@ page import = “org.apache.commons.fileupload.servlet.*” %> <%@ page import = “org.apache.commons.io.output.*” %> <% File file ; int maxFileSize = 5000 * 1024; int maxMemSize = 5000 * 1024; ServletContext context = pageContext.getServletContext(); String filePath = context.getInitParameter(“file-upload”); // Verify the content type String contentType = request.getContentType(); if ((contentType.indexOf(“multipart/form-data”) >= 0)) { DiskFileItemFactory factory = new DiskFileItemFactory(); // maximum size that will be stored in memory factory.setSizeThreshold(maxMemSize); // Location to save data that is larger than maxMemSize. factory.setRepository(new File(“c:\temp”)); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // maximum file size to be uploaded. upload.setSizeMax( maxFileSize ); try { // Parse the request to get file items. List fileItems = upload.parseRequest(request); // Process the uploaded file items Iterator i = fileItems.iterator(); out.println(“<html>”); out.println(“<head>”); out.println(“<title>JSP File upload</title>”); out.println(“</head>”); out.println(“<body>”); while ( i.hasNext () ) { FileItem fi = (FileItem)i.next(); if ( !fi.isFormField () ) { // Get the uploaded file parameters String fieldName = fi.getFieldName(); String fileName = fi.getName(); boolean isInMemory = fi.isInMemory(); long sizeInBytes = fi.getSize(); // Write the file if( fileName.lastIndexOf(“\”) >= 0 ) { file = new File( filePath + fileName.substring( fileName.lastIndexOf(“\”))) ; } else { file = new File( filePath + fileName.substring(fileName.lastIndexOf(“\”)+1)) ; } fi.write( file ) ; out.println(“Uploaded Filename: ” + filePath + fileName + “<br>”); } } out.println(“</body>”); out.println(“</html>”); } catch(Exception ex) { System.out.println(ex); } } else { out.println(“<html>”); out.println(“<head>”); out.println(“<title>Servlet upload</title>”); out.println(“</head>”); out.println(“<body>”); out.println(“<p>No file uploaded</p>”); out.println(“</body>”); out.println(“</html>”); } %> Now try to upload files using the HTML form which you created above. When you try http://localhost:8080/UploadFile.htm, it will display the following result. This will help you upload any file from your local machine. File Upload − Select a file to upload − If your JSP script works fine, your file should be uploaded in c:apache-tomcat5.5.29webappsdata directory. Print Page Previous Next Advertisements ”;

JSP – Session Tracking

JSP – Session Tracking ”; Previous Next In this chapter, we will discuss session tracking in JSP. HTTP is a “stateless” protocol which means each time a client retrieves a Webpage, the client opens a separate connection to the Web server and the server automatically does not keep any record of previous client request. Maintaining Session Between Web Client And Server Let us now discuss a few options to maintain the session between the Web Client and the Web Server − Cookies A webserver can assign a unique session ID as a cookie to each web client and for subsequent requests from the client they can be recognized using the received cookie. This may not be an effective way as the browser at times does not support a cookie. It is not recommended to use this procedure to maintain the sessions. Hidden Form Fields A web server can send a hidden HTML form field along with a unique session ID as follows − <input type = “hidden” name = “sessionid” value = “12345”> This entry means that, when the form is submitted, the specified name and value are automatically included in the GET or the POST data. Each time the web browser sends the request back, the session_id value can be used to keep the track of different web browsers. This can be an effective way of keeping track of the session but clicking on a regular (<A HREF…>) hypertext link does not result in a form submission, so hidden form fields also cannot support general session tracking. URL Rewriting You can append some extra data at the end of each URL. This data identifies the session; the server can associate that session identifier with the data it has stored about that session. For example, with http://tutorialspoint.com/file.htm;sessionid=12345, the session identifier is attached as sessionid = 12345 which can be accessed at the web server to identify the client. URL rewriting is a better way to maintain sessions and works for the browsers when they don”t support cookies. The drawback here is that you will have to generate every URL dynamically to assign a session ID though page is a simple static HTML page. The session Object Apart from the above mentioned options, JSP makes use of the servlet provided HttpSession Interface. This interface provides a way to identify a user across. a one page request or visit to a website or store information about that user By default, JSPs have session tracking enabled and a new HttpSession object is instantiated for each new client automatically. Disabling session tracking requires explicitly turning it off by setting the page directive session attribute to false as follows − <%@ page session = “false” %> The JSP engine exposes the HttpSession object to the JSP author through the implicit session object. Since session object is already provided to the JSP programmer, the programmer can immediately begin storing and retrieving data from the object without any initialization or getSession(). Here is a summary of important methods available through the session object − S.No. Method & Description 1 public Object getAttribute(String name) This method returns the object bound with the specified name in this session, or null if no object is bound under the name. 2 public Enumeration getAttributeNames() This method returns an Enumeration of String objects containing the names of all the objects bound to this session. 3 public long getCreationTime() This method returns the time when this session was created, measured in milliseconds since midnight January 1, 1970 GMT. 4 public String getId() This method returns a string containing the unique identifier assigned to this session. 5 public long getLastAccessedTime() This method returns the last time the client sent a request associated with the this session, as the number of milliseconds since midnight January 1, 1970 GMT. 6 public int getMaxInactiveInterval() This method returns the maximum time interval, in seconds, that the servlet container will keep this session open between client accesses. 7 public void invalidate() This method invalidates this session and unbinds any objects bound to it. 8 public boolean isNew() This method returns true if the client does not yet know about the session or if the client chooses not to join the session. 9 public void removeAttribute(String name) This method removes the object bound with the specified name from this session. 10 public void setAttribute(String name, Object value) This method binds an object to this session, using the name specified. 11 public void setMaxInactiveInterval(int interval) This method specifies the time, in seconds, between client requests before the servlet container will invalidate this session. Session Tracking Example This example describes how to use the HttpSession object to find out the creation time and the last-accessed time for a session. We would associate a new session with the request if one does not already exist. <%@ page import = “java.io.*,java.util.*” %> <% // Get session creation time. Date createTime = new Date(session.getCreationTime()); // Get last access time of this Webpage. Date lastAccessTime = new Date(session.getLastAccessedTime()); String title = “Welcome Back to my website”; Integer visitCount = new Integer(0); String visitCountKey = new String(“visitCount”); String userIDKey = new String(“userID”); String userID = new String(“ABCD”); // Check if this is new comer on your Webpage. if (session.isNew() ){ title = “Welcome to my website”; session.setAttribute(userIDKey, userID); session.setAttribute(visitCountKey, visitCount); } visitCount = (Integer)session.getAttribute(visitCountKey); visitCount = visitCount + 1; userID = (String)session.getAttribute(userIDKey); session.setAttribute(visitCountKey, visitCount); %> <html> <head> <title>Session Tracking</title> </head> <body> <center> <h1>Session Tracking</h1> </center> <table border = “1” align = “center”> <tr bgcolor = “#949494”> <th>Session info</th> <th>Value</th> </tr> <tr> <td>id</td> <td><% out.print( session.getId()); %></td> </tr> <tr> <td>Creation Time</td> <td><% out.print(createTime); %></td> </tr> <tr> <td>Time of Last Access</td> <td><% out.print(lastAccessTime); %></td> </tr> <tr> <td>User ID</td> <td><% out.print(userID); %></td> </tr> <tr> <td>Number of visits</td> <td><% out.print(visitCount); %></td> </tr> </table> </body> </html> Now put the above code in main.jsp and try to access http://localhost:8080/main.jsp. Once you run the URL, you will receive the following result − Welcome to my website Session Information Session info

JSP – Directives

JSP – Directives ”; Previous Next In this chapter, we will discuss Directives in JSP. These directives provide directions and instructions to the container, telling it how to handle certain aspects of the JSP processing. A JSP directive affects the overall structure of the servlet class. It usually has the following form − <%@ directive attribute = “value” %> Directives can have a number of attributes which you can list down as key-value pairs and separated by commas. The blanks between the @ symbol and the directive name, and between the last attribute and the closing %>, are optional. There are three types of directive tag − S.No. Directive & Description 1 <%@ page … %> Defines page-dependent attributes, such as scripting language, error page, and buffering requirements. 2 <%@ include … %> Includes a file during the translation phase. 3 <%@ taglib … %> Declares a tag library, containing custom actions, used in the page JSP – The page Directive The page directive is used to provide instructions to the container. These instructions pertain to the current JSP page. You may code page directives anywhere in your JSP page. By convention, page directives are coded at the top of the JSP page. Following is the basic syntax of the page directive − <%@ page attribute = “value” %> You can write the XML equivalent of the above syntax as follows − <jsp:directive.page attribute = “value” /> Attributes Following table lists out the attributes associated with the page directive − S.No. Attribute & Purpose 1 buffer Specifies a buffering model for the output stream. 2 autoFlush Controls the behavior of the servlet output buffer. 3 contentType Defines the character encoding scheme. 4 errorPage Defines the URL of another JSP that reports on Java unchecked runtime exceptions. 5 isErrorPage Indicates if this JSP page is a URL specified by another JSP page”s errorPage attribute. 6 extends Specifies a superclass that the generated servlet must extend. 7 import Specifies a list of packages or classes for use in the JSP as the Java import statement does for Java classes. 8 info Defines a string that can be accessed with the servlet”s getServletInfo() method. 9 isThreadSafe Defines the threading model for the generated servlet. 10 language Defines the programming language used in the JSP page. 11 session Specifies whether or not the JSP page participates in HTTP sessions 12 isELIgnored Specifies whether or not the EL expression within the JSP page will be ignored. 13 isScriptingEnabled Determines if the scripting elements are allowed for use. Check for more details related to all the above attributes at Page Directive. The include Directive The include directive is used to include a file during the translation phase. This directive tells the container to merge the content of other external files with the current JSP during the translation phase. You may code the include directives anywhere in your JSP page. The general usage form of this directive is as follows − <%@ include file = “relative url” > The filename in the include directive is actually a relative URL. If you just specify a filename with no associated path, the JSP compiler assumes that the file is in the same directory as your JSP. You can write the XML equivalent of the above syntax as follows − <jsp:directive.include file = “relative url” /> For more details related to include directive, check the Include Directive. The taglib Directive The JavaServer Pages API allow you to define custom JSP tags that look like HTML or XML tags and a tag library is a set of user-defined tags that implement custom behavior. The taglib directive declares that your JSP page uses a set of custom tags, identifies the location of the library, and provides means for identifying the custom tags in your JSP page. The taglib directive follows the syntax given below − <%@ taglib uri=”uri” prefix = “prefixOfTag” > Here, the uri attribute value resolves to a location the container understands and the prefix attribute informs a container what bits of markup are custom actions. You can write the XML equivalent of the above syntax as follows − <jsp:directive.taglib uri = “uri” prefix = “prefixOfTag” /> For more details related to the taglib directive, check the Taglib Directive. Print Page Previous Next Advertisements ”;

JSP – Server Response

JSP – Server Response ”; Previous Next In this chapter, we will discuss the Server Response in JSP. When a Web server responds to a HTTP request, the response typically consists of a status line, some response headers, a blank line, and the document. A typical response looks like this − 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 is a summary of the most useful HTTP 1.1 response headers which go back to the browser from the web server. These headers are frequently used in web programming − S.No. Header & Description 1 Allow This header specifies the request methods (GET, POST, etc.) that the server supports. 2 Cache-Control This header specifies the circumstances in which the response document can safely be cached. It can have values public, private or no-cache etc. Public means document is cacheable, Private means document is for a single user and can only be stored in private (nonshared) caches and no-cache means document should never be cached. 3 Connection This header instructs the browser whether to use persistent HTTP connections or not. A value of close instructs the browser not to use persistent HTTP connections and keep-alive means using persistent connections. 4 Content-Disposition This header lets you request that the browser ask the user to save the response to disk in a file of the given name. 5 Content-Encoding This header specifies the way in which the page was encoded during transmission. 6 Content-Language This header signifies the language in which the document is written. For example, en, en-us, ru, etc. 7 Content-Length This header indicates the number of bytes in the response. This information is needed only if the browser is using a persistent (keep-alive) HTTP connection. 8 Content-Type This header gives the MIME (Multipurpose Internet Mail Extension) type of the response document. 9 Expires This header specifies the time at which the content should be considered out-of-date and thus no longer be cached. 10 Last-Modified This header indicates when the document was last changed. The client can then cache the document and supply a date by an If-Modified-Since request header in later requests. 11 Location This header should be included with all responses that have a status code in the 300s. This notifies the browser of the document address. The browser automatically reconnects to this location and retrieves the new document. 12 Refresh This header specifies how soon the browser should ask for an updated page. You can specify time in number of seconds after which a page would be refreshed. 13 Retry-After This header can be used in conjunction with a 503 (Service Unavailable) response to tell the client how soon it can repeat its request. 14 Set-Cookie This header specifies a cookie associated with the page. The HttpServletResponse Object The response object is an instance of a javax.servlet.http.HttpServletResponse object. Just as the server creates the request object, it also creates an object to represent the response to the client. The response object also defines the interfaces that deal with creating new HTTP headers. Through this object, the JSP programmer can add new cookies or date stamps, HTTP status codes etc. The following methods can be used to set HTTP response header in your servlet program. These methods are available with the HttpServletResponse object. This object represents the server response. S.No. Method & Description 1 String encodeRedirectURL(String url) Encodes the specified URL for use in the sendRedirect method or, if encoding is not needed, returns the URL unchanged. 2 String encodeURL(String url) Encodes the specified URL by including the session ID in it, or, if encoding is not needed, returns the URL unchanged. 3 boolean containsHeader(String name) Returns a boolean indicating whether the named response header has already been set. 4 boolean isCommitted() Returns a boolean indicating if the response has been committed. 5 void addCookie(Cookie cookie) Adds the specified cookie to the response. 6 void addDateHeader(String name, long date) Adds a response header with the given name and date-value. 7 void addHeader(String name, String value) Adds a response header with the given name and value. 8 void addIntHeader(String name, int value) Adds a response header with the given name and integer value. 9 void flushBuffer() Forces any content in the buffer to be written to the client. 10 void reset() Clears any data that exists in the buffer as well as the status code and headers. 11 void resetBuffer() Clears the content of the underlying buffer in the response without clearing headers or status code. 12 void sendError(int sc) Sends an error response to the client using the specified status code and clearing the buffer. 13 void sendError(int sc, String msg) Sends an error response to the client using the specified status. 14 void sendRedirect(String location) Sends a temporary redirect response to the client using the specified redirect location URL. 15 void setBufferSize(int size) Sets the preferred buffer size for the body of the response. 16 void setCharacterEncoding(String charset) Sets the character encoding (MIME charset) of the response being sent to the client, for example, to UTF-8. 17 void setContentLength(int len) Sets the length of the content body in the response In HTTP servlets; this method also sets the HTTP Content-Length header. 18 void setContentType(String type) Sets the content type of the response being sent to the client, if the response has not been committed yet. 19 void setDateHeader(String name, long date) Sets a response header with the given name and date-value. 20 void setHeader(String name, String value) Sets a response header with the given name and value. 21 void setIntHeader(String name, int value) Sets a response header with the given name and integer value. 22 void setLocale(Locale loc) Sets the locale of the response, if the response has not