Posts Tagged ‘Tomcat server’

Difference Between Parameters And Attributes In Servlets/JSP Parameter vs. Attribute

Parameters and Attributes in Servlets And JSPs

 

Parameters and attributes in servlets and JSPs in java web applications are ways of communication among various entities(servlets and JSPs). However, there are differences between parameters and attributes.

The differences are as follows :

 

Attributes in Servlets and JSPs:

Attributes in servlets and JSPs can be of various scope.e.g.-request,session,servlet context(Application)

When attributes in servlets and JSPs are obtained in the code the return type is object of an “Object” class.

Attributes  in servlets and JSPs can be set or got from the code of the of servles and JSPs.

 

Parameters in servlets and JSPs:

Parameters  in servlets and JSPs are valid till the request response cycle only.

The return type of he code for obtaining  the parameters  in servlets and JSPs  is an object of  the  type String.

Parameters  in servlets and JSPs can only be read from the code.

Parameters  in servlets and JSPs can be set only through web.xml or appended in url from html parameters(text boxes etc.)

 

 

Code for getting a parameter is::

request.getParameter("paramname");

code for  seting an attribute is ::

scope.setAttribute("name","value");

code of getting an attribute value is ::

scope.getAttribute("name");

Here scope symbolizes different scopes(Request,Session or Application))

 

Parameters can be set from web.xml file as follows:

 

<servlet>
<servlet-name>myservlet</servlet-name>
<servlet-class>MyServlet</servlet-class>
 <init-param> <param-name>pname</param-name>
<param-value>pvalue</param-value>
</init-param>
</servlet> 

or 

<web-app> 

<context-param>
 <param-name>pname</param-name>
<param-value>pvalue</param-value>
</context-param>
 ...
 </web-app>

 

Conceptually Parameters in servlets and JSPs are used to capture user input/s in the application or to read from some configuration file.

Attributes in servlets and JSPs are used to pass data from one servlets or JSP to another servlet or JSP.Since attributes in servlets and JSPs can be associated to various scopes,its usage spans form maintaining session to maintain request attributes or maintain or get a value across the application itself. It is the concept  of usage which itself describes the differences between the two.

 

 

Number of View :1955

Tags: , , , , , , , ,

No Comments


How To Get The Parameters From One Servlet To Another Using Request

Access Parameters From One Servlet To Another

Parameters can only be set from the web.xml file or can be input from a user input through a view. It cannot be set from the servlet code. Once we have accessed the required parameter/parameters in one servlet,we can set a particular attribute and set that very attribute with the accessed value of parameter and it can be accessed through out various pages depending upon the type and nature and scope of the attributes .Here it must be noted that attributes and only attributes can be set with a value from code and not the parameters. So if we want to access a parameter from one one servlet to another,we must first access it in one servlet ,set an attribute with its value and then we can access it in other servlet.If the scope of attribute is request it will exist till request exists,if session then till session and if servletcontext then once set it can be accessed through the application. But the parameters can be read only once when taken from user input. The following code demonstrates this :

<servlet>

<servlet-name>FirstServlet</servlet-name>

<servlet-class>myjobs.FirstServlet</servlet-class>

<init-param>

<param-name>username</param-name>

<param-value>john</param-value>

</init-param>

</servlet>

<servlet>

<servlet-name>SecondServlet</servlet-name>

<servlet-class>myjobs.SecondServlet</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>NewServlet</servlet-name>

<url-pattern>/NewServlet</url-pattern>

</servlet-mapping>

FirstServlet :

public class FirstServlet extends HttpServlet {

/**

* Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.

* @param request servlet request

* @param response servlet response

* @throws ServletException if a servlet-specific error occurs

* @throws IOException if an I/O error occurs

*/

protected void processRequest(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

response.setContentType(“text/html;charset=UTF-8”);

PrintWriter out = response.getWriter();

try {

String uname=getServletConfig().getInitParameter(“username”);

request.setAttribute(“usrname”,uname);

request.getRequestDispatcher(“SecondServlet”).forward(request, response);

} finally {

out.close();

}

}

}

