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

Points To Remember

Bootstrap is one of the major UI componnet used worldwide, So you may want to implemnt pagination using bootstrap in java , j2ee or spring application. So all you need to do is

  1. Create a Class that will behave like a taglib.
  2. Create a Tld file that will map the tablib class with the jsp's.
  3. Use the taglib on jsp using the tld file.

Create Pagination Taglib for Jsp with Bootstrap.

Following is an example of the a custom taglib built for Bootstrap. This taglib takes in

  • uri -> action to be hit when clicked.
  • offset -> the offset of pagination.
  • count -> total number of elements to be shown.
  • max -> maximum number of pages to be shown in the pagination bar.
  • steps -> maximum number of elements to be shown per page.
  • previous -> text to be shown for previous page link.
  • next -> text to be shown for next page link.

PaginationTaglib.java
This is a java class that will behave like a taglib on jsp's.
package com.ekiras.taglib;

import java.io.Writer;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.SimpleTagSupport;

public class PaginationTaglib extends SimpleTagSupport {
private String uri;
private int offset;
private int count;
private int max = 10;
private int steps = 10;
private String previous = "Previous";
private String next = "Next";

private Writer getWriter() {
JspWriter out = getJspContext().getOut();
return out;
}

@Override
public void doTag() throws JspException {
Writer out = getWriter();

try {
out.write("<nav>");
out.write("<ul class=\"pagination\">");

if(offset<steps)
out.write(constructLink(1, previous, "disabled", true));
else
out.write(constructLink(offset-steps, previous, null, false));

for(int itr=0;itr<count;itr+=steps) {
if(offset==itr)
out.write(constructLink((itr/10+1)-1 *steps, String.valueOf(itr/10+1), "active", true));
else
out.write(constructLink(itr/10*steps, String.valueOf(itr/10+1), null , false));
}

if(offset+steps>count)
out.write(constructLink(offset+steps, next, "disabled", true));
else
out.write(constructLink(offset+steps, next, null , false));


out.write("</ul>");
out.write("</nav>");
} catch (java.io.IOException ex) {
throw new JspException("Error in Paginator tag", ex);
}
}


private String constructLink(int page, String text, String className, boolean disabled) {
StringBuilder link = new StringBuilder("<li");
if (className != null) {
link.append(" class=\"");
link.append(className);
link.append("\"");
}
if(disabled)
link.append(">").append("<a href=\"#\">"+text+"</a></li>");
else
link.append(">").append("<a href=\""+uri+"?offset="+page + "\">"+text+"</a></li>");
return link.toString();
}

public String getUri() {
return uri;
}

public void setUri(String uri) {
this.uri = uri;
}

public int getOffset() {
return offset;
}

public void setOffset(int offset) {
this.offset = offset;
}

public int getCount() {
return count;
}

public void setCount(int count) {
this.count = count;
}

public int getMax() {
return max;
}

public void setMax(int max) {
this.max = max;
}

public String getPrevious() {
return previous;
}

public void setPrevious(String previous) {
this.previous = previous;
}

public String getNext() {
return next;
}

public void setNext(String next) {
this.next = next;
}

public int getSteps() {
return steps;
}

public void setSteps(int steps) {
this.steps = steps;
}

}

customTaglib.tld
This is the .tld file that defines how to use the java class as a taglib in jsp's
<?xml version="1.0" encoding="UTF-8"?>
<taglib version="2.1" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd">
<tlib-version>1.0</tlib-version>
<short-name>paginator</short-name>
<uri>/WEB-INF/taglibs/customTaglib.tld</uri>

<tag>
<name>paginate</name>
<tag-class>com.ekiras.taglib.PaginationTaglib</tag-class>
<body-content>empty</body-content>

