Showing posts with label JSP. Show all posts
Showing posts with label JSP. Show all posts

Thursday, January 8, 2015

STRUTS2 JQURY PLUGIN + STRUTS2 JSON PLUGIN EXAMPLE

OUTPUT




JSP


<%@taglib uri="/struts-jquery-tags" prefix="sj"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<html>
<head>
<sj:head jquerytheme="flick" jqueryui="true" />
</head>
<script>
$(document).ready(function() {
$('#states').change(function(event) {
var state = $("select#states").val();
$.getJSON('/nvsmx/jsonSelectAction.action', {
stateName : state
}, function(jsonResponse) {
$('#message').text(jsonResponse.message);
var select = $('#cities');
select.find('option').remove();
$.each(jsonResponse.cityMap, function(key, value) {
$('<option>').val(key).text(value).appendTo(select);
});
});
});
});
</script>
<body>
<h1>Welcome to AJAX + JSON</h1>

<sj:tabbedpanel id="localtabs" cssClass="list">
<sj:tab id="tab1" target="tone" label="Ajax" />
<sj:tab id="tab2" target="ttwo" label="getJSON" />
<sj:tab id="tab3" target="tthree" label="JSON-ACTION" />
<sj:tab id="tab4" target="tfour" label="JSON-SELECT" />

<div id="tone">
<sj:div id="resultDiv">
</sj:div>
<s:form id="form" namespace="/" action="ajax/Ajax/ajax" method="post">
<s:textfield id="id" name="id" value="1" label="ID" />
<br>
<sj:submit value="Submit" targets="resultDiv" />
</s:form>
</div>

<div id="ttwo">
<s:form id="form2" namespace="/" action="jsonMethoAction"
method="post">
<sj:submit value="JSON METHOD" />
</s:form>
</div>

<div id="tthree">
<s:form id="form3" namespace="/" action="jsonAction" method="post">
<sj:submit value="JSON ACTION" />
</s:form>
</div>
<div id="tfour">
<s:url var="remoteurl" namespace="/" value="/jsonAction.action"/>
<sj:select href="%{remoteurl}"
       id="states"
       name="states"
       list="stateList"
       emptyOption="false"
       headerKey="-1"
       headerValue="Please Select a Language"/>
       
         <br><br><div id="message"></div>        
       <br><s:select id="cities" name="cities" list="{'Select State'}" label="City" />
</div>

</sj:tabbedpanel>

</body>
</html>

CONTROLLER/ACTION
;
1) 
package com.el.nvsmx.pd.controller.json

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.opensymphony.xwork2.Action;

public class JsonCTRL {
private List<String> stateList = new ArrayList<String>();
private Map<String, String> cityMap = new HashMap<String, String>();
private String stateName;
private String message;
 
    public String execute() {
    System.out.println("CALLED EXECUTE()");    
    if ("Gujarat".equals(stateName)) {
setMessage("Welcome to GUJARAT");
getCityMap().put("1", "Anand");
getCityMap().put("2", "V.V.Nagar");
getCityMap().put("3", "Baroda");
getCityMap().put("4", "Ahmedabad");

} else if ("Rajasthan".equals(stateName)) {
setMessage("Welcome to Rajasthan");
getCityMap().put("1", "Jaipur");
getCityMap().put("2", "Udepur");
}  
    return Action.SUCCESS;
}
public String getJSON(){
getStateList().add("Gujarat");
getStateList().add("Rajasthan");
        return execute();
    }
public JsonCTRL(){
}


public String getStateName() {
return stateName;
}

public void setStateName(String stateName) {
this.stateName = stateName;
}

public String getMessage() {
return message;
}

public void setMessage(String message) {
this.message = message;
}

public Map<String, String> getCityMap() {
return cityMap;
}

public void setCityMap(Map<String, String> cityMap) {
this.cityMap = cityMap;
}

public List<String> getStateList() {
return stateList;
}

public void setStateList(List<String> stateList) {
this.stateList = stateList;
}
}

2)
package com.el.nvsmx.pd.controller.ajax;

import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;

import com.elitecore.nvsmx.policydesigner.constants.Results;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.Preparable;

public class AjaxCTRL extends ActionSupport implements ServletRequestAware,
ServletResponseAware, Preparable {

private static final long serialVersionUID = 1L;
private static final String MODULE = AjaxCTRL.class.getSimpleName();
private HttpServletRequest request;
private HttpServletResponse response;
private Map<String, String> stateMap = new LinkedHashMap<String, String>();
private List<String> dataList = new ArrayList<String>();

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

public String getJSON() {
dataList.add("First");
return "Hello i am Json Result";
}
public String ajax() {

String key = request.getParameter("id");
String result = stateMap.get(key);
System.out.println("Name: " + result);
if (result == null) {
result = "Unknown";
}
try {
response.getWriter().write("your are in " + result + " state of INDIA.");
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
e.printStackTrace();
}
return null;

}

@Override
public void setServletRequest(HttpServletRequest request) {
this.request = request;
}

@Override
public void setServletResponse(HttpServletResponse response) {
this.response = response;
}

@Override
public void prepare() throws Exception {
System.out.println("Called prepare()");
if (stateMap.size() == 0) {
System.out.println("Initializing Map");
stateMap.put("1", "Kerala");
stateMap.put("2", "Tamil Nadu");
stateMap.put("3", "Jammu Kashmir");
stateMap.put("4", "Assam");
stateMap.put("5", "Gujarat");
stateMap.put("6", "Goa");
stateMap.put("7", "Maharastra");
stateMap.put("8", "Rajasthan");
}
}

}

STRUTS.XML 

<package name="jsonnvsmx" namespace="/" extends="json-default">
<action name="jsonMethoAction" class="com.el.nvsmx.pd.controller.ajax.AjaxCTRL">
<result type="json" />
</action>

<action name="jsonAction" class="com.el.nvsmx.pd.controller.json.JsonCTRL">
<result type="json" />
</action>
<action name="jsonSelectAction" class="com.el.nvsmx.pd.controller.json.JsonCTRL">
<result type="json" />
</action>
<action name="ajaxJsonAction" class="com.el.nvsmx.pd.controller.json.JsonCTRL">
<result name="success" type="json" >/view/commons/Success.jsp</result>
</action>
</package>

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 :)

Wednesday, November 26, 2014

Define Error page in Java web App



Page which will display the Error detail : ErrorPage.jsp

<%@ page isErrorPage=”true” %>
<html>
<body>
<strong>I am Error Page.</strong><br>
Error is : ${pageContext.exception}<br>
</body>
</html>

Page which will cause Error : Hello.jsp

<%@ page errorPage=”ErrorPage.jsp” %>
<html>
<body>
<%=1/0%>
</body>
</html>

Web.xml

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

<error-page>
          <error-code>java.lang.ArithMeticException</error-code>
           <location>/jsp/ErrorPage.jsp</location>
</error-page>

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...