Second Servlet :

public class SecondServlet extends HttpServlet {

/**

* Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.

* @param request servlet request

* @param response servlet response

* @throws ServletException if a servlet-specific error occurs

* @throws IOException if an I/O error occurs

*/

protected void processRequest(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

response.setContentType(“text/html;charset=UTF-8”);

PrintWriter out = response.getWriter();

try {

/* TODO output your page here*/

out.println(“<html>”);

out.println(“<head>”);

out.println(“<title>Servlet SecondServlet</title>”);

out.println(“</head>”);

out.println(“<body>”);

out.println(“<h1>Parameter from first servlet is ” + request.getAttribute(“usrname”) + “</h1>”);

out.println(“</body>”);

out.println(“</html>”);

} finally {

out.close();

}

}

}

Here we are getting the paramter in FirstServlet setting an attribute and accessing in another servlet called SecondServlet.

Number of View :6389

Tags:

3 Comments


How To Redirect From One Servlet To Another Servlet Basics Servlet Redirect

Redirect to Other Servlets

Here we will talk about how to redirect from one servlet to another.Redirecting to a servlet is something like someone calls one for some work and the approached guy asks the person to call some other as he doesnot have the solution. It must be noted that the aproachee has to send the request to that other guy.The same thing happens in servlet redirecting as the request url changes and response comes form the servlet where request has been redirected. So,what can be done is write that very code in a servlet and that can be used at various places .The response object gives the method for redirect.The RequestDispacher class as the name suggests is the request delegater as it delegates the request but in redirect the request itself changes,so we can redirect the response to be given by another servlet.Iinside the doPost or doGet method.we can write the code to redirect in which the url for the servlet has to be given as a string..The example code is written below :

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

public class ResponseRedirect extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      ServletContext sc = this.getServletContext();
      response.senRedirect(“login”)
      }
      PrintWriter out = response.getWriter();
      out.print("Output after the content of login");
   }
}

Here we can see that redirection is occurring to login servlet in the ResponseRedirect servlet.In the redirection from one servlet to another we need to give the entry in <url-pattern> tag for the servlet as string.Once redirection happens the new request goes to login servlet,that means that client url changes and response comes from the login servlet as opposed to in the case of include or forward.With redirection we can move across applications and even across containers.Inside the servlet where redirection is happening,the rest of the code for the servlet will not be executed as the execution goes to the new redirected servlet.In the case of redirection we donot pass the request and response objects from the first servlet because new request and response is generated.

Number of View :2577

Tags:

No Comments


how to forward from one servlet to another Servlet Essentials Servlet Forward

Forward to Servlets

Here we will talk about how to forward from one servlet to another.Forwarding to a servlet is something like someone calls one for some work and the approached guy asks some one for help and returns the result to the approachee. It must be noted that the aproachee always sees the response from the that same guy only whom he called.The same thing happens in servlet forwarding as the request url doesnot change and response always comes as it has come from the first servlet and not the forwarded one. So,what can be done is write that very code in a servlet and that can be used at various places.The forward basically is a dynamic .The RequestDispatcher class gives the method for forward.The RequestDispacher class as the name suggests is the request delegater. The RequestDispatcher instance can be get from the request object inside the doPost or doGet method.Here the request and response objects are passed as paramters from the servlet code where forward code is written.The example code is written below :

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

public class RequestDispatch extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      ServletContext sc = this.getServletContext();
      RequestDispatcher rDis = sc.getRequestDispatcher("/login");
      if (rDis != null){
          rDis.forward(request, response);
      }
      PrintWriter out = response.getWriter();
      out.print("Output after the content of login");
   }
}

Here we can see that request is forwarded to login servlet in the RequestDispatch servlet.In the getting of RequestDispatch instance from the request object we need to give the entry in <url-pattern> tag for the servlet as string.

Number of View :2397

Tags:

No Comments


how to include one servlet into another Servlet Essentials Servlet Include

Include Servlets