<attribute>
<name>next</name>
<rtexprvalue>true</rtexprvalue>
<type>java.lang.String</type>
</attribute>
<attribute>
<name>previous</name>
<rtexprvalue>true</rtexprvalue>
<type>java.lang.String</type>
</attribute>
<attribute>
<name>uri</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
<type>java.lang.String</type>
</attribute>
<attribute>
<name>offset</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
<type>int</type>
</attribute>
<attribute>
<name>count</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
<type>int</type>
</attribute>
<attribute>
<name>max</name>
<rtexprvalue>true</rtexprvalue>
<type>int</type>
</attribute>
</tag>
</taglib>
Well that's all that you need to do do create a custom taglib and use it in your jsp's.
<%@ taglib prefix="tag" uri="/WEB-INF/taglibs/customTaglib.tld"%>
You can use this taglib in jsp by including it as mentioned above and use it like shown below.
<tag:paginate max="15" offset="${offset}" count="${count}" uri="${uri}"
next="&raquo;" previous="&laquo;" />
So this when used in the application may give u an output as shown in image below.



Points To Remember

You can define your custom error pages in web.xml. This is the best way to define custom 404 and other error pages.

Configure Custom error pages

Many times we want to create custom error pages in our web applications like for a 404 error, resource not found, 500 internal server error and other errors that we see commonly. So we may want to redirect such errors to a better looking custom error page.

If you want to redirect to custom error pages in a web application you can add these custom error pages in web.xml like following.

web.xml
 <error-page>
<error-code>400</error-code>
<location>/error/400.html</location>
</error-page>

<error-page>
<error-code>404</error-code>
<location>/error/404.html</location>
</error-page>

<error-page>
<error-code>500</error-code>
<location>/error/500.html</location>
</error-page>

<error-page>
<error-code>503</error-code>
<location>/error/503.html</location>
</error-page>
You can define your error page location in the <location> tag.

Points To Remember
  • Each Servlet has its own ServletConfig object.
  • ServletConfig is defined in web.xml
  • ServletConfig is a way of giving init parameters to a servlet during initialization. 
  • ServletConfig is a predefined interface.
  • ServeltConfig object is created by the container when a servlet is initialized and this object remains with the servlet throughout the life cycle of the servlet.
Example : How to get ServletConfig Object in a Servlet.
Lets take an example where we will add a few init params in the servlet config and get the config object from the servlet config object within the servlet.
package com.ekiras;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ServletConfigTest extends HttpServlet {
private static final long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();

ServletConfig config = getServletConfig();
Enumeration<String> e = config.getInitParameterNames();

String param = "";
while (e.hasMoreElements()) {
param = e.nextElement();
out.print(param);
out.print(" = " + config.getInitParameter(param) +"<br/>");
}

out.close();
}

protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {

}

}



The following is the web.xml with the servlet mapping and init params for servlet.
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID" version="3.1">
<display-name>Servlet Config Test</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>


<servlet>
<servlet-name>servletConfigTest</servlet-name>
<servlet-class>com.ekiras.ServletConfigTest</servlet-class>

<init-param>
<param-name>name</param-name>
<param-value>ekiras</param-value>
</init-param>

<init-param>
<param-name>blog</param-name>
<param-value>http://ekiras.blogspot.com</param-value>
</init-param>

</servlet>

<servlet-mapping>
<servlet-name>servletConfigTest</servlet-name>
<url-pattern>/test</url-pattern>
</servlet-mapping>



</web-app>
The above will give the following output when run in a servlet container like tomcat with url /test
name=ekiras
blog=http://ekiras.blogspot.com

Points To Remember
  • Servlet is a java class that implements javax.servlet.Servlet interface.
  • Servlets are initialized by the servlet containers using init() method.
  • Servlets like any other java class can have constructors.
  • Servlet must have a no argument constructor in case it have a non zero arguments constructor.
  • Servlet needs an object of ServletConfig for initialization.
  • Interfaces cannot have constructors.
Can we have Constructors in a Servlet ?
Yes we can, please read How a servlet is initialized by the servlet container. So this article will make clear, why we cannot use a constructor for initializing a servlet.

However there is no problem in having a constructor in a servlet. We can have both argumented and no arguments constructor in a servlet.
Example
What we are trying to do is to create a simple servlet with a constructor and assign a value to a String variable named as "msg".

