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

Wednesday, January 7, 2015

How to Configure database credential in context.xml file and read it using Hibernate configuration file


Put your context.xml file in the META-INF directory



context.xml

<?xml version="1.0" encoding="UTF-8"?>
<context>
<Resource name="jdbc/dbresource" auth="Container"
        type="javax.sql.DataSource" username="imusername" password="impassword"
        driverClassName="oracle.jdbc.driver.OracleDriver"
        url="jdbc:oracle:thin:@//IP:1521/mydb"
        maxActive="10" maxIdle="4" />
</context>

Hibernate.cfg.xml

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
  
<hibernate-configuration>
    <session-factory>
        <!-- Database connection settings -->
        <property name="current_session_context_class">thread</property>
        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
        <property name="hibernate.connection.datasource">java:/comp/env/jdbc/dbresource</property>
        <property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
<property name="show_sql">false</property>
<property name="format_sql">false</property>
<property name="use_sql_comments">false</property>
<property name="hibernate.jdbc.use_get_generated_keys">true</property>

<!-- Resource mapping -->
<mapping class="com.raj.UserData"/>
  </session-factory>

</hibernate-configuration>


Keep Visiting :)
Write your comment 

Monday, December 22, 2014

Difference between sendRedirect() vs forward()

sendRedirect()

response.sendRedirect();

sendRedirect can let the servlet to move on to a completely new Application Url

Need response object to call the method.

It takes the string url path as an Argument. The value may be a complete url path or a relative path

Created new request and response object to the redirected URL

Assume that the client originally typed in:
http://www.myworld.com/com/raj/info.do

When the request comes into the servlet named “info.do”, 
the servlet calls sendRedirect() with a relative URL that does NOT start with a forward slash:
sendRedirect(“personal/Information.html”); // NO SLASH AT THE BEGINNING

The Container builds the full URL (it needs this for the “Location” header it
puts in the HTTP response) relative to the original request URL:
http://www.myworld.com/com/raj/personal/Information.html

But if the argument to sendRedirect() DOES start with a forward slash:
sendRedirect(/personal/Information.html); // SLASH AT THE BEGINNING

The Container builds the complete URL relative to the web Container itself, instead
of relative to the original URL of the request. So the new URL will be:
http://www.myworld.com/personal/Information.html

sendRedirect() change the Url as per the usage of the string value in the argument

Browser created new request object to the redirected url

.forward()

RequestDispatcher view = request.getRequestDispatcher(“Process.jsp”);
view.forward(request,response);

Need RequestDispatcher object with the string Url value as an Argument

Need to pass request, response object into the forward method

Takes the same (existing) request and response object to the redirected URL

The Url is not getting changed in the browser location bar.

JSP page vs PageContext

page

class: java.lang.Object
page represents the current servlet/jsp object.
page represents 'this'.

pageContext

class: javax.servlet.jsp.PageContext
Use to foward/redirect to particular url.
Use to include particular url.
Use to store/retrieve page level values.
It provides the following list of objects 

ServletRequest
ServletResponse
ServletContext
ServletConfig
HttpSession

application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
request = pageContext.getRequest();
response = pageContext.getResponse();
out = pageContext.getOut(); 


It provides following list of constants

public static final String APPLICATION
public static final int APPLICATION_SCOPE
public static final String CONFIG
public static final String EXCEPTION
public static final String OUT
public static final String PAGE
public static final int PAGE_SCOPE
public static final String PAGECONTEXT
public static final String REQUEST
public static final int REQUEST_SCOPE
public static final String RESPONSE
public static final String SESSION
public static final int SESSION_SCOPE

Object obj = pageContext.getAttribute("BeginnersBook", PageContext. REQUEST_CONTEXT);
Object obj = pageContext.getAttribute("BeginnersBook", PageContext. PAGE_CONTEXT);
Object obj = pageContext.getAttribute("BeginnersBook", PageContext. APPLICATION_CONTEXT);
If it finds the attribute it would assign it to Object obj else it would return Null.

pageContext.setAttribute(“userName”, “RAJ”, PageContext.APPLICATION_CONTEXT);
pageContext.removeAttribute(“userName”, PageContext.APPLICATION_CONTEXT);

Keep Visiting :)
Give your valuable Comment

EL Expression Implicit Objects/Variables


  1. pageContext
  2. pageScope
  3. requestScope
  4. sessionScope
  5. applicationScope
  6. param
  7. paramValues
  8. header
  9. headerValues
  10. cookie
  11. initParam
