Home » Archive

Articles tagged with: javabout.com

Java Codes »

[13 Feb 2009 | No Comment | 256 views]

This J2EE program demonstrates a method of handling status code errors in web.xml (Tested in weblogic 7.0). This is important since normal users are not familier with statuscode it. Therefore, the servlet can use the status codes to indicate the status of the response. This method does not trigger the container to generate an error page. It just sends the status code to the browser.
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class ServletExceptionHandling extends HttpServlet {
  public void doGet(HttpServletRequest request, 
      HttpServletResponse response) 
      throws ServletException , IOException {
    response.setContentType(“text/plain”);
    
    PrintWriter out = response.getWriter();
    int a = request.getContentLength();
    // The default content Length is -1
    if(a==-1) {
      response.sendError(response.SC_LENGTH_REQUIRED,
         “Content Length Required”);
    }
  }
}
Here is the web.xml for the servlet developer can specify this code anywhere in where in web.xml but should be outside servlet & servlet-mapping tags.
<error-page>
<error-code> 411 …

Java Codes »

[12 Feb 2009 | One Comment | 2,502 views]
Java Servlet – How to get/set values from servlet page to session object

Applications like UserManagement, Shopping Cart etc require to store values in cache so that when a user returns his information is restored from cache.
There are three ways to implement sessions in Java Servlets:
* Cookies: HTTP Cookies to store information. Methods response.addCookie(cookie) will add cookie and request.getCookies() will return value of cookies.
* URL Rewriting: Append data on the end of each URL that identifies the session like http://localhost/yourservlet?session-id=value.
* Hidden form fields: HTML forms can have

Java Codes »

[12 Feb 2009 | No Comment | 191 views]

This Java tip illustrates a method of getting the client’s address in a Servlet. In an embodiment developer may use this tip in their client server applications for knowing at the server end the address of the client which made the request.
// This method is called by the servlet container to process a GET request.
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {

// Get client’s IP address
String addr = req.getRemoteAddr(); // 123.123.123.123

// Get client’s hostname
String host = req.getRemoteHost(); // hostname.com
}

Java Codes »

[12 Feb 2009 | No Comment | 172 views]

The method getRemoteUser() of the HttpServletRequest gives the username of the client. With the remote user’s name, a servlet can save information about each client. Over the long term, it can remember each individual’s preferences. For the short term, it can remember the series of pages, viewed by the client and use them to add a sense of state to a stateless HTTP protocol.
A simple servlet that uses getRemoteUser() can greet its clients by name and remember when each last logged in as shown in the example below:
import java.io.*;
import java.sql.Date;
import …

Java Codes »

[12 Feb 2009 | No Comment | 149 views]

These are the four methods that a servlet can use to get information about its server:
public String ServletRequest.getServerName()
public String ServletRequest.getServerPort()
public String ServletContext.getServerInfo()
public String ServletRequest.getAttributes(String name)
The sample code below uses the above function and print the server information to client.
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class DemoServerSnoop extends GenericServlet{

public void service(ServletRequest req , ServletResponse res)
throws ServletException,IOException{

res.setContentType(“text/plain”);
PrintWriter out= res.getWriter();
out.println(“req.getServerName()” + req.getServerName());
out.println(“req.getServerPort()” + req.getServerPort());

out.println(“ServletContext().getServerInfo()” +
getServletContext().getServerInfo());

out.println(“getServerInfo() name:” +
getServerInfoName(getServletContext().getServerInfo()));

out.println(“getServerInfo() version:” +
getServerInfoVersion(getServletContext().getServerInfo()));

out.println(“getServerContext().getAttribute(\”attribute\”)” +
getServletContext().getAttribute(“attribute”));
}
private String getServerInfoName(String serverInfo){

int slash = serverInfo.indexOf(‘/’);
if(slash==-1)
return serverInfo;

Java Codes »

[12 Feb 2009 | No Comment | 176 views]

A servlet can use getRemoteAddr() and getRemoteHost() to retrieve the IP Address and host of the client machine respectively:
public String ServletRequest.getRemoteAddr()
public Stirng ServletRequest.getRemoteHost()
Using these functions access to specific client host can be restricted. The sample code below checks the client specification at the server and send the relevant message to the client.
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class DemoExportRestriction extends HttpServlet{
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException{

res.setContentType(“text/plain”);
PrintWriter out= res.getWriter();

//Getting the client’s hostname
String remoteHost = req.getRemoteHost();

//See if the client is allowed
if(!isHostAllowed(remoteHost)){
out.println(“Access <BLINK>ACCESS DENIED </BLINK>”);
} else{
out.println(“access granted”);
}
}
private boolean isHostAllowed(String host) {
return(host.endsWith(“.com”))||
(host.indexOf(‘.’)==-1);//no domain , assume OK
}
}

Java Codes »

[12 Feb 2009 | No Comment | 166 views]

Servers like JRun and other provide separate logs where all your print requests print their data. For example requests to System.out. And System.err goes to different log files. If you want to maintain logs separately for each module then you can create a static class called “LogWriter” and call the method inside the try catch loop as follows.
try
{
// write your code here
}
catch(Exception e)
{
LogWriter.print(“Debug : error occurred at function ”)
}

Java Codes »

[12 Feb 2009 | No Comment | 137 views]

For example, you have two servlets (Servlet1 and Servlet2).
In Servlet1, you have a method called getString().
In Servlet2, use
ServletContext context = getServletContext();
to get servlet context of Servlet2. Then use
Servlet1 servlet = (Servlet1)context.getServlet(“Servlet1″);
to get the Servlet1 servlet object.
Now, you can Call Servlet1 method from Servlet2 with
servlet.getString();

Java Codes »

[12 Feb 2009 | No Comment | 191 views]

This J2EE tip demostrates chaining method in servlets. Servlet Chaining means the output of one servlet act as a input to another servlet. Servlet Aliasing allows us to invoke more than one servlet in sequence when the URL is opened with a common servlet alias. The output from first Servlet is sent as input to other Servlet and so on. The Output from the last Servlet is sent back to the browser. The entire process is called Servlet Chaining.
// FirstServlet
import javax.servlet.*;
import java.io.*;
import javax.servlet.http.*;
public class FirstServlet extends HttpServlet {
String name ;
ServletConfig config;