Showing posts with label JSP FAQ. Show all posts
Showing posts with label JSP FAQ. Show all posts

Wednesday, August 12, 2009

Retrieving values from HTML form input elements in JSP

To retrieve any value from an HTML Form element on a jsp page you need to use the implicit HttpServletRequest object's getParameter(String s) method. The HttpServletRequest object is available to all jsp pages and is named request. The String argument of the method getParameter(String s) is the elements name whose value you want to retrieve.

The result of this method will differ according to what type of element you are querying. For instance a checkbox element might return "on" if it has been selected, or it might return "null" if it hasn't been selected. Where a text element will return the text/value that was part of the element at the time the form was submitted. A radio button will return the value of the selected radio button in the button group. If you try and query an element that never existed in the form and therefore was never submitted to the JSP page in the HttpServletRequest object will return null.

Example HTML Form:
form name="myForm" action="result.jsp" method="post"
input type="checkbox" name="inputCheckbox"
input type="radio" value="0" name="inputRadio"
input type="radio" value="1" name="inputRadio"
input name="inputText"
input type="submit" value="Submit Query"



Example JSP page (This will only display the values recieved from the submitted form):
= request.getParameter("inputCheckbox")
= request.getParameter("inputRadio")
= request.getParameter("inputText")

How can I print the stack trace of an Exception out to my JSP page?

To print a stack trace out to your JSP page, you need to wrap the implicit object 'out' in a printWriter and pass the object to the printStackTrace method in Exception. ie:

// JSP scriptlet
try{
// An Exception is thrown
}catch(Exception e){
e.printStacktrace(new java.io.PrintWriter(out));
}

What is the difference between HttpSession mySession=request.getSession(true) and HttpSession mySession=request.getSession()

request.getSession() will return the current session and if one does not exist, a new session will be cretaed.

request.getSession(true) will return the current session if one exists, if one doesn't exits a new one will be created.

So there is actually no difference between the two methods HOWEVER, if you use request.getSession(false), it will return the current session if one exists and if one DOES NOT exist a new one will NOT be cretaed.

I want to run JSP files using the Tomcat server, where should I place my JSP files?

Under the Tomcat root directory there will be a sub-directory named web-apps, all web applications running on this Tomcat server will reside there. Each web application will have it's own sub-directory under web-apps, so you could create a directory for your web application under the web-apps directory like so /web-apps/. JSP pages can be placed insisde the directory you have created or in other sub-directories you might like to create, however please note that for each new sub-directory you place your JSP files in the URL to access them will need to include each directory.

Inside the directory you created there needs to be another directory named WEB-INF, this directory will contain the web.xml file which contains configuration information for your web application such as the welcome file for your application, all servlet mappings, filters, etc...

Under the WEB-INF directory you can create another directory named classes, all your java classes used in your web application should be placed in here, in a tree structure that resembles their packages, for example: if you have a class named MyClass whose package is com.xyz then the class should be placed in /web-apps//WEB-INF/classes/com/xyz/MyClass.class. Another alternative to handling classes in this way is to package them all in a jar file, the jar file can be placed in a directory named lib also under the WEB-INF directory, for example: say you have a jar file named myLibrary.jar, it can be placed in /web-apps//WEB-INF/lib/myLibrary.jar. By placing classes and jar files in these directories Tomcat ensures they are on the CLASSPATH when you run your application.

An alternative to repeating this procedure each time you want to deploy some JSP pages to your Tomcat server is to simply create a WAR file and use the Tomcat manager (which can be accessed through a browser window) to deploy the WAR file to the server

How can I avoid making multiple HTTP calls for content that hasn't changed? Is it possible to cache it? Is there a way to set this in the header?

This can be achieved by using a filter. You can setup the filter in your web.xml to intercept the response and edit the HTTP headers for the specified content type. An example filter could look like:

package com.xyz

import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

public class CacheFilter implements javax.servlet.Filter {
FilterConfig filterConfig = null;

public void init(FilterConfig filterConfig){
this.filterConfig = filterConfig;
}

public void doFilter(ServletRequest req,
ServletResponse res,
FilterChain chain)
throws IOException, ServletException {
String sCache = filterConfig.getInitParameter("cache");

if(sCache != null){ ((HttpServletResponse)res).setHeader("Cache-Control", sCache);

}

chain.doFilter(req, res);
}

public void destroy(){
this.filterConfig = null;
}
}


Now to set up this filter to act on all jpg requests you need to add the following to your web.xml file:


Cache
com.xyz.CacheFilter

cache
public, max-age=2592000



Cache
*.jpg



This filter will now instruct the client to store the specified content (jpg) in it's cache for 2592000 seconds from when this request was processed and no requests for this resource will be necessary till the time has elapsed.