Keep Visiting :)
Give your valuable Comment


JSP ELEMENTS

PAGE DIRECTIVE 

         <%@ page import=”java.util.*” %>

DECLARATION

          <! int num = 10;>

SCRIPLET

          <% out.println(num) %>

EXPRESSION

          <%=num%>
          <%= pageContext.getAttribute(“foo”) %>

ACTION

          <jsp:include page=”foo.html” />

EL EXPRESSION

           ${pageContext.request.contextPath}
           ${pageContext.foo}

JSP USEBEAN

<jsp:useBean id="" class="" type="" scope="">BODY</jsp:useBean>

*id = Unique Name of the Bean (i.e. Object Name)<br>

 type (reference type) = Type of the Bean<br>

*class (object type) = Class of the Bean<br>

Scope = Scope of the Bean (i.e. page, request, session, application)<br>

i.e. Type id = new Class();


jsp:useBean =  
Create the new object of the specified class. with type specified in the type="" attribute. First it will find the object in the specified scope. and if it is not available then it will create the object and will store the object in the specified scope.  
Body gets evaluated only if new object is getting created.

<jsp:getProperty name=”beanId” property=”name” />

using get tag we can get particular property of the bean object.

<jsp:setProperty name=”beanId” property=”name” value=”Fred” />
using set tag we can set particular property value for the bean object

Keep Visiting :)
Give your valuable Comment



Sunday, December 21, 2014

Enable Disable Scripting and EL Expression in all JSP pages with only Two Line Configuration

<web-app ...>

     <jsp-confi g>
           <jsp-property-group>
           <url-pattern> *.jsp</url-pattern>
           <el-ignored>  true/false <el-ignored>
           <scripting-invalid> true/fals </scripting-invalid>
           </jsp-property-group>
     </jsp-confi g>

</web-app>

Explanation
By configuration above jsp-config element and it subelements in the web.xml file
it will enable/disable the EL expression and Scripting (scriplet,expression and declaration)
in the mentioned url jsp pages.

Give your valuable Comment
Keep Visiting :)

Thursday, December 11, 2014

STRUTS2 client side validation with Wild card usage

struts.xml

<struts>
    
    <constant name="struts.devMode" value="true" />
    <constant name="struts.custom.i18n.resources" value="ApplicationResources" />
     <constant name="struts.enable.SlashesInActionNames" value="true" />

  <package name="policy" extends="struts-default">
        
               
        <global-results>
    <result name="success">/view/commons/Success.jsp</result>
    <result name="error">/view/commons/Error.jsp</result>
    <result name="*"> /view/commons/InvalidResult.jsp</result>
         </global-results>
        
       <action name="*/*/*"  class="com.policydesigner.controller.{1}.{2}CTRL" method="{3}" >                                     
            <result name="create">/view/{1}/{2}Create.jsp</result>
            <result name="update">/view/{1}/{2}Update.jsp</result>                       
            <result name="view">/view/{1}/{2}View.jsp</result>
            <result name="list">/view/{1}/{2}Search.jsp</result>            
        </action>
        
    </package>  
      
</struts>


Action class


import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.interceptor.ParameterAware;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.SessionAware;
import org.apache.struts2.interceptor.validation.SkipValidation;

import com.elitecore.nvsmx.policydesigner.controller.constants.Results;
import com.elitecore.nvsmx.policydesigner.model.policy.PolicyData;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.Preparable;
import com.opensymphony.xwork2.interceptor.annotations.InputConfig;
import com.opensymphony.xwork2.util.logging.Logger;
import com.opensymphony.xwork2.util.logging.LoggerFactory;

/**
 * @author kirpalsinh.raj
 *
 */
