Archive for the ‘Java’ Category

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 :154858

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 :7341

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 :7738

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 :9705

Tags:

2 Comments


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

Basic HelloWorld Program for Servlet

Servlet Definition – Servlet 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 :6013

Tags:

1 Comment


Tomcat Directory Tree structure Tomcat Fundamentals Tomcat Administration

Tomcat Directory Tree

As we know that the tomcat container is used for web applications deployment,the various directories inside the server directory have proper purposes. The figure below illustrates the directory tree for Apache-Tomcat server :

  1. lib folder – This is where all the supporting jar files are placed which are needed by our project such as drivers .
  2. conf folder-This is where all the server configuration files are present,e.g. server.xml,tomcat-users.xml etc.This files are server configuration files and are not project specific.server.xml contains information like running port,shutdown port for the server.
  3. webapps folder-As the name suggests this is the place where we have to keep our project folders to be recoganised by our tomcat server.It is this folder where server searches for deployed projects.Here only the project folders are placed.Project folders again need to follow a certain directory structure for successful deployment.The project directory tree is shown as below :1.WEBINF folder – This folder contains folders classes ,lib.Inside classes folder all the java class files for servlets and pojos are kept.The server searches here for the class file of respective java source code.Inside lib project specific jar files such as drivers or others are kept.Inside the WEB-INF folder only lies the project configuration file web.xml which is also known as the deployment descriptor.It is the project configuration file which contains info like servlet mapping info,welcome file list,servlet and context params etc.

The html and jsp files are put in project folder parallel to WEBINF folder.

Number of View :3341

Tags:

No Comments


Basics of tomcat Apache-Tomcat Tutorial Download and Run Tomcat

How To Install Apache-Tomcat  Web server

Apache-tomcat is a web  server which processes static requests and provides a number of services .The container in fact provides services for web applications.Here comes the distinction between web servers and the application servers where application servers are capable of processing dynamic requests.

Installing tomcat is a simple process.Please note the steps noted below :

Step -1

Install the latest stable version of java sdk.Installing java is simple.Just uncompress the java zip file

and set the environment variables PATH to fullyqualifiedpathofjavafoldername/bin and JAVA_HOME env to fullyqualifiedpathofjavafoldername.Tomcat server looksup for the java from the JAVA_HOME env.

Step-2

Download Stable version of Apache-Tomcat version from the url : http://tomcat.apache.org/download-60.cgi .Download tar.gz file and uncompress it in a proper directory.

Step-3

Set the environment variable CATALINA_HOME to fullyqualifiedpathoftomcatserver.Append the PATH variable with fullyqualifiednameoftomcatserver/bin.

Step-4

To run the tomcat server goto tomcatpath/bin and run the startup.sh file/startup.bat file.If your tomcat has been installed properly following page will appear.


Here 8081 is the port number on which server is running.By default,the port number is 8080

Number of View :3145

Tags:

No Comments


Quartz Open source Scheduler Basic Schedulers in Java Install Quartz for JAva

Quartz scheduler for java

Quartz is an open source scheduler for java applications.It is a full-featured job scheduling service which can be intergrated with any java application whether web based or console.Quartz can be used to create simple or complex schedules for executing tens, hundreds, or even tens-of-thousands of jobs.The Quartz Scheduler includes many enterprise-class features, such as JTA transactions and clustering and many more.

How to install Quartz :

Download the quartz latest stable release from the link http://www.terracotta.org/dl/quartz-oss-sign-up .

