Sunday, November 6, 2016

Eclipse setup for JEE

1. Install apache server
2. Go to Eclipse->Windows-> Preferences->Server->Runtime Environment
3. Click Add
4. Select Apache server 7.0
5. Click next and download and install
6. Right click on the server. Go to properties. Then click on the Switch Location.
7. Double click on the Tomcat server. Select 'Use tomcat installation' instead of 'Use workspace metadata'.
8. Restart the apache server.

Thursday, January 21, 2016

Configuring Git in windows

1. Download Git and install
 
    https://git-scm.com/download/win

2. Add path to git to PATH environment variable.

    C:\Program Files\Git\cmd

Wednesday, January 13, 2016

JSP Elements

JSP Elements

JSP page is converted to Servlet java class. Therefore following elements in JSP will be copied in Servelet. Suppose there is a JSP page named "DisplayCounter.jsp". It will be converted to DisplayCounter_jsp class when it is placed in container. DisplayCounter_jsp will be extended from HttpServlet. Inside this class _jspService() method will be created and all the java code will be populated there.
  • Directives
    Page directive
    <%@ page import="java.util.*" %>
    Page directive defines page-spacific properties such as character encoding, the content type, whether this page should have the implicit session object.
    Attributes in page directives are
    • import
    • isThreadSafe
    • contentType
    • isELIgnored
    • isErrorPage
    • errorPage
    Taglib directive
    <%@ taglib tagdir="/WEB-INF/tags/cool" prefix="cool" %>
    It defines tag libraries available to the JSP.
    Include directive
    <%@ include file="wickedHeader.html" %>
    It defines text and code that gets added into the current page at translation time. This lets you build reusable chunks withou having to duplicate all that code in each JSP.
  • Declaration
    <%! int count=0; %>
    Declare count will be a member variable. You can define method or member variable.
  • Scriptlet
    <% out.println(count); %>
    Inside the scriptlet, you can write java code which will be copeid to converted servelet.
  • Expression
    <%=count+1 %>
  • Jsp Comment
    `<%-- --%>

JSP Implicit objects

API Implicit Object
JSPWriter-------------------out
HttpServletRequest------request
HttpServletResponse----response
HttpSession----------------session
ServletContext------------application
ServletConfig--------------config
Throwable------------------exception
PageContext--------------pageContext
Object-----------------------page

Attributes in a JSP

Application

application.setAttribute("username",user);

Request

request.setAttribute("username",user);

Session

session.setAttribute("username",user);

Page

pageContext.setAttribute("username",user);

Attributes can be accessed through PageContext

There are 4 PageContexts
APPLICATION_SCOPE
PAGE_SCOPE
REQUEST_SCOPE
SESSION_SCOPE
We can pass this in overloaded method of pageContext.setAttribute or pageContext.getAtribute as a 3rd parameter.
  • Accessing a page-scoped attribute
    <% pageContext.setAttribute("username",username); %>
    <%= pageContext.getAttribute("username",username); %>
  • Accessing a session-scoped attribute
    <% pageContext.setAttribute("username",username, PageContext.SESSION_SCOPE); %>
    <%= pageContext.getAttribute("username",username, PageContext.SESSION_SCOPE); %>
  • Accessing a application-scoped attribute
    <% pageContext.setAttribute("username",username, PageContext.APPLICATION_SCOPE); %>
    <%= pageContext.getAttribute("username",username, PageContext.APPLICATION_SCOPE); %>
  • Accessing a page-scoped attribute
    <% pageContext.setAttribute("username",username, PageContext.PAGE_SCOPE); %>
    <%= pageContext.getAttribute("username",username, PageContext.PAGE_SCOPE); %>
  • Accessing a request-scoped attribute
    <% pageContext.setAttribute("username",username, PageContext.REQUEST_SCOPE); %>
    <%= pageContext.getAttribute("username",username, PageContext.REQUEST_SCOPE); %>

Tuesday, January 12, 2016

How to use Maven

Advantages of using Maven project.

1. All the required jar are added.
2. It removes dependancy of one jar on another.
3. It helps to create project file structure.
4. It helps to build, publish and deploy the project.

How to setup Maven.

1. Download the latest binary zip archive from https://maven.apache.org/download.cgi.

2. Extract it.

3. Add following environment variables
M2_HOME=C:\Program Files\Apache Software Foundation\apache-maven-3.3.3
M2=%M2_HOME%\bin
MAVEN_OPTS=-Xms256m -Xmx512m
Add %M2%; to PATH environment variable

4. Now open the command prompt and run the following command.
   >mvn --version
If path is set ok, then you will see the output.


Creating a project.
1. create a directory
>mkdir myapp

2. mvn archetype:generate

Arctype is project structure
Group id is package name 
artifact id is Application name.
Version is version number
Package is what kind of packaging would be. like jar, war or ear.

When you select any structure it creates that file structure and pom.xml. In the pom.xml, dependancy jars are mentioned. Following command build project.

3. 
mvn package
mvn test
mvn compile
mvn build
mvn install
mvn clean

Suppose you added import org.sl4j.*; in your code.
Now if you compile the application (mvn compile), it will fail.
So you have to go to http://mvnrepository.com/ and search for slf4j. Click on the api link. Click on the version you like. Then copy the dependancy snippet and paste in pom.xml of the project under dependencies element. Then compile will be successful.

To add maven plugin in Eclipse:
help->Install->Work with (--All Available Sites--). Type maven. Select General Purpose Tools with m2e Maven Integration for Eclipse . Then install it.
You can do the same with Maven eclipse plugin. Create a Maven project. Then you can choose archetype. You can compile, build and everything.

Cookie

Server sends the cookie to client and client sends it back with each subsequent request. Session cookies vanishes when the client's browser quits, but it is possible to set set cookies lifetime.

Creating a new cookie

Cookie cookie=new Cookie("username","parvez");

Setting time to live

cookie.setMaxAge(30);

Sending cookie to client

response.addCookie(cookie);

Getting cookie from client's request

Cookie[] cookies=request.getCookies();
for(int i=0;i<cookies.length;i++
 {
  Cookie cookie=cookies[i];
  out.println(cookie.getName()+" "+cookie.getValue());
 }

URL Rewriting

Sometimes cookies are disabled in client side. Therefore it session id will not be used in http request. In that case, session id will has to be passed to client by adding session id at the end of each URL. This is called URL rewriting.
URL rewriting works only on dynamically generated URL, not on the static web page.
response.encodeURL("/Test.do");
If you want to redirect the request to different URL but keeping the same session, use the following encoding.
response.encodeRedirectURL("/Test.do");

Session management

HTTP protocol is stateless. To make it state-full, server creates a HttpSessoin for each session. Container recogniges each client by sessionid. Session-ID can be found in jsessionid in HTTPResponse. Server replies with session-id, when the client sends the request first time. Sesson-id is put in the Cookie. For the sub sequent request/response, cookie is being exchanged.
Sending a session cookie in the RESPONSE
HttpSession session=request.getSession();
Getting the session ID from the REQUEST
HttpSession session=request.getSession();
Session also can be created, with HTTP session related listener's event.
Interfaces are
  • HttpSessionListener -- Lifecycle
  • HttpSessionAttributeListener -- Changes to attributes
  • HttpSessionActivationListener -- Session migration
  • HttpSessionBindingListener -- Object binding
  • HttpSessionIdListener -- Changes to id
Checking a session is created or already exists
session.isNew()
How to get pre-existing session
HttpSession session=request.getSession(false); //Passing false means it returns pre-existed session or null

if (session == null)
{
  session= request.getSession(); // create a new session
}
getSession() and getSession(true) is same. It creates a new session if session does not exist.

Key HttpSession Method

getCreationTime - Returns the time the session was first created
getLastAccessedTime - Returns the last time time the container got a request with this session ID (in milliseconds)
setMaxInactiveInterval - Specifies the maximum time in seconds that is allowed between clients requests
getMaxInactiveInterval - Returns the maximum time in seconds that is allowed between clients requests
invalidate - Ends the session

Setting session timeout

3 ways a session can die
  • It time out
  • You call invalidate() on the session object
  • The application goes down.

Configuring session time out

setting session timeout in DD in minutes
<session-config> <session-timeout>15</session-timeout> </session-config>
setting timeout for a specific session in seconds (eg: 20minutes)
session.setMaxInactiveInterval(20*60);
If you pass 0 as parameter, session will be invalidate immediately.

RequestDispatcher

Request is forwarded from Servlet to JSP using RequestDispatcher. This interface has two method, forward and include. Forward method is used to forward request to the resource (servlet and JSP).
Getting a RequestDispatcher from a ServletRequest. It is suitable for accessing JSP/Servlet in same web application.
RequestDispatcher view=request.getRequestDispatcher("result.jsp");
// It means the result.jsp is relative to current HTTP request
Getting a RequestDispatcher from a ServletContext. It is suitable for accessing JSP/Servlet in other web application.
RequestDispatcher view=getServletContext().getRequestDispatcher("/result.jsp");
//It means that result.jsp is relative to root of the ServletContext. Slash (/) must be used.
Calling forward() on a RequestDispatcher.
view.forward(request,response);

Attributes in Servlet

An attribute is an object set into one of three other servlet API objects
1. ServletContext: All the servlet/JSP can set/get data. It is not thread safe.
2. HttpServletRequest (or ServletRequest):Servlet can set data and JSP view can get data
3. HttpSession: For each session, servlets/JSP have access. Session can persists across multiple requests from the same client. Session attribute is not thread safe. For example: Shopping cart.
As ServletContext is not thread safe, it is recommended to make call to get/set method under synchronized block.
To be noted that, all other servlet should synchronizes on the ServletContext.
synchronized(getServletContext())  
{  
  getServletContext().setAttribute("adminEmail","admin@email.com");  
  out.println(getServletContext().getAttribute("adminEmail"));  
} 
As Session is not thread safe, it is recommended to make call to get/set method under synchronized block.
To be noted that, all other servlet should synchronizes on the Session.
HttpSession session=request.getSession();
synchronized(session)  
{  
  session.setAttribute("supportEmail","support@email.com");  
  out.println(session.getAttribute("supportEmail"));  
} 

Saturday, January 9, 2016

Servlet accessing init parameters

There are two types of init parameters.

1. Context init parameter which is accessible from all the servlets in a app. It can be accessed by following code.

getServletConfig().getServletContext().getInitParameter("companyName");

or

getServletContext().getInitParameter("companyName");


Deployment descriptor web.xml

<?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>TestInitParameters</display-name>
   <context-param>
  <param-name>companyName</param-name>
  <param-value>Scotia bank Ltd</param-value>
  </context-param>
</web-app>



2. Servlet init paramters which is accessible from a servlet for which it is declared. It can be accessed by following code.

getServletConfig().getInitParameter("supportEmailAddress");



annotation:

@WebServlet(
urlPatterns = { "/TestInitParameter" },
initParams = {
@WebInitParam(name = "supportEmailAddress", value = "support@gmail.com")
})