Showing posts with label J2EE 6. Show all posts
Showing posts with label J2EE 6. Show all posts

Monday, July 25, 2011

Large WAR file deployment in Tomcat 7

Tomcat 7 Manager application complains while deploying a larger WAR file. Here is error message:

The server encountered an internal error () that prevented it from fulfilling this request.

Exception java.lang.IllegalStateException: org.apache.tomcat.util.http.fileupload.FileUploadBase$SizeLimitExceededException:
the request was rejected because its size (XXX) exceeds the configured maximum (52428800)

Here is a solution:
Go to the web.xml of the manager application (@: TOMCAT_HOME/webapps/manager/WEB-INF/web.xml)
Increase the max-file-size and max-request-size:
Set these values greater than your WAR file size.



52428800
52428800
0

Wednesday, March 9, 2011

File Upload with Servlet 3.0

Servlet 3.0 has come with bunch of exciting features. File upload is one among the new feature available in servlet 3.0.

In earlier versions of servlet, file upload required commons api. In version 3.0 this feature is embedded in servlet api itself.

Here is a example to brief on file upload in servlet 3.0

FileUploadServlet is a servlet which extends HttpServlet and overrides doPost() method. To use file upload feature of servlet 3.0,
• MultipartConfig annotation has to specified on servlet, indicating that instance of the servlet expect request that conform to the multipart/form-data MIME type.

• Request object is provided with an API request.part(fileName), to get part or form item that was received within a multipart/form-data post request.


package com.jb;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

@MultipartConfig
@WebServlet(name="FileUploadServlet", urlPatterns={"/FileUploadServlet"})
public class FileUploadServlet extends HttpServlet {
   
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        doPost(request, response);
    } 
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {

        System.out.println("do post of file upload...");
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        Part part = request.getPart("fileName");
        InputStream is = part.getInputStream();
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);
        FileWriter fw = new FileWriter("c:/temp/tmp.txt");
        BufferedWriter bw = new BufferedWriter(fw);
        String line = null;
        while((line = br.readLine())!=null){
        bw.write(line);
        bw.newLine();
        }
        bw.close();
        br.close();
        out.write("File Uploaded successfully...");
        out.close();
    }
}

A jsp form to upload file to servlet is here.

Tuesday, March 1, 2011

Servlet 3.0 (part-2)

This article is continued from Servlet 3.0 (part-1). Here i will try to brief on programmatic adding of Servlet, Filters and Listeners to ServletContext object.

As per Servlet 3.0 Specs, any of these components (servlet, filter or listener) should be added during initialization of servletContext object, contextInitialized(ServletContextEvent sce) method of ServletContextListener API is a better place to add servlet and other components to context object.

A simple example to add a Servlet to ServletContext:

UserHomeServlet is a servlet which has to be registered to context programmatically.

public class UserHomeServlet extends HttpServlet {
   
    /** 
     * Handles the HTTP GET method.
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            RequestDispatcher rd = request.getRequestDispatcher("userHome.jsp");
            rd.forward(request, response);
        } finally {
            out.close();
        }
    } 

    /** 
     * Handles the HTTP POST method.
      */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        doGet(request, response);
    }
    
}


Implement ServletContextListener to provide realization for contextInitialized() method

@WebListener
public class CustServletContextListener implements ServletContextListener{

    public void contextInitialized(ServletContextEvent sce) {

        System.out.println("init context method");

        try{
            //add UserHomeServlet to context.
            ServletRegistration userHome = sce.getServletContext().addServlet("userHome", UserHomeServlet.class);
            //provide url pattern for UserHomeServlet.
            userHome.addMapping("/userHome");
        }catch(Exception e){
            e.printStackTrace();
        }
        
    }

    public void contextDestroyed(ServletContextEvent sce) {
        throw new UnsupportedOperationException("Not supported yet.");
    }
}


Similarly a Filter and Listener can be registered to context as below:

* Filter
public void contextInitialized(ServletContextEvent sce) {

        try{

            //add UserFilter to Context.
            FilterRegistration userFilter = sce.getServletContext().addFilter("userFilter", UserrequestFilter.class);
            //provide servlet name to filter.
            userFilter.addMappingForServletNames(null, true, "com.jb.UserHomeServlet");

        }catch(Exception e){
            e.printStackTrace();
        }
   }

* Listener

public void contextInitialized(ServletContextEvent sce) {

   try{

            //register UserRequestListener to context.
            sce.getServletContext().addListener(UserRequestListener.class);
            
        }catch(Exception e){
            e.printStackTrace();
        }
        
    }

Sunday, February 6, 2011

Servlet 3.0 (part-1)

The widely accepted technology to build web application, Servlets, has seen new features and APIs in its store with the release of version Servlet 3.0 specs. This release is crammed with stirring feature for new age web development.

The specification focuses on following feature:

• Ease of development
• Plug-ability and extensibility
• Asynchronous support
• Security enhancement

In this article(Servlet 3.0 part-1), I would keep the focus on defining Servlet, Filters and Listeners using annotations and will try to put my thougts on programmatically adding Servlet, Filters and Listeners to ServletContext object in Servlet 3.0 (part-2).

According to specs 3.0, deployment descriptor is optional. Servlets and other components can be configured using annotations.

All annotations used in Servlet 3.0 can be found under package ‘javax.servlet.annotation’.
For comparison, i have put code snippets for writing servlet and its components in old Servlet 2.5 API and same components in new Servlet 3.0. In 2.5 Web container will initialize the components only if you configure the details in deployment descriptor.

• Servlet:

public class ServletA extends HttpServlet {
//A GET method
    public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException{
        //code to process request
    }

Deployment Descriptor (web.xml) Entry 


        ServletA
        com.jb.ServletA

    
        ServletA
        /ServletA
    
 

Here is a much simplified code for servlet written in Servlet 3.0

@WebServlet(name="ServletA", urlPatterns={"/ServletA"})
public class ServletA extends HttpServlet {
    @ Override
    public void doGet (HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException{
        //code to process request.
    }
}

Deployment Descriptor (web.xml) Entry
Optional


• Filters

public class FilterA implements Filter {
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain)
 throws IOException, ServletException {
 //code snippets …
}

Deployment Descriptor (web.xml) Entry

    
        FilterA
        com.jb.FilterA
    
    
        FilterA
        /ServletA
    


Configuring Filter in Servlet 3.0
@WebFilter(filterName="FilterA", urlPatterns={"/ServletA"})
public class FilterA implements Filter {
 public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain)
 throws IOException, ServletException {
  //filter code here…
     }
}  
 

Deployment Descriptor (web.xml) Entry
Optional



• Listeners
public class ListenerA implements ServletContextListener {

    public void contextInitialized(ServletContextEvent sce) {
        throw new UnsupportedOperationException("Not supported yet.");
    }
}

Deployment Descriptor (web.xml) Entry

   
        com.jb.ListenerA    
    


Configuring Listeners in Servlet 3.0

@WebListener()
public class ListenerA implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        throw new UnsupportedOperationException("Not supported yet.");
    } 
}    

Deployment Descriptor (web.xml) Entry
Optional


• Passing Init Params in Servlet 3.0 has a simple syntax too.

@WebServlet(name="ServletA",
        urlPatterns={"/ServletA"},
        initParams={@WebInitParam(name="param1", value="paramvalue")} // passing init params to servlet ServletA
)
public class ServletA extends HttpServlet {
 //Servlet code …
}
 

Continued in Servlet 3.0 (part-2)...