Here we will talk about how to include one servlet into another.Including a servlet is as same as include that servlet`s code into the servlet in which it is included. This concept is used in places where we need to have reusable servlet codes which can be used at multiple places.Suppose we have some common code like login or some other logic which can be used at various places.So,what can be done is write that very code in a servlet and that can be used at various places.The inclusion basically is a dynamic inclusion which means the response of the included servlet is included in the includer servlet.The RequestDispatcher class gives the method for inclusion.The RequestDispacher class as the name suggests is the request delegater. The RequestDispatcher instance can be get from the request object inside the doPost or doGet method.Here the request and response objects are passed as paramters from the servlet code where inclusion code is written.The example code is written below :

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

public class RequestDispatch extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      ServletContext sc = this.getServletContext();
      RequestDispatcher rDis = sc.getRequestDispatcher("/login");
      if (rDis != null){
          rDis.include(request, response);
      }
      PrintWriter out = response.getWriter();
      out.print("Output after the content of login");
   }
}

Here we can see that login is included in the RequestDispatch servlet.In the getting if RequestDispatch instance from the request object we need to give the entry in <url-pattern> tag for the servlet.Then we can find that if we are printing anything from the included the servlet it will appear when we run RequestDispatch servlet as the login servlet is included.

Number of View :2628

Tags:

No Comments


Tomcat Error Pages list Display different error pages in tomcat setup Error Pages in tomcat

Setup error pages in tomcat

We can set up error pages for our applications running on tomcat server,so that when error or exception is thrown the user can get the appropriate message instead of the usual tomcat exception page which a user cant understand.The proper way to handle this issue is to have one`s own exception classes and throw them from the code and display error pages stating the possible causes for the error or exception and how to get rid of the same.Basically an error is a bug which is cannot be handeled from the source code such as linkage error or JVM crashes etc.An exception is a bug which our source code is liable to handle.Exceptions like file not found,sql exception etc. are checked exceptions which our code necessarily need to handle because of their possiblities of occurrences.Other exceptions which are run time exceptions need not be handled from our code as they are runtime and basically are logical errors such as division by zero,null pointer exception etc.But we can configure the error pages for errors and exceptions regardless of their nature in our tomcat application in the similar manner.We need to introduce a tag <error-pag> in our application`s web.xml file.In which we can specify error code and the location of the file to which the application must proceed if the error or exception has occurred.The snippet from the web.xml file is shown below :

<web-app>

  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>LoginView.jsp</welcome-file>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>

  <error-page>
     <error-code>404</error-code>
      <location>/error404.jsp</location>
  </error-page> 

  <error-page>
     <error-code>java.lang.NullPointerException</error-code>
      <location>/NullPointerException.jsp</location>
  </error-page>

</web-app>

The error-page tag is generally put in the last section of web.xml file,just below the welcome-file tag.Here we have put one error and an exception for demonstration.When we talk about errors we need to specify the error code in the <error-code> tag and the location of the html or jsp file which should be displayed when the error occurs.Likewise we have to cofigure for exceptions with the difference that instead of error in the error-code tag ,we have to write the fully qualified name of the exception class.For the checked exceptions however we need to throw our own exception derived from the class RuntimeException from the catch block of our code and configure the error page for our derived class inside the web.xml file.

Number of View :11994

Tags:

2 Comments


Tomcat Welcome file list Tomcat directory listing setup welcome files in tomcat

Setup Welcome File List

When we type the URL till the project name only,we get the directory listing of the project folders.To avoid this we can setup the welcome files,which acts the the default welcome page when we type the url till project folder.We can use this facility provided by the tomcat folder when we want to display something like a login page or welcome page as the default or first page for the website and check other pages to be in session so that the user once logins then only he/she can traverse through different views of the site.The entry for the welcome file can be done in the delpoyment descriptor,i.e. Web.xml file .The sample is given below :

<welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>LoginView.jsp</welcome-file>
    <welcome-file>index.jsp</welcome-file>
</welcome-file-list>

Here we can see that,when the url for till the project folder is hit in the browser,the welcome file is displayed.We can write as many welcome files in the <welcome-file-list> tag.The container first looks up for the first file to be present.If it exists it is displayed instead the container searches for the second entry.If not found it searches for the next page and so on till it finds one or els page not found error is thrown.However,to enable directory listing we can either edit the containers web.xml file which lies in the CATALINA_HOME/conf,or we can can edit our application specific web.xml file.In the server`s web.xml file we need to edit listings init param value for DefaultServlet entry as true.For the application specific purpose we need to override the DefaultServlet behaviour by making a sparate entry in the servlet tag for DeafaultServlet and making the listings init param as true.The snippet from the application`s web.xml file illustrates this:

<!-- Enable directory listings by overriding the server`s default web.xml file -->
<!-- The default servlet →