public class PolicyCTRL extends ActionSupport implements   ServletRequestAware, SessionAware, ParameterAware, Preparable {

private static final long serialVersionUID = 1L;
private static final String MODULE = PolicyCTRL.class.getSimpleName(); 
private static final Logger LOG = LoggerFactory.getLogger(PolicyCTRL.class);
private HttpServletRequest request;
private Map<String, String[]> parameters;
private Map<String, Object> session;
private String message;
private PolicyData policy = new PolicyData();

/* This method will be used to set a success/failure message.
* Message will be displayed on the same respected page */
public void setMessage(String message){
this.message=message;
}

public String getMessage(){
return message;
}

/* This method gives All the request parameter in Map */
@Override
public void setParameters(Map<String, String[]> thatParameters) {
this.parameters = thatParameters;
}

/* This method gives map of all the attributes stored in current session */
@Override
public void setSession(Map<String, Object> thatSession) {
this.session =  thatSession;
}

/* This method gives the current request object*/
@Override
public void setServletRequest(HttpServletRequest thatRequest) {
this.request = thatRequest;
}

/* In each call to any method, this method will be called first.*/
@Override
public void prepare() throws Exception {
}

/* This method will be used to create the policy.
* If the create page violets the validation rules then @InputConfig(resultName="create") 
* will take the page back to create page by returning "create" string in result*/

@InputConfig(resultName="create")
public String create(){
LOG.info(MODULE, "Method called create()");
setMessage("Policy Created Successfully");
return SUCCESS;
}

/* This method will be used to update the policy.
* If the update page violets the validation rules then @InputConfig(resultName="update") 
* will take the page back to update page by returning "update" string in result*/
@InputConfig(resultName="update")
public String update(){
setMessage("Policy Updated Successfully");
return SUCCESS;
}

public String view(){
setMessage("Viewing Policy");
return Results.VIEW;
}

public String delete(){
setMessage("Policy deleted Successfully");
return SUCCESS;
}


public String initCreate(){
setMessage("Create Policy");
System.out.println("inside initCreate()");
return Results.CREATE;
}

public String initUpdate(){
setMessage("Update Policy");
return Results.UPDATE;
}

public String list(){
return Results.LIST;
}

public PolicyData getPolicy() {
return policy;
}

public void setPolicy(PolicyData policy) {
this.policy = policy;
}

public void validate() {  
System.out.println("Method called validate()");
}
}



VALIDATION FILE

PolicyCTRL-validation.xml
Note: this file must be place at the same location where PolicyCTRL.java file resides

<!DOCTYPE validators PUBLIC "-//Apache Struts//XWork Validator 1.0.2//EN" "http://struts.apache.org/dtds/xwork-validator-1.0.2.dtd">
    
<validators>

<field name="policy.name">
<field-validator type="requiredstring">
<message key="error.policy.name.required"/>
</field-validator>

<field-validator type="stringlength">
<param name="minLength">2</param>
<param name="maxLength">16</param>
<param name="trim">true</param>
<message key="error.length.field" />
</field-validator>
</field>


</validators>

JSP
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<%@ taglib prefix="s" uri="/struts-tags" %>
<%@ page import="com.policydesigner.model.policy.PolicyData"%>

<html>
<head>
<title>Create</title>
<s:head/>
</head>

<body> 
<center>
<div class="msg" >
<s:form action="policy/Policy/create"  validate="true" id="createForm"   name="createForm">
<table>
<tr><td><s:textfield name="policy.name" id="name"  label="Name" /></td></tr>
<tr><td> <s:submit/> </td></tr>
</table>
</s:form>
</div>
</center>  
</body>


</html>

Take Care
Note: see the action attribute of s:form tag 
<s:form action="policy/Policy/create"  validate="true" id="createForm"   name="createForm">

in this tag action attribute contains the values policy/Policy/create 
this will be map with the wild cards used in the struts.xml file.
and remember to not begin the action attribute value with slash "/"

not do this :  action="/policy/Policy/create" because it will make a call to the validate method of the respected action class. means it will load the page.

and action ="policy/Policy/create" : this will not load the page and it will perform the client side validation withe the generated java script. 

:) Keep Visiting :)


Wednesday, November 26, 2014

How to define Error Page in web.xml


Exception Based

<error-page>
<exception-type>java.lang.ArithmeticException</exception-type>
<location>/ExceptionError.jsp</location>
</error-page>

HTTP status code based 

<error-page>
<error-code>404</error-code>
<location>/NotFound.jsp</location>
</error-page>

Wednesday, November 19, 2014

Include directive vs jsp:include action


Include directive

include directive should be use to include the static contents
which is not getting changed frequently.

It includes the content at the translation time

example
<%@include file="/jsp/core/includes/common/Footer.jsp" %>

<jsp:include> action tag

include action tag is used to include the content which is getting changeg frequently

it includes the content at the runtime

example
<jsp:include page="/jsp/data/dynamic.jsp"/>

Tuesday, November 18, 2014

HTTP Status code Range


1) 100 to 199 (Informational)

This range include the Informational codes about the kind of action client should use or respond

2) 200 to 299 (Request success)

