Thursday, April 3, 2008

Servlet init parameters

these parameters are used to store some dynamic information in web applications.
init parameters can be accessed through the servlet config object where every servlet gets a reference to that.init parameters can only be accessed after calling the init method for that servlet.because the servletconfig is only available after a servlet initialization is done.

  • how to access init parameters











the ServletConfig interface have a method for getting init parameters
this is how we do that
getServletConfig.getInitParameter("Admin-email") ;

Dealing with the response

this is a sample class written by me to show how to deal with the responses.

package connection;

import java.io.*;
import java.net.*;

import javax.servlet.*;
import javax.servlet.http.*;


public class NewServlet extends HttpServlet {


protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//setting the content type
response.setContentType("text/html");
//response.setContentType("application/jar");
//we give the response page's content via this method
//whether it is a html one or appication download or some thing else

//to write data in to a character stream
PrintWriter out = response.getWriter();
//to add a new header
response.addHeader("name","value");
//to replace an existing header
response.setHeader("name", "new value");
//to redirect to a new page some where else
response.sendRedirect("www.cmb.ac.lk");
//to direct another portion of the web application
RequestDispatcher rd=request.getRequestDispatcher("test.jsp");
out.close();
}


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);
}

}