Servlet : ServletConstructor

package com.ekiras.demo;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ServletConstructor extends HttpServlet {
private static final long serialVersionUID = 1L;

private String msg;

public ServletConstructor() {
super();
System.out.println("HI i am getting initialized");
this.msg = "Servlet Constructor Demo";
}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("Get method --> msg = " + msg);
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}

}

Deployment Descriptor : web.xml

<?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" 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>Test</display-name>
<welcome-file-list>
<welcome-file>ServletConstructor</welcome-file>
</welcome-file-list>

<servlet>
<servlet-name>ServletConstructor</servlet-name>
<servlet-class>com.ekiras.demo.ServletConstructor</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ServletConstructor</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
When we run the above application in the web server like tomcat we will get the following output.
HI i am getting initialized
Get method --> msg = Servlet Constructor Demo
So this makes it clear that there is no problem in having a constructors in a servlet.
Points To Remember
  • Servlets are initialized by the servlet containers.
  • Servlets like any other java class can have constructors.
  • Servlet needs an object of ServletConfig for initialization.
  • Interfaces cannot have constructors.
Why a Servlet is initialized using init() method ?
A servlet is a java class that implements javax.servlet.Servlet interface.A servlet can be given some init parameters in web.xml, called the ServelConfig and some global init parameters called the ServletContext. Thus they both are required at the initialization time of a servlet.

Also Servlet is an interface so it cannot have a constructor, so how will we pass the ServletConfig  object to the servlet for its initialization. This is the reason the Servlet interface have a init(ServletConfig config) method and the implementing class needs to override this method to pass a ServletConfig object to it.

GeneralServlet is an abstract class that implements the Servlet interface for us and helps in initialization of servlets by passing the ServletConfig object to the init() method of the Servlet interface.
Summary : Why we use init() for Servlet initialization
  • For a servlet to be initialized we need a ServletConfig Object.
  • Interfaces cannot have a constructor, so the only way is to get the ServletConfig object in the implementing class of javax.servlet.Servlet interface and then pass it to some method, so we created a method in the Servlet interface and called it init().
  • Now all the classes that implement Servlet interface will have to override init() method and pass a ServletConfig object to this method.
  • This will give the servlet container all necessary control to initialize the servlet.
Points To Remember
  • JSP stands for Java Server Pages.
  • Jsp at compilation time is a servlet and also behaves like a servlet.
  • Jsp serves as views in MVC architecture.
  • Jsp can contain HTML code inside them.
  • They are compiled everytime they are requested.
What is a JSP ?
JavaServer Pages (JSP) is a technology for developing dynamic web pages with dynamic data. You can write java code within a jsp along with the Html using special Jsp tags most of which start with <% and end with %>.

A JavaServerPage component is a type of Java servlet that is designed to fulfill the role of a user interface for a Java web application. Web developers write JSPs as text files that combine HTML or XHTML code, XML elements, and embedded JSP actions and commands.

Using JSP, you can collect input from users through web page forms, present records from a database or another source, and create web pages dynamically. JSP tags can be used for a variety of purposes, such as retrieving information from a database or registering user preferences, accessing JavaBeans components, passing control between pages and sharing information between requests, pages etc.

Sample JSP Structure

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
This is the body of the jsp page.
</body>
</html>

Difference : ServletContext vs ServletConfig

ServletContextServletConfig
Servlet Context is a global configuration for servlets in a an application i.e this is same for all the servlets. Servlet Config is a local configuration for each servlet in an application i.e each servlet has its own servlet configuration that may differ from the servlet config of another servlet.
ServletContext is one per application.ServletConfig is one per servlet.
 It is created at the time of deployment of the web application.It is initialized when a servlet is initialized.
 Its scope is as long as the application is up and running, it will be destroyed when the application is removed from the server. Its scope isand is destroyed when a servlet is destroyed by the servlet container.
 In web.xml it should be declared as <context-param> tag and it should be under <web-app> tag.In web.xml it should be declared as <init-param> under <servlet-class> tag.