<servlet>
    <servlet-name>DefaultServletOverride</servlet-name>
    <servlet-class>org.apache.catalina.servlets.DefaultServlet</servlet-class>
    <init-param>
        <param-name>listings</param-name>
        <param-value>true</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

<!-- Add a mapping for our new default servlet -->
<servlet-mapping>
    <servlet-name>DefaultServletOverride</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

It must be noted that the entry in the servlet-name tag for the DefaultServlet be different in the container`s web.xml file and the application`s web.xml file otherwise a conflict will occur.

Number of View :3604

Tags:

No Comments


Context Params How to get context parameters in servlets Retrieving context params in servlets

Context Parameters

We can provide the context parameters for an application,insdie the web.xml file.These parameters are specific to a particular application and are initialised at the time application is loaded. Inside the web.xml file we declare a particular context param as shown below in the web.xml fragment :

<web-app>

<servlet>

<servlet-name>HelloWorld</servlet-name>

<servlet-class>HelloWorld</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>HelloWorld</servlet-name>

<url-pattern>/HelloWorld</url-pattern>

</servlet-mapping>

<context-param>

<param-name>username</param-name>

<param-value>Steve</param-value>

</context-param>

</webapp>

Here inside the web-app tag where we define the servlet-name and servletclass tags,we introduce the context-param tags which consist of param-name and param-value tags.param-name is the name of the context parameter and param-value is the value to which it has to be initialised.

Inside the servlet code we can access the context parameters from the servlet context object.Servlet context instance can be get from the inherited getServletContext() method.

The servlet code below illustrates the above :

import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

public class HelloWorld extends HttpServlet {

protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

doPost(request, response);

}

protected void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

response.setContentType(“text/html;charset=UTF-8”);

PrintWriter out = response.getWriter();

out.println(“<html>”);

out.println(“<head>”);

out.println(“<title>Servlet HelloWorld</title>”);

out.println(“</head>”);

out.println(“<body>”);

out.println(“<h1>Context Parameter username is ” + getServletContext().getInitParameter(“username”) + “</h1>”);

out.println(“</body>”);

out.println(“</html>”);

}

}

Here we get the context parameter “username” declared in the web.xml file by calling the method getInitParameter(“username”) on the servlet context object.The getInitParameter() method takes the name of the context parameter as string.The method getInitParameterNames() returns the enumeration of parameter values,all of which are declared in the web.xml file.Having run the above servlet code we get the output as :

Context Parameter username is Steve

steve is the value with which we inialised the context parameter,username in the web.xml file.

Number of View :4081

Tags:

1 Comment


Servlet Init Params How to get init parametrs in servlets Retreiving init params in servlets

Servlet Init Parameters

We can provide the initialistaion parameters for a servlet,insdie the web.xml file.These parameters are specific to a particular servlet and are initialised at the time application is loaded. Inside the web.xml file we declare a particular init param as shown below in the web.xml fragment :

<servlet>

<servlet-name>HelloWorld</servlet-name>

<servlet-class>HelloWorld</servlet-class>

<init-param>

<param-name>username</param-name>

<param-value>john</param-value>

</init-param>

</servlet>

<servlet-mapping>

<servlet-name>HelloWorld</servlet-name>

