Showing posts with label Servlets. Show all posts
Showing posts with label Servlets. Show all posts

What to use When ? Forward / Redirect in JSP

A Controller servlet may perform either a forward or a redirect operation at the end of processing a request. It is important to understand the difference between these two cases, in particular with respect to browser reloads of web pages.
Forward
  • a forward is performed internally by the servlet
  • the browser is completely unaware that it has taken place, so its original URL remains intact
  • any browser reload of the resulting page will simple repeat the original request, with the original URL
Redirect
  • a redirect is a two step process, where the web application instructs the browser to fetch a second URL, which differs from the original
  • a browser reload of the second URL will not repeat the original request, but will rather fetch the second URL
  • redirect is marginally slower than a forward, since it requires two browser requests, not one
  • objects placed in the original request scope are not available to the second request
In general, a forward should be used if the operation can be safely repeated upon a browser reload of the resulting web page; otherwise, redirect must be used. Typically, if the operation performs an edit on the datastore, then a redirect, not a forward, is required. This is simply to avoid the possibility of inadvertently duplicating an edit to the database.
More explicitly :
  • for SELECT operations, use a forward
  • for INSERT, UPDATE, or DELETE operations, use a redirect
In HTML, a
tag can either
GET or POST its data. In this context, a GET corresponds to a SELECT-then-forward, and a POST corresponds to an edit-then-redirect.
It is strongly recommended that forms for the input of search criteria should use GET, while forms for editing database records should use POST.



Example
This example is after the style of the WEB4J Controller class. The important methods of the Servlet API are :

import java.io.IOException;
import javax.servlet.*;
import javax.servlet.http.*;
import hirondelle.web4j.action.Action;
import hirondelle.web4j.action.ResponsePage;
import hirondelle.web4j.request.RequestParser;
import hirondelle.web4j.model.BadRequestException;

public class RedirectForward extends HttpServlet {
  
  //..many items elided
  @Override public final void doGet(
      HttpServletRequest aRequest, HttpServletResponse aResponse
   ) throws ServletException, IOException {
    processRequest(aRequest, aResponse);
  }

  @Override public final void doPost(
      HttpServletRequest aRequest, HttpServletResponse aResponse
   ) throws ServletException, IOException {
    processRequest(aRequest, aResponse);
  }

  /**
  * Handle all HTTP GET and POST requests.
  */
  protected void processRequest(
    HttpServletRequest aRequest, HttpServletResponse aResponse
  ) throws ServletException, IOException {
    RequestParser requestParser = RequestParser.getInstance(aRequest, aResponse);
    try {
      Action action = requestParser.getWebAction();
      ResponsePage responsePage = action.execute();
      if ( responsePage.getIsRedirect() ) {
        redirect(responsePage, aResponse);
      }
      else {
        forward(responsePage, aRequest, aResponse);
      }
    }
    catch (BadRequestException ex){
      //..elided      //use Response.sendError()    }
    catch (Throwable ex) {
      //..elided      //use Response.sendError()    }
  }
  
  // PRIVATE //  
  private void redirect(
    ResponsePage aDestinationPage, HttpServletResponse aResponse
  ) throws IOException {
    String urlWithSessionID = aResponse.encodeRedirectURL(aDestinationPage.toString());
    aResponse.sendRedirect( urlWithSessionID );
  }

  private void forward(
    ResponsePage aResponsePage, HttpServletRequest aRequest, HttpServletResponse aResponse
  ) throws ServletException, IOException {
    RequestDispatcher dispatcher = aRequest.getRequestDispatcher(aResponsePage.toString());
    dispatcher.forward(aRequest, aResponse);
  }
} 
Click here to View more...

Http Session and PortletSession

When the user initially accesses a portlet, a PortletSession is created. The portlet
session stores transient data associated with an individual use of the portlet.

The PortletSession object extends from HttpSession and serves much the same
purpose. The PortletSession is intended to represent an ongoing conversation between the client and the portlet. To this end, the PortletSession can be used to store information needed between requests. The PortletSession is intended to store data between requests, not between portlets. As such, data stored in the session by one portlet is not accessible by another. The PortletSession is retrieved from the request object.


Well both Portlets and Servlets are loaded using the same classloader.So it's a plain fact that session can be made available in both the contexts.

As far as the portlets are concerned,
The PortletSession is namespaced :
1) PORTLET_SCOPE : Only available to the particular portlet.
2) APPLICATION_SCOPE: Available to all Portlets and also available in Servlets/JSP etc