This range include the success codes that indicates the success of the request

3) 300 to 399 (Request File is moved)

This range include the code to indicate that the particular document/file location is moved to another location

4) 400 to 499 (Client side Error)

This range codes indicates the error generated by the client side

5) 500 to 599 (Server side Error)

This range codes indicates the error generated by the server side

How to use

To set the status code one should  use the predefined constants for the respective status code using the method :  response.setStatus(response.SC_ABC_XYZ);


Status Code
Purpose
100-199
Informational
200-299
Request was successful
300-399
Request file has moved.
400-499
Client error
 500-599
Server error.



Some Status Code with their Short Meaning

100 : Continue

200 : OK
202 : Accepted
204 : No Content
205 : Reset Content

301 : Moved Permanentely
302 : Found
303 : See Other
304 : Not Modified


400 : Bad Request
: Bad syntax of the request

401 : Unauthorized
: client tries to access the password protected resource, 

403 : Forbidden
: server refuse to supply the requested resource

404 : Not Found
: when the requested resource is not found on the server.

405 : Method Not Allowed
: put,trace,delete,options if server doesnt support the method requested.

415 : Unsupported Media Type
: request contain the document that the server doesnt know how to handle.

417 : Expectation Failed
: request ask to process some document with 100 code in header, in this request response
 server can respond with code 417


500 : Internal Server Error
: When Server is Confused.

501 : Not Implemented
: doesnt support the functionality to fullfill the request.

503 : Service Unavailable
: When server is not able to fullfill the request service. because of overloading or maintenance or etc




How to Include Header and Footer in all Jsp files Dynamically


Include following tag in your web.xml file with your files proper path
it will include Header.jsp in header of all jsp file and Footer.jsp in footer of all the jsp files

<jsp-config>
<jsp-property-group>
<url-pattern>*.jsp</url-pattern>
<include-prelude>/view/commons/Header.jsp</include-prelude>
<include-coda>/view/commons/Footer.jsp</include-coda>
</jsp-property-group>
</jsp-config>

Friday, November 7, 2014

FILTER vs INTERCEPTOR

FILTERS
0)  Filter is an Interface
1)  Filters are Java Components. somewhat equivalent to servlet.
2)  Filters intercepts and process the request before it sent to the actual servlet.
- on request object filter can do security checks
- filter can do some log work
- filter can change the request parameter
- filter can reformat the request headers 
- filter can take some decision based on request parameters
3)  Filter intercepts the response received from the servlet before it sent to the end user.
- filter can do some log work for the response
- filter can change the response stream

4)  Filters are configurable in DD (Deployement Descriptor)
5)  Container decides when to invoke which filter
6)  Filters have init(), destroy() and doFilter() methods
7)  One request can be intercepted by multiple filters
8)  Every filter must implemens the Filter Interface
9)  Filter interface is in package "import javax.servlet.Filter;"
10) doFilter(ServletRequest request, ServletResponse response, FilterChain fchain) 
11) As per the declaration of filter in the DD the filter chain will be prepared for the similar url-mapping and servlet-names.
12) The Filter chain concept can also be called a filter stack.

INTERCEPTORS
0)  Interceptor is an Interface
1)  Interceptors are struts2 components similar to Filter
2)  Interceptors intercepts the request before it reach to the servlet and can do the same      
     work as filter can do.
3)  Interceptors intercepts the respons before it reach to the end user and can perform the 
     same work as filter can do.
4)  Interceptors can be declared in the struts specific configuration file (struts.xml)
5)  Interceptors are can be called action specific
6)  Programmer can be define in specific order to create stack of the interceptor. (as filter 
    chaining )
7)  Prepared stack can be used at multiple times for the specified actions
8)  Struts2 provides many useful interceptors (i.e 
     http://struts.apache.org/release/2.3.x/docs/interceptors.html)
9)  To create interceptor we need to implement Interceptor interface
10) Interceptor have three methods void init(),  void destroy() and Strinng 
      intercept(ActionInvocation acIn)
11) package : "import com.opensymphony.xwork2.interceptor.Interceptor;"
12) Interceptor can exclude and include specific method's execution.

I think this is enough basic information about FILTER and INTERCEPTOR :)

KEEP VISITING :) GIVE YOUR RATING AND COMMENTS

Scrum and Scrum master

Scrum  Scrum is a framework which helps a team to work together.  It is like a rugby team (the scrum name comes from rugby game). Scrum enco...