<url-pattern>/HelloWorld</url-pattern>

</servlet-mapping>

Here inside the servlet tag where we define the servlet-name and servletclass tags,we introduce the init-param tags which consist of param-name and param-value tags.param-name is the name of the initialistaion parameter and param-value is the value to which it has to be initialised.

Inside the servlet code we can access the init parameters from the servlet config object.Servlet config instance can be get from the inherited getServletConfig() method.

The servlet code below illusrtares the above :

import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

public class HelloWorld extends HttpServlet {

protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

doPost(request, response);

}

protected void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

response.setContentType(“text/html;charset=UTF-8”);

PrintWriter out = response.getWriter();

out.println(“<html>”);

out.println(“<head>”);

out.println(“<title>Servlet HelloWorld</title>”);

out.println(“</head>”);

out.println(“<body>”);

out.println(“<h1>Servlet Initialisation parameter is ” + getServletConfig().getInitParameter(“username”) + “</h1>”);

out.println(“</body>”);

out.println(“</html>”);

}

}

Here we get the init parameter “username” declared in the web.xml file by calling the method getInitParameter(“username”) on the servlet config object.The getInitParameter() method takes the name of the initialisation parameter as string.The method getInitParameterNames() returns the enumeration of parameter values,all of which are declared in the web.xml file.Having run the above servlet code we get the output as :

Servlet Initialisation parameter is john

john is the value with which we inialised the init parameter,username in the web.xml file.

Number of View :5448

Tags:

2 Comments


A Hello,World Servlet Servlet Tutorial Servlet Examples Run servlet on tomcat

Basic HelloWorld Program for Servlet

Servlet DefinitionServlet is a java code which runs at the servlet side and gives output in the form of html page.Its life cycle, init(),service() and destroy() is maintained by the container.

Here we will discuss how to run a simple servlet code. We will illustrate a simple HelloWorld.java for servlet .Lets us look at the code below so that we can correlate the concept.

import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

public class HelloWorld extends HttpServlet {

protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

doPost(request, response);

}

protected void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

response.setContentType(“text/html;charset=UTF-8”);

PrintWriter out = response.getWriter();

out.println(“<html>”);

out.println(“<head>”);

out.println(“<title>Servlet HelloWorld</title>”);

out.println(“</head>”);

out.println(“<body>”);

out.println(“<h1>Servlet HelloWorld at ” + request.getContextPath () + “</h1>”);

out.println(“</body>”);

out.println(“</html>”);

}

Here the methods doGet() and doPost() are the methods which get called by the service() method depending upon the fact that whether the request is post or get.How to call this servlet depends upon the entry in the web.xml file where the url-pattern tag indicates the url through which the servlet can be called.The imports above must be noted as the container will import the servlet APIs HttpServlet is the class from which our servlet class must inherit so as to process http requests.Let us look at he web.xml file now :

<?xml version=”1.0″ encoding=”UTF-8″?>

<web-app version=”2.4″ xmlns=”http://java.sun.com/xml/ns/j2ee” xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xsi:schemaLocation=”http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd”>

<servlet>

<servlet-name>HelloWorld</servlet-name>

<servlet-class>HelloWorld</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>HelloWorld</servlet-name>

<url-pattern>/HelloWorld</url-pattern>

</servlet-mapping>

</web-app>

This is the web.xml file with HelloWorld.java as the only servlet.the servlet-class tag contains the fully qualified name of the java class file.Before that we need to compile the servlet code and put the class file into WEB-INF/classes folder of our tomcat server.The entry in the servlet-name tag represents the alias name for the servlet,meaning in the rest of the portion of web.xml file the servlet will be recoganized by this alias name.url-pattern tag denotes the url through which the servlet can be accessed from browser.Now to run the servlet type the following url in your browser :

http://localhost:portnumber/projectname/HelloWorld

Number of View :4228

Tags:

1 Comment



SetPageWidth
Content Protected Using Blog Protector By: PcDrome.

Mahol Dot Org is Stephen Fry proof thanks to caching by WP Super Cache