So, if you really want to share sessions among Servlets and Portlets...
1) Define the scope of the session attributes as APPLICATION_SCOPE in Portlets....
2) Access the session attributes defined or set in servlets by specifying APPLICATION_SCOPE.. else you will get null.

As far as retrieving the PortletSession from HttpRequest is concerned.. You can get them via the APIs available..
For JSR168 Struts Portlets we have WpsStrutsUtil package that will return you the PortletSession...


Click here to View more...

Session management in servlets

Procedure

  1. Get the HttpSession object.

    To obtain a session, use the getSession() method of the javax.servlet.http.HttpServletRequest object in the Java Servlet 2.3 API.

    When you first obtain the HttpSession object, the Session Management facility uses one of three ways to establish tracking of the session: cookies, URL rewriting, or Secure Sockets Layer (SSL) information.

    Assume the Session Management facility uses cookies. In such a case, the Session Management facility creates a unique session ID and typically sends it back to the browser as a cookie. Each subsequent request from this user (at the same browser) passes the cookie containing the session ID, and the Session Management facility uses this ID to find the user's existing HttpSession object.

    In Step 1 of the code sample, the Boolean(create) is set to true so that the HttpSession object is created if it does not already exist. (With the Servlet 2.3 API, the javax.servlet.http.HttpServletRequest.getSession() method with no boolean defaults to true and creates a session if one does not already exist for this user.)

  2. Store and retrieve user-defined data in the session.

    After a session is established, you can add and retrieve user-defined data to the session. The HttpSession object has methods similar to those in java.util.Dictionary for adding, retrieving, and removing arbitrary Java objects.

    In Step 2 of the code sample, the servlet reads an integer object from the HttpSession, increments it, and writes it back. You can use any name to identify values in the HttpSession object. The code sample uses the name sessiontest.counter.

    Because the HttpSession object is shared among servlets that the user might access, consider adopting a site-wide naming convention to avoid conflicts.

  3. (Optional) Output an HTML response page containing data from the HttpSession object.
  4. Provide feedback to the user that an action has taken place during the session. You may want to pass HTML code to the client browser indicating that an action has occurred. For example, in step 3 of the code sample, the servlet generates a Web page that is returned to the user and displays the value of the sessiontest.counter each time the user visits that Web page during the session.
  5. (Optional) Notify Listeners. Objects stored in a session that implement the javax.servlet.http.HttpSessionBindingListener interface are notified when the session is preparing to end and become invalidated. This notice enables you to perform post-session processing, including permanently saving the data changes made during the session to a database.
  6. End the session. You can end a session:
    • Automatically with the Session Management facility if a session is inactive for a specified time. The administrators provide a way to specify the amount of time after which to invalidate a session.
    • By coding the servlet to call the invalidate() method on the session object.





import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;


public class SessionSample extends HttpServlet {
public void doGet (HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {


// Step 1: Get the Session object

boolean create = true;
HttpSession session = request.getSession(create);

// Step 2: Get the session data value


Integer ival = (Integer)
session.getAttribute ("sessiontest.counter");
if (ival == null) ival = new Integer (1);
else ival = new Integer (ival.intValue () + 1);
session.setAttribute ("sessiontest.counter", ival);

// Step 3: Output the page

response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head><title>Session Tracking Test</title></head>");
out.println("<body>");
out.println("<h1>Session Tracking Test</h1>");
out.println ("You have hit this page " + ival + " times" + "<br>");
out.println ("Your " + request.getHeader("Cookie"));
out.println("</body></html>");
}
}


Click here to View more...

request.getParameter() and request.getAttribute()

Ok, getParameter() first:

Code:

<html>

<body>
<form name="testForm" method="post" action="testJSP.jsp">
<input type="text" name="testParam" value="Hello Amit">

<input type="submit">
</form>
</body>

</html>

-------------------------------------------------------------------------------------
Ok so when you click the submit button on this HTML page the form will be posted to testJSP.jsp

<!-- Code for testJSP.jsp -->
<%
String sValue = request.getParameter("testParam");
%>
<html>

<body>
<%= sValue %>
</body>

</html>

------------------------------------------------------------------------------------------

request.getParameter("testParam") will get the value from the posted form (named testForm) of the input box named testParam which is "Hello Vaibhav". It will then print it out, so you should see "Hello Vaibhav" on the screen. So request.getParameter() will retrieve a value that the client has submitted. You will get the value on the server side.

----------------------------------------------------------------------------------------------
Now for request.getAttribute(), this is all done server side. YOU add the attribute to the request and YOU submit the request to another resource, the client does not know about this. So all the code handling this would typically be in servlets.


// Your servlet code

public class SomeServlet extends HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}


protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}

protected void processRequest(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {

RequestDispatcher rd = request
.getRequestDispatcher("http://www.website.com/yourResource");

Object object = new Object();

request.setAttribute("ObjectName", object);
rd.forward(request, response);
}

Now when you call rd.forward() the request will be forwarded to the resource specified ie: in this case "http://www.website.com/yourResource"

Now in this case yourResource is a Servlet, here is the code

public class YourResourceServlet extends HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {

processRequest(request, response);
}


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

processRequest(request, response);
}


protected void processRequest(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {

// Retrieve the object stored in the request.

Object myDispatchedObject =
request.getAttribute("ObjectName");

}
}
}

main


Click here to View more...

Best Site for Servlet

Click Here to Open the site Click here to View more...

Inter-Servlet Communication (API v2.1 above)

This section shows how to

  • call another Servlet (or any other kind of active resource) to process a request

A Servlet can make a request to an active resource on the web server just like a client can (by requesting a URL). The Servlet API supports a more direct way of accessing server resources from within a Servlet which is running in the server than opening a socket connection back to the server. A Servlet can either hand off a request to a different resource or include the response which is created by that resource in its own response. It is also possible to supply user-defined data when calling an active resource which provides for an elegant way of doing inter-Servlet communication.



Example.

We're building an online shop with an ItemServlet which takes an argument item=number and returns a paragraph of HTML text with a description of the item which is retrieved from a database.

A second Servlet, the PresentationServlet, takes the same argument and creates a complete HTML page which includes the output of the ItemServlet. If the item argument is missing, the request is delegated to an ErrorServlet which returns a formatted error message.

public class PresentationServlet extends HttpServlet
{
private static class ItemNotFoundException extends Exception
{
ItemNotFoundException() { super("Item not found"); }
}

protected void doGet(HttpServletRequest req,
HttpServletResponse res)
throws ServletException, IOException
{
String item = req.getParameter("item");
if(item == null)
{
req.setAttibute("exception", new ItemNotFoundException());
getServletContext()
.getRequestDispatcher("/servlet/ErrorServlet")
.forward(req, res);
}
else
{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.print("<HTML><HEAD><TITLE>Item " + item + "</TITLE>"+
"</HEAD><BODY>Item " + item + ":<P>");
getServletContext()
.getRequestDispatcher("/servlet/ItemServlet?item="+item)
.include(req, res);
out.print("</BODY></HTML>");
}
}
}


In the doGet method we first check for the existence of the item argument. If it is present (second branch of the if statement) the Servlet is responding with an HTML document in the usual way. In the middle of the document the response body of the ItemServlet is included by asking the ItemServlet's RequestDispatcher (whis is obtained through the ServletContext) to perform that operation.

If no item attribute was specified, the request is delegated to the ErrorServlet in a similar way. Note that this time we are using the RequestDispatcher's forward method (instead of include). This method can be called only once and only if neither getOutputStream nor getWriter has been called, but it allows the included Servlet to set headers and the response code (which is required to create a proper HTTP error response message).

The ItemServlet gets its item argument from the query string. That way it can also be accessed directly via an HTTP request, but argument values have to be represented as url-encoded strings (which is no problem in this case). The ErrorServlet takes an exception argument of type java.lang.Exception which is provided as a request attribute. The ErrorServlet uses the ServletRequest method getAttribute to read the attribute.

Note that a server which supports load balancing could run the Servlets on different JVMs. All custom request attributes should be serializable to allow them to be moved from one JVM to another.

3.3 Accessing Passive Server Resources [API 2.1]

This section shows how to

  • access a resource in the server's document tree

