- contextInitialized() method will be executed automatically during Servlet container initialization, which in turn calls the Quartz scheduler job, which gets executed every 10 seconds.
- contextDestroyed() method will be executed when the application shuts down, So in this function I have invoked the shutdown function of quartz scheduler
Export Grid View to Excel in Servlet and Jsp
Exporting contents to excel spreadsheet is a much required functionality for almost every data driven website. In this article I am going to explain in detail on how to export gridview contents to an excel sheet via a java web application.
Project Structure
Servlet
package servlet; import java.io.IOException; import java.util.ArrayList; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import model.Student; public class ExportToExcel extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ArrayList<Student> students = new ArrayList<Student>(); students.add(new Student("Mohaideen", "CSE", 17)); students.add(new Student("Nilafar", "IT", 16)); students.add(new Student("Thasleema", "CSE", 16)); request.setAttribute("students", students); RequestDispatcher rd = request.getRequestDispatcher("report.jsp"); rd.forward(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ArrayList<Student> students = new ArrayList<Student>(); students.add(new Student("Mohaideen", "CSE", 17)); students.add(new Student("Nilafar", "IT", 16)); students.add(new Student("Thasleema", "CSE", 16)); request.setAttribute("students", students); RequestDispatcher rd = request.getRequestDispatcher("exportExcel.jsp"); rd.forward(request, response); } }
Model
package model; public class Student { private String name; private String department; private int age; public Student(String name, String department, int age) { this.name = name; this.department = department; this.age = age; } public String getName() { return name; } public String getDepartment() { return department; } public int getAge() { return age; } public void setName(String name) { this.name = name; } public void setDepartment(String department) { this.department = department; } public void setAge(int age) { this.age = age; } }
JSP Page
File : index.jsp – Used to navigate to exporttoexcel servlet action
<html> <head> <META HTTP-EQUIV="Refresh" CONTENT="0;URL=exporttoexcel"> </head> <body> </body> </html>
File : report.jsp – This page used to display gridview filled with data of student table from server side.
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ page import="java.util.List"%> <%@ page import="model.Student"%> <html> <head> <title>Export to Excel</title> </head> <body> <h3>Export to Excel Example</h3> <form action="exporttoexcel" method="post"> <table cellpadding="1" cellspacing="1" border="1" bordercolor="gray"> <tr> <td><b>Name</b></td> <td><b>Department</b></td> <td><b>Age</b></td> </tr> <% List<Student> students = (List<Student>) request .getAttribute("students"); for (Student std : students) { %> <tr> <td><%=std.getName()%></td> <td><%=std.getDepartment()%></td> <td><%=std.getAge()%></td> </tr> <% } %> </table> <BR /> <input type="submit" value="Export To Excel" /> </form> </body> </html>
File : exportExcel.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ page import="java.util.List"%> <%@ page import="model.Student"%> <html> <head> <title>Export to Excel Example</title> </head> <body> <h3>Export to Excel Example</h3> <table cellpadding="1" cellspacing="1" border="1" bordercolor="gray"> <tr> <td>Name</td> <td>Department</td> <td>Age</td> </tr> <% List<Student> students = (List<Student>) request.getAttribute("students"); if (students != null) { response.setContentType("application/vnd.ms-excel"); response.setHeader("Content-Disposition", "inline; filename=" + "StudentReport.xls"); } for (Student std : students) { %> <tr> <td><%=std.getName()%></td> <td><%=std.getDepartment()%></td> <td><%=std.getAge()%></td> </tr> <% } %> </table> </body> </html>
web.xml
<web-app .. version="3.0"> <display-name>ExportToExcel</display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <servlet> <servlet-name>ExportToExcel</servlet-name> <servlet-class>servlet.ExportToExcel</servlet-class> </servlet> <servlet-mapping> <servlet-name>ExportToExcel</servlet-name> <url-pattern>/exporttoexcel</url-pattern> </servlet-mapping> </web-app>
Demo
On running the application
On clicking “Export To Excel” button the following page with download file options get appears
AJAX implementation in Servlets using JQuery and JSON
In my previous post, I explained about making AJAX calls to a servlet from a JSP page and updating a part of the JSP page with a simple response from the Servlet . In this post I am going to add something more to it by making the servlet return complex Java Objects such as lists, maps, etc with the help of JSON in addition to JQuery and AJAX.
Here I’m going to use a JSON library in Servlet to convert this complex Java objects (lists,maps,arrays.etc) to JSON strings that will be parsed by JQuery in the JSP page and will be displayed on the web page. I am going to use google’s gson library for this purpose.
Library required
Project Structure
Steps done to set up our Servlet for JSON
From the browser perspective: jQuery
Jsp Page
<html> <head> <title>AJAX in Servlet using JQuery and JSON</title> <script src="js/jquery-1.11.1.js" type="text/javascript"></script> <script> $(document).ready(function() { $('.ajax-link').click(function() { $('.page-content').hide(); var category = $(this).attr("data-category"); // the URL for the request $.get('ajaxAction', { // Parameter to be sent to server side category : category }, function(jsonResponse) { $.each(jsonResponse, function(index, value) { $("#" + index).html(value); if (index % 2 == 0) { $("#" + index).addClass("lightblue"); } }); $('.page-content').show(); }); }); }); </script> </head> <body> <div class="main-content"> <div> <h3>Click on the links</h3> <ul> <li><a href="#" class="ajax-link" data-category="serial">Top 5 Serial</a></li> <li><a href="#" class="ajax-link" data-category="movies">Top 5 Movies</a></li> <li><a href="#" class="ajax-link" data-category="sports">Top 5 Sports</a></li> </ul> <h3>Result will be displayed below via Ajax</h3> <div class="page-content"> <div id="0"></div> <div id="1"></div> <div id="2"></div> <div id="3"></div> <div id="4"></div> </div> </div> </div> </body> </html>
jQuery allows you to fire an ajax request via get or post method and expects a JSON object as a response, as described in my previous post the first and second parameter of these method are the url and a key-value pair and the third argument of get method is a function that defines what is to be done with the response that is got back from the Servlet.
Code Explanation
In the above code jquery will fire an ajax request when user clicks on a link, for this we have binded the jQuery’s click event with each link using the class supplied on the links; Then we need to extract the category
from link using jQuery’s attribute selector, and then we had binded the ajax request to ajaxAction
url and passed the category as parameter and the server in turn return the required response.
Another must read:
- jQuery Tutorial for Beginners
- Refresh DIV Content Without Reloading Page using jQuery
- Autocomplete in Java web application
From the server’s perspective: Servlet
In Servlet, I’m going to use a GSON library to convert Java objects (lists, maps etc) to JSON strings that will be parsed by JQuery in the JSP page and will be displayed on the web page and note that I have returned the response back to jsp based on the value of category
parameter which i pass to the servlet via jQuery’s get() method.
Servlet
package com.action; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.gson.Gson; public class JsonServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String category = request.getParameter("category"); List<String> result = new ArrayList<String>(); if (category.equalsIgnoreCase("serial")) { result.add("Game Of Throme"); result.add("Prison Break"); result.add("Breaking Bad"); result.add("Sherlok Home"); result.add("Suits"); } else if (category.equalsIgnoreCase("movies")) { result.add("Inception"); result.add("War Horse"); result.add("Avatar"); result.add("Titanic"); result.add("Life is Beautiful"); } else if (category.equalsIgnoreCase("sports")) { result.add("Basket Ball"); result.add("Football"); result.add("Tennis"); result.add("Rugby"); result.add("Cricket"); } String json = new Gson().toJson(result); response.setContentType("application/json"); response.getWriter().write(json); } }
Web.xml
Servlet mapping should be done in web.xml as shown below
<web-app ..> <servlet> <servlet-name>AjaxAction</servlet-name> <servlet-class>com.action.JsonServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>AjaxAction</servlet-name> <url-pattern>/ajaxAction</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
Demo
On clicking ‘Top 5 Serial’ the following response appears
On clicking ‘Top 5 Movies’ the following response appears
Other Ajax tutorial from our Blog
- Ajax Cascading DropDownList in JSP & Servlet using JQuery and JSON
- AngularJS Interacting with Java Servlet using JSON
- Autocomplete in java web application using Jquery and JSON
Reference
Read More
Setting up jQuery jTable plugin in Servlets and JSP
In this article we will learn to setup jTable and dependent libraries in a Java web application.
For all who do not know what exactly jTable is, it is a jQuery plugin which is used to create AJAX based CRUD tables without coding HTML or Javascript.
Let us take a look at what happens if we are not using a Jquery Plugin for front end Table data management.
Using Java & Javascript:
Pre-requisites for usage:
- Must be a expertise in java & javascript
- A lot of time on hand
- Last but not the least patience
Now if the project requirement for this table changes at last moment one would pull their hair out and end up resembling a Joker
jTable has a few advantages over the above, some of them being:
- Automatically creates HTML table and loads records from server using AJAX.
- jTable uses just a div id and automatically generates html table inside the div
- It uses jQuery UI dialog that pops up when the user clicks on add, edit or update record buttons
- Shows animations for create/delete/edit operations on the table.
- Supports server side paging & sorting using AJAX.
- Supports master/child tables.
- Supports several pre defined color themes; In this example I have used metro blue theme for my project.
And there are lot other features than mention above, to know more please read on its official home page.
Steps done to set up our application for jTable
Libraries required
Now to start with demonstration of above topic, let us Create a Dynamic Web Project in Eclipse, with following project structure.
As show in the image download the required library mentioned and place it in js and css folder of eclipse work-space, and refer these files in the head section in the jsp as shown below.
Setup done from the browser perspective: jTable
jTable plugin allows you to issue an ajax request via jQuery plugin and expects a JSON object as a response, hence the following configuration needs to be made in Jsp file
Jsp Page
<!DOCTYPE html> <html> <head> <title>jQuery jTable Setup in java</title> <!-- jTable Metro styles. --> <link href="css/metro/blue/jtable.css" rel="stylesheet" type="text/css" /> <link href="css/jquery-ui-1.10.3.custom.css" rel="stylesheet" type="text/css" /> <!-- jTable script file. --> <script src="js/jquery-1.8.2.js" type="text/javascript"></script> <script src="js/jquery-ui-1.10.3.custom.js" type="text/javascript"></script> <script src="js/jquery.jtable.js" type="text/javascript"></script> <script type="text/javascript"> $(document).ready(function() { $('#StudentTableContainer').jtable({ title : 'Students List', actions : { listAction : 'Controller?action=list' }, fields : { studentId : { title : 'Student Id', width : '30%', key : true, list : true, create : true }, name : { title : 'Name', width : '30%', edit : false }, department : { title : 'Department', width : '30%', edit : true }, emailId : { title : 'Email', width : '20%', edit : true } } }); $('#StudentTableContainer').jtable('load'); }); </script> </head> <body> <div style="text-align: center;"> <h4>jQuery jTable Setup in java</h4> <div id="StudentTableContainer"></div> </div> </body> </html>
As you can see, jTable just needs a div element as the only HTML tag. It fields options are explained below:
title: Title of the table.
actions: URLs of actions that are used to create/delete/update/list records.
fields: It defines the field names that represent columns of the record. Note that the field name should exactly match the instance variable defined in the model class.
In the jsp above I have only provided action url for listAction for demonstration purpose, we can include action for add,edit and delete functionality as well, which we will learn in a while. The load method of jTable is fired when page is loaded which in turn trigger listAction to get records from the server.
Setup done from the server’s perspective: Servlet
In Servlet, we are going to use a JSON library to convert Java objects(studentList) to JSON strings that will be parsed by jTable pugin in the JSP page and will be displayed on the web page.This conversion of Java Object to Json format is done using Google gson jar.
Controller
package com.servlet; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.model.Student; public class Controller extends HttpServlet { private static final long serialVersionUID = 1L; private HashMap<String, Object> JSONROOT = new HashMap<String, Object>(); public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String action = request.getParameter("action"); if ( action != null) { List<Student> studentList = new ArrayList<Student>(); Gson gson = new GsonBuilder().setPrettyPrinting().create(); response.setContentType("application/json"); if (action.equals("list")) { try { // Add data to Student list studentList.add(new Student(1, "Haripriya", "IT", "[email protected]")); studentList.add(new Student(2, "Dinesh", "ECE", "[email protected]")); studentList.add(new Student(3, "Prabhu", "MECH", "[email protected]")); studentList.add(new Student(4, "Badru", "ECE", "[email protected]")); studentList.add(new Student(5, "Lahir nisha", "CSC", "[email protected]")); studentList.add(new Student(6, "Nilafar nisha", "CSC", "[email protected]")); studentList.add(new Student(7, "Jamil", "ECE", "[email protected]")); studentList.add(new Student(8, "Mahes", "ECE", "[email protected]")); studentList.add(new Student(9, "Lourde", "IT", "[email protected]")); //Return in the format required by jTable plugin JSONROOT.put("Result", "OK"); JSONROOT.put("Records", studentList); // Convert Java Object to Json String jsonArray = gson.toJson(JSONROOT); System.out.println(jsonArray); response.getWriter().print(jsonArray); } catch(Exception ex){ JSONROOT.put("Result", "ERROR"); JSONROOT.put("Message", ex.getMessage()); String error = gson.toJson(JSONROOT); response.getWriter().print(error); } } } } }
In case of read operations in jTable, Result property must be “OK” if operation is successful. If an error occurs, then Result property must be “ERROR”. If Result is “OK”, the Records property will contain an array of records defined in the servlet. If it’s ERROR, a Message property will contain an error message to show to the user. A sample return value for listAction is show below
{“Result”:”OK”,”Records”:[
{
“studentId”: 2,
“name”: “Bashit”,
“department”: “EEE”,
“emailId”: “[email protected]”
},
{
“studentId”: 3,
“name”: “Haripriya”,
“department”: “IT”,
“emailId”: “[email protected]”
}
]}
Model Class
Create the Model class , which will have getters and setters for fields used in jsp
package com.model; public class Student { public Student() { } public Student(int studentId, String name, String department, String emailId) { this.studentId = studentId; this.name = name; this.department = department; this.emailId = emailId; } private int studentId; private String name; private String department; private String emailId; public int getStudentId() { return studentId; } public String getName() { return name; } public String getDepartment() { return department; } public String getEmailId() { return emailId; } public void setStudentId(int studentId) { this.studentId = studentId; } public void setName(String name) { this.name = name; } public void setDepartment(String department) { this.department = department; } public void setEmailId(String emailId) { this.emailId = emailId; } }
web.xml
Make sure you have done servlet mapping properly in web.xml file. An example of this is given below,
<welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <servlet> <servlet-name>Controller</servlet-name> <servlet-class>com.servlet.Controller</servlet-class> </servlet> <servlet-mapping> <servlet-name>Controller</servlet-name> <url-pattern>/Controller</url-pattern> </servlet-mapping>
Demo
Now on including action for create, update and delete in jsp page as below
actions : { listAction: 'Controller?action=list', createAction:'Controller?action=create', updateAction: 'Controller?action=update', deleteAction: 'Controller?action=delete' }
No on running with the above changes, the demo looks like below
On clicking ‘Add new record’
On clicking edit button
On clicking delete button
Note :
In the above program I have not included the logic for create, delete and update functions at server side. In the article CRUD Operations in Java Web Applications using jTable jQuery plugin via Ajax I have implemented CRUD operation, and in the article Pagination in Java Web Applications using jQuery jTable plugin I have implemented paging feature using the same plugin.
Reference
jTable official website
AJAX based CRUD tables using ASP.NET MVC 3 and jTable jQuery plug-in
Wikipedia : JSON
Integrating Quartz Scheduler with Java Web Application
In our previous article we learn about Quartz 2 hello world example along with types of Triggers in Quartz 2, In this article we shall learn to Integrating Quartz 2 Scheduler in Java Web Application. Quartz, is an open source job scheduling framework, that let you schedule a task to run on a predefine date and time.
Library required
commons-logging-1.1.1.jar
log4j-1.2.16.jar
quartz-2.2.1.jar
slf4j-api-1.6.6.jar
slf4j-log4j12-1.6.6.jar
Scheduler Job
Create a Quartz’s job
package com.quartz; import org.quartz.Job; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; public class QuartzJob implements Job { public void execute(JobExecutionContext context) throws JobExecutionException { System.out.println("Java web application + Quartz 2.2.1"); } }
Servlet Listener
Now Create servlet listener class by implementing ServletContextListener interface and override contextInitialized and contextDestroyed methods with your logic’s.
package com.quartz; import static org.quartz.JobBuilder.newJob; import static org.quartz.TriggerBuilder.newTrigger; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import org.quartz.CronScheduleBuilder; import org.quartz.JobDetail; import org.quartz.Scheduler; import org.quartz.SchedulerException; import org.quartz.Trigger; import org.quartz.impl.StdSchedulerFactory; public class QuartzListener implements ServletContextListener { Scheduler scheduler = null; @Override public void contextInitialized(ServletContextEvent servletContext) { System.out.println("Context Initialized"); try { // Setup the Job class and the Job group JobDetail job = newJob(QuartzJob.class).withIdentity( "CronQuartzJob", "Group").build(); // Create a Trigger that fires every 5 minutes. Trigger trigger = newTrigger() .withIdentity("TriggerName", "Group") .withSchedule(CronScheduleBuilder.cronSchedule("0/5 * * * * ?")) .build(); // Setup the Job and Trigger with Scheduler & schedule jobs scheduler = new StdSchedulerFactory().getScheduler(); scheduler.start(); scheduler.scheduleJob(job, trigger); } catch (SchedulerException e) { e.printStackTrace(); } } @Override public void contextDestroyed(ServletContextEvent servletContext) { System.out.println("Context Destroyed"); try { scheduler.shutdown(); } catch (SchedulerException e) { e.printStackTrace(); } } }
Recommended Article
web.xml
Configure the listener class QuartzSchedulerListener.java into the web.xml file as shown below
<listener> <listener-class>com.quartz.QuartzListener</listener-class> </listener>
Demo
Now on starting the Tomcat Server, the project gets started, and so the registered listener class QuartzSchedulerListener.java will be fired, and following output is obtained at the console
Why use JSP when we can do the same thing with servlets?
Highly Coupled Servlets
In our previous tutorial we have implemented an servlet hello world example, in which a servlet acts as both controller as well as presenter; below are the list of problem when servlet acts as both controller and presenter,
- High cost of maintenance
- HTML and Java exist in the same file.
- Web Designers don’t understand java code, don’t like the java code…
- Programmers don’t particularly like the messing with <HTML> code!!!!
In simple words ….
if( developer == javaProgrammer) System.out.println("Stick to Java code!"); else if( developer == webDesigner ) System.out.println("Stick to html code!");
So its better to separate JAVA code from the HTML code. Now the Question is How to Separate ????
Java Server Pages(JSP)
Java Server Pages (JSPs) provide a way to separate the generation of dynamic content (java) from its presentation (html)
How do JSP’s Work
The work flow of jsp is depicted pictographically below.
In our next tutorial we shall learn to implement hello world example in servlet using JSP.
Servlet Hello World Example in Eclipse IDE with Tomcat Server
In our previous tutorial we have learnt on how to create a Servlet with Eclipse IDE and Tomcat server, in this article we shall learn to run a sample hello world program using servlet to display welcome message in browser.
Library required
servlet-api-3.0.jar
Final Project Structure
Servlet
package com.servlet; 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 HelloWorldServlet extends HttpServlet { private static final long serialVersionUID = 1L; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<head><title>Hello world in Servlet</title></head>"); out.println("<body>"); out.println("<p>Hurray!! This Servlet worked!!!</p>"); out.println("</body>"); out.println("</html>"); } }
web.xml
Having created a simple servlet, Now the question arises, how the container knows which servlet is being requested by the client, the answer to this question is web.xml file that resides there on server and it have valid mappings from request to servlet. This web.xml looks something like this:
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>HelloWorldServlet</display-name> <servlet> <servlet-name>HelloWorld</servlet-name> <servlet-class>com.servlet.HelloWorldServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>HelloWorld</servlet-name> <url-pattern>/Hello</url-pattern> </servlet-mapping> </web-app>
Every servlet in a web application must have an entry into this file within two tags
<servlet-name>: A name is given to the servlet within this tag; name could be any user defined value.
<servlet-class>: Here we give the name with path to exact servlet class.
<url-pattern> : Here we give the url pattern of requested url, on which the servlet will be called.
No if we want to call a servlet for helloworld, then the requested url will be like http://localhost:8089/HelloWorldServlet/helloworld. Here / helloworld is the url-pattern for servlet.
http://<server>:<port>/<webapp>/urlpattern
So whenever this url is requested then it will search for a url-pattern with /helloworld in web.xml, now the servlet-name to this mapping will be compared to servlet block and required class file will be called according to servlet-class tag.
So this is how web containers maps a request from a client and invoke a right servlet and right method and the dynamic response is being served to the client.
Demo
Now right click on project [Root] > Run As > Run on Server
See in the URL ‘http://localhost:8089/HelloWorldServlet/’ is our servlet application directory. Here I have got a 404 page since i have not configured any welcome page in my web.xml
Now if you try to access the project via http://localhost:8089/HelloWorldServlet/helloworld then the following output is obtained.
Hope you understood how this servlet mapping occurs in java web application.