[ Back | Previous | Next ]

How to redirect servlet calls?

Package:
javax.servlet.*
Product:
JDSK
Release:
1.x
Related Links:
General
General
General
General
General
Comment:
There are three ways to redirect servlet request.
  1. res.sendRedirect(url) -
    //No opening of any streams!!! Before 
    res.sendRedirect( query );
    // No opening of any streams!! After (not even System.out.println(x);
    // You cannot alter the URI!! Use the thrid method….
    
  2. open Socket to host and port and talk the HTTP protocol -
    /**
     * This method was created in VisualAge.
     * @param url java.lang.String
     */
    public void redirect(HttpServletResponse res, String url) {
    	String host = "141.176.4.9";
    	int port = 80;
    	String request = "GET / \n";
    	String line="";
    	try {
    		java.net.Socket s = new java.net.Socket(host, port);
    		java.io.OutputStream os = s.getOutputStream();
    		java.io.PrintWriter op = new java.io.PrintWriter(os);
    		op.println(request);
    		java.io.InputStream is = s.getInputStream();
    		java.io.BufferedReader di = new java.io.BufferedReader(new java.io.InputStreamReader(is));
    		res.setContentType("text/html");
    		while ((line = di.readLine()) != null)
    			res.getOutputStream().println(line);
    	} catch (Exception e) {
    		try {
    			res.sendError(javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST, "" + e.getMessage() + "
    " + line); } catch (java.io.IOException ioe) { } } }
  3. using the server headers to relocate the request - the 301 is the server code for redirection. This way it is also possible to alter the url.
    		res.setHeader("Location", "http://point/s97is.vts?" + query );
    		res.setStatus(301);
    
1