Passive server resources (e.g. static HTML pages which are stored in local files) are not accessed with RequestDispatcher objects. The ServletContext method getResource(String path) returns a URL object for a resource specified by a local URI (e.g. "/" for the server's document root) which can be used to examine the resource.

If you only want to read the resource's body you can directly ask the ServletContext for an InputStream with the getResourceAsStream(String path) method.

In Servlets which have to use version 1.0 or 2.0 of the Servlet API you can use the ServletContext method getRealPath(String path) to find a path in the local file system to a resource. This method is less general than the one described above because it doesn't allow you to access resources which are not stored in local files.

Accessing Servlet Resources

This section shows how to

  • access resources which belong to a Servlet

A Servlet may need to access additional resources like configuration files whose locations should not need to be specified in init parameters. Those resources can be accessed with the methods getResource(String name) and getResourceAsStream(String name) of the java.lang.Class object which represents the Servlet's class.

Example. The following code gets an InputStream for a configuration file named myservlet.cfg which resides in the same directory as the class in which the code is executed:

InputStream confIn =
getClass().getResourceAsStream("myservlet.cfg");

Note that the Servlet engine's Servlet class loader must implement the getResource and getResourceAsStream methods in order for this to work. This may not be the case with all Servlet engines.

Sharing Data Between Servlets [API 2.1]

This section shows how to

  • share data between Servlets

Version 2.1 of the Servlet API offers a new way of sharing named objects between all the Servlets in a Servlet context (and also other contexts, as you'll see below) by binding the objects to the ServletContext object which is shared by several Servlets.

The ServletContext class has several methods for accessing the shared objects:

  • public void setAttribute(String name, Object object) adds a new object or replaces an old object by the specified name. The attribute name should follow the same naming convention as a package name (e.g. a Servlet com.foo.fooservlet.FooServlet could have an attribute com.foo.fooservlet.bar).

    Just like a custom ServletRequest attribute, an object which is stored as a ServletContext attribute should also be serializable to allow attributes to be shared by Servlets which are running in different JVMs on different machines in a load-balancing server environment.

  • public Object getAttribute(String name) returns the named object or null if the attribute does not exist.

    In addition to the user-defined attributes there may also be predefined attributes which are specific to the Servlet engine and provide additional information about a Servlet(Context)'s environment.

  • public Enumeration getAttributeNames() returns an Enumeration of the names of all available attributes.

  • public void removeAttribute(String name) removes the attribute with the specified name if it exists.

The separation of Servlets into Servlet contexts depends on the Servlet engine. The ServletContext object of a Servlet with a known local URI can be retrieved with the method public ServletContext getContext(String uripath) of the Servlet's own ServletContext. This method returns null if there is no Servlet for the specified path or if this Servlet is not allowed to get the ServletContext for the specified path due to security restrictions.


Click here to View more...

Inter-Servlet Communication (v1.0 and 2.0 only)

This section shows how to

  • call a method of another Servlet

The inter-Servlet communication method which is described in this section can only be used with Servlet engines which implement version 1.0 or 2.0 of the Servlet API. It will not work with Servlet engines which comply strictly to version 2.1. The new way of doing inter-Servlet communication which was introduced in the 2.1 API is not done by the following method


Servlets are not alone in a Web Server. They have access to other Servlets in the same Servlet Context (usually a Servlet directory), represented by an instance of javax.servlet.ServletContext. The ServletContext is available through the ServletConfig object's getServletContext method.

A Servlet can get a list of all other Servlets in the Servlet Context by calling getServletNames on the ServletContext object. A Servlet for a known name (probably obtained through getServletNames) is returned by getServlet. Note that this method can throw a ServletException because it may need to load and initialize the requested Servlet if this was not already done.

After obtaining the reference to another Servlet that Servlet's methods can be called. Methods which are not declared in javax.servlet.Servlet but in a subclass thereof can be called by casting the returned object to the required class type.

Note that in Java the identity of a class is not only defined by the class name but also by the ClassLoader by which it was loaded. Web servers usually load each Servlet with a different class loader. This is necessary to reload Servlets on the fly because single classes cannot be replaced in the running JVM. Only a ClassLoader object with all loaded classes can be replaced.

This means that classes which are loaded by a Servlet class loader cannot be used for inter-Servlet communication. A class literal FooServlet (as used in a type cast like "FooServlet foo = (FooServlet)context.getServlet("FooServlet")") which is used in class BarServlet is different from the class literal FooServlet as used in FooServlet itself.

A way to overcome this problem is using a superclass or an interface which is loaded by the system loader and thus shared by all Servlets. In a Web Server which is written in Java those classes are usually located in the class path (as defined by the CLASSPATH environment variable).

Example. Servlet FooServlet wants to call the method public void bar() of Servlet BarServlet. Both Servlets should be reloadable so the Servlet classes cannot be loaded by the system loader. Instead we define an interface BarInterface which defines the callable method and is loaded by the system loader. BarServlet implements this interface. The Servlets are placed into the Servlet directory and the interface into a directory in the class path.

 1:  public class FooServlet extends HttpServlet
2: {
3: protected void doGet(HttpServletRequest req,
4: HttpServletResponse res)
5: throws ServletException, IOException
6: {
7: ...
8: ServletContext context = getServletConfig().getServletContext();
9: BarInterface bar = (BarInterface)context.getServlet("BarServlet");
10: bar.bar();
11: ..
12: }
13:
14: ...
15: }

 1:  public interface BarInterface
2: {
3: public void bar();
4: }

 1:  public class BarServlet extends HttpServlet implements BarInterface
2: {
3: public void bar()
4: {
5: System.err.println(""bar() called"");
6: }
7:
8: ...
9: }



Click here to View more...

General Tutorials, Java technologies

Java security in web applicationThis article gives an overview about different attack mechanisms against Java web applications and J2EE applications. It introduces available security concepts in Java like JAAS and Sandbox security. Furthermore, security related design patterns.
Date: 06-03-07
Log4j tutorial with Tomcat examplesThis tutorial explains how to set up log4j with email, files and stdout. It compares XML to properties configuration files, shows how to change LogLevels for a running application. Furthermore, we explain best practices on logging and exception handling.
Date: 06-03-07
Tips and tricks for eclipse and the plugin MyEclipseIn this Tutorial we present tips and trick for the development enviroment eclipse and the extension MyEclipse.
Date: 28-08-06
Java EncyclopaediaFirst pages of an encyclopaedia including javas common abbreviations and technolgies. We try to explain short and easily to understand the terms of the java world.
Date: 28-08-06
MyEclipse CSS editorThis paper describes the new and improved editors of MyEclipse for CSS files.
Date: 29-08-06
MyEclipse JavaScript editorThis paper describes the new and improved editors of MyEclipse for JavaScript and CSS files.
Date: 29-08-06

Struts, JSP and Servlets Tutorials

JavaServer Faces Tutorials

First Java Server Faces TutorialThis tutorial facilitates the first steps with the quite new framework JavaServer Faces (JSF). Step by step an example application (a library) will be created, which illustrate the different elements of the framework.
Date: 28-08-06
JavaServer Faces Navigation Tutorial (?)This tutorial explain the navigation handling in JSF and shows the usage with an small example application. We will show multiple and complex examples for navigation rules. For examples navigation outcomes depending on application logic, actions, static n
Date: 29-08-06
JavaServer Faces - Converter TutorialThis tutorial explains the usage of converters in JSF. It shows how you can use standard converters step by step using an example application.
Date: 29-08-06
JavaServer Faces - Validation & Error Handling (€)This tutorial explains the validation and the error handling in JSF and shows a step by step example application. The tutorials shows the standard validators but also the creation of custom validators.
Date: 12-01-08
JavaServer Faces - Developing custom converters (€)This tutorial explains how to develop your own converters. It shows the usage of own custom converter tags and overriding standard converter of basic types.
Date: 12-01-08
JavaServer Faces - Message ResourcesThis tutorial explains the internationalization of a web application using JSF message resource bundle.
Date: 12-01-08

Debugging, Testing and Tuning Tutorials

Debugging from JSP and Java ApplicationsThis tutorial gives you an overview of how to use the debugging feature of eclipse to debug your web or Java projects.
Date: 28-08-06
Eclipse Junit testing tutorialThis tutorial gives you an overview of the features of JUnit and shows a little example how you can write tests for your Java application using eclipse.
Date: 29-08-06
Junit Testing with Struts (StrutsTestCases extension)This tutorial gives you an overview about the StrutsTestCases extension of JUnit and example how you can use it to test your Struts application.
Date: 29-08-06
Junit Testing Enterprise Java Beans (EJB) (?)This tutorial will demonstrate how to use Junit to unit test Enterprise JavaBeans.
Date: 29-08-06


Database Development, EJB and Hibernate Tutorials


Jboss Tutorials

Jboss as windows serviceInstallation of Jboss as windows service on windows 2000 and windows XP
Date: 28-08-06
Click here to View more...