For linux it will be zipper tar file which can be extracted.The Quartz package includes a number of jar files.The main Quartz library is named quartz-all-version.jar . In order to use any of Quartz’s features, this jar must be located on your application’s classpath.Basically we need to include all the jar files in the “lib” folder and other jar files to be included in the project`s classpath.

Quartz contains a number of third party librarries which are available in the form of jar files inside the “lib” folder.When we are devloping any web application or enterprise application,we need to add these jar files in projects library.

The properties file :

Quartz uses “quartz.properties” file to store all the configuration details,thus making quartz highly configurable.All details such as sceduler name,number of threads etc can be mentioned here within this file.The properties file appears like :

org.quartz.scheduler.instanceName = SchedulerName
org.quartz.scheduler.instanceId = 1
org.quartz.scheduler.rmi.export = false
org.quartz.scheduler.rmi.proxy = false

org.quartz.threadPool.class = org.quartz.simpl.SimpleThreadPool
org.quartz.threadPool.threadCount = 5

org.quartz.jobStore.class = org.quartz.simpl.RAMJobStore

The sample Code :
Once we have included all the jar files we can use quartz scheduling in our project.
The sample code is as follows :

import org.quartz.Scheduler;
import org.quartz.SchedulerException;
ipport org.quartz.impl.StdSchedulerFactory;

public class QuartzTest {
    public static void main(String[] args) {
        try {
            // Obtain the Scheduler from the Factory as an instance
            Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();

            // start scheduler
            scheduler.start();
               //write jobs here
            scheduler.shutdown();

        } catch (SchedulerException se) {
            se.printStackTrace();
        }
    }
}

We can schedule the jobs writing the job scheduling code within scheduler.start() and scheduler.shutdown() function calls.

Number of View :5515

Tags:

2 Comments


Acegi Security Grails Acegi Plugin Acegi Tutorial

Number of View :4982

Tags:

No Comments


Introduction to Grails plugins Grails Plugins Tutorials Understanding Grails Plugins

What is Grails Plugins

What is a plugin

One of the most important factors which makes Grails very configurable is the concept of plug and play plugins. Almost any functionality which needs to be coded in a web application can be introduced via plugins without any code to be written. The beauty of plugin lies in, we donot have to write any code but just include the plugin and customize codes to our requirement.

A plugin is nothing but a regular Grails application with this special file; but when plugin is installed, the plugin structure slightly differs.

Plugin’s structure

When a plugin is installed into a project, the contents of grails-app directory goes into a directory like $PROJECT_HOME/plugins/example-1.0/grails-app . They will NOT be copied into the main source tree. A plugin doesnot tamper a project’s primary source tree.

The plugin directory structure appears as below :

+ grails-app
     + controllers
     + domain
     + taglib
     etc.
 + lib
 + src
     + java
     + groovy
 + web-app
     + js
     + css

The static resources such as those inside the web-app directory will be copied into the project’s web-app directory under a special “plugins” directory for example web-app/plugins/example-1.0/js . It is therefore the responsibility of the plugin to make sure that it references static resources from the correct place. For example if you were

<g:createLinkTo dir="/plugins/example/js" file="mycode.js" />

To make this easier there is a special pluginContextPath variable available that changes whether you’re executing the plugin standalone or whether you’ve installed it into an application:

<g:createLinkTo dir="${pluginContextPath}" file="js/mycode.js" />

At runtime this will either evaluate to /js or /plugins/example/js depending on whether the plugin is running standalone or has been installed in an application.

Java & Groovy code that the plugin provides within the lib and src/java and src/groovy directories will be compiled into the main project’s web-app/WEB-INF/classes directory so that they are made available at runtime.

What a Plugin can and can’t do

A plugin can do just about anything, but a good plugin should be as intrusive as possible. It should use convention over configuration where possible, otherwise provide an artifact in a project’s grails-app/conf directory where configuration can be done.

One thing a plugin cannot do though is modify the web-app/WEB-INF/web.xml or web-app/WEB-INF/applicationContext.xml files. A plugin can participate in web.xml generation, but not modify the file or provide a replacement. A plugin can NEVER change the applicationContext.xml file, but can provide runtime bean definitions .

Number of View :4761

Tags:

No Comments



SetPageWidth
Content Protected Using Blog Protector By: PcDrome.