ServletContext object will be available even before giving the first requestWe should give request explicitly, in order to create ServletConfig object for the first time
Example


Points To Remember
  • A filter is hit before the servlet or a controller is hit and before the response is sent back to the client.
  • Filters can be used to apply some action on application level.
  • A filter implements the javax.servlet.Filter interface and the primary filter functionality is implemented by the doFilter() method of the filter.
  • Filters can be used to manipulate both requests from client and response from server.
What is a Filter in Java Web Applications ?
A filter is a useful way of performing filtering operations in java web applications bith before a request reaches the backend server and after the response is received from the backend server. A filter is basically used to filter things. Suppose you want to make your application accessible to a particular country, then you can apply IP filtering in your application, similarly we can have various types of filters like
  • Authentication Filters
  • Data compression Filters
  • Encryption Filters
  • Filters that trigger resource access events
  • Image Conversion Filters
  • Logging and Auditing Filters
  • MIME-TYPE Chain Filters
  • Tokenizing Filters
  • XSL/T Filters That Transform XML Content
Filters are deployed in the deployment descriptor file web.xml and then map to either servlet names or URL patterns in your application's deployment descriptor. When the web container starts up your web application, it creates an instance of each filter that you have declared in the deployment descriptor. The filters execute in the order that they are declared in the deployment descriptor.

Example : Implementation of a Filter 

web.xml -

It contains the following
  • Welcome file list
  • Mapping for a filter named MyFilter
  • Mapping for a servlet named DemoServlet
<web-app id="WebApp_ID" version="2.5" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemalocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<display-name>FilterDemo</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<filter>
<filter-name>MyFilter</filter-name>
<filter-class>com.ekiras.filter.MyFilter</filter-class>
<init-param>
<param-name>my-param</param-name>
<param-value>my-param-value</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>MyFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<description></description>
<display-name>DemoServlet</display-name>
<servlet-name>DemoServlet</servlet-name>
<servlet-class>com.ekiras.servlet.DemoServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DemoServlet</servlet-name>
<url-pattern>/DemoServlet</url-pattern>
</servlet-mapping>
</web-app>

Filter - MyFilter

This filter implements the Filter interface and overrides its methods init(), destroy() and doFilter(). We write the filtering logic in the doFilter() method. In this case we are just going to add the init parameters for the filter to the response object inorder to show it on the jsp. filterChain.doFilter() method will take the control to the requested servlet or jsp. After a response has been set the control comes back to this filter.

package com.ekiras.filter;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

// Implements Filter class
public class MyFilter implements Filter {

// To get The FilterConfig object
FilterConfig filterConfig = null;

public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
}

public void destroy() {
}

//doFilter() method is the method where we write filtering logic.
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
throws IOException, ServletException {
servletResponse.setContentType("text/html");

PrintWriter out = servletResponse.getWriter();
// Get init parameter
out.println("my-param (InitParameter): " + filterConfig.getInitParameter("my-param"));
out.println("

Parameters:
");
Enumeration parameterNames = servletRequest.getParameterNames();
if (parameterNames.hasMoreElements()) {
while (parameterNames.hasMoreElements()) {
String name = parameterNames.nextElement();
String value = servletRequest.getParameter(name);
out.println("name:" + name + ", value: " + value + "
");
}
} else {
out.println("---None---
");
}
out.println("
Start Regular Content:


");
// Pass request back down the filter chain
filterChain.doFilter(servletRequest, servletResponse);
out.println("


End Regular Content:
");

}

}

Servlet - DemoServlet

This is a demo servlet and just calls a method performTask() to print a demo message.
package com.ekiras.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 DemoServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

public DemoServlet() {
super();
}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
performTask(request, response);
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
performTask(request, response);
}

private void performTask(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("TestServlet says hi");
}

}

Jsp - index.jsp

This is the jsp that will be hit. This jsp just contains a demo message .
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1">;

<html>
<head>

<title>Test Filter</title>
</head>
<body>
Hi This is My JSP
</body>
</html>