Friday, August 29, 2014

How to create multilevel menu's in JSP using recursion..

There was a requirement where in I need to create multi-level menu's in a JSP

A role has certain set of Privileges.
Each privilege may or may not have child privileges..

Where Privilege has child privileges, it was desired to display a sub menu..

So this is how I have achieved...
First thing you need to know about this is how to create multi level menu's using HTML and CSS.
(http://javakafunda.blogspot.in/2014/08/how-to-create-multi-level-menus-using.html)

and once you learn that you'll have to use recursion in JSP to achieve the above requirement.

I'll just put the core logic here which is the base of this..

Create a parent jsp (lets say LoginSuccess.jsp)

<ul id="nav">
<c:forEach var="role" items="${userDbObject.roles}"> 
  <li><a href="#item1">${role.roleName}</a>
   <ul> 
   <c:forEach var="priv" items="${role.privileges}">
     <c:set value="${priv}" var="myPriv" scope="request"/>
     <jsp:include page="showPrivileges.jsp"/>
   </c:forEach>
   </ul>
 </li>   
</c:forEach>
</ul>


Create a showPrivileges.jsp as follows:

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<c:if test="${empty myPriv.childPrivileges}">
  <c:set var="url" value="${myPriv.privUrl}" />
  <c:if test="${not empty url}">
   <li><a href="${url}" >${myPriv.privilegeName}</a></li>
  </c:if>
  <c:if test="${empty url}">
   <li><a href="unimplemented.jsp" >unimplemented.jsp</a></li>
  </c:if>
</c:if>
<c:if test="${not empty myPriv.childPrivileges}">
   <li><a href="#" >${myPriv.privilegeName}</a>
    <ul> 
    <c:forEach var="childPriv" items="${myPriv.childPrivileges}">
      <c:set value="${childPriv}" var="myPriv" scope="request"/>
      <jsp:include page="showPrivileges.jsp"/>
    </c:forEach>
    </ul>
   </li>
</c:if>

Thursday, August 28, 2014

How to create multi-level menu's using HTML and CSS

Create a style.css as follows


Create body of your HTML as follows


And the output will look like:










Tuesday, August 26, 2014

How to implement a self join in hibernate

Source : http://viralpatel.net/blogs/hibernate-self-join-annotations-one-to-many-mapping/

We have a create table in the database.

CREATE TABLE employee (
employee_id NUMBER(10) NOT NULL,
firstname VARCHAR2(50) NULL DEFAULT NULL,
lastname VARCHAR(50) NULL DEFAULT NULL,
manager_id NUMBER(10) NULL DEFAULT NULL,
PRIMARY KEY ('employee_id'),
CONSTRAINT 'FK_MANAGER' FOREIGN KEY ('manager_id') REFERENCES 'employee' ('employee_id')
);

Here in Employee table, we defined a column MANAGER_ID which is mapped to the same table’s primary key. Thus for each employee we will store its manager’s id also. Manager will be yet another employee in this table

We will be using annotations to implement this in hibernate:


@Entity
@Table(name="EMPLOYEE")
public class Employee {
    @Id
    @Column(name="EMPLOYEE_ID")
    @GeneratedValue
    private Long employeeId;
     
    @Column(name="FIRSTNAME")
    private String firstname;
     
    @Column(name="LASTNAME")
    private String lastname;
     
    @ManyToOne(cascade={CascadeType.ALL})
    @JoinColumn(name="manager_id")
    private Employee manager;
 
    @OneToMany(mappedBy="manager")
    private Set<Employee> subordinates = new HashSet<Employee>();
 
    public Employee() {
    }
 
    public Employee(String firstname, String lastname) {
        this.firstname = firstname;
        this.lastname = lastname;
    }
         
    // Getter and Setter methods
}


Note that in Employee entity class, we defined two new attributes: Employee manager and Set subordinates. Attribute manager is mapped with @ManyToOne annotation and subordinates is mapped with @OneToMany. Also within @OneToMany attribute we defined mappedBy="manager" making manager as the relationship owner and thus which manages the foreign relationship within table.

Also the annotation @JoinColumn is defined on manager making it the relationship owner. @JoinColumn defines the joining column which in our case is manager_id.

Monday, August 25, 2014

How to integrate Spring and Hibernate

Here are the few tips I have gathered on how to integrate spring and hibernate.

Create your bean.xml something like this...


The list of jars that you might need are
  1. antlr-2.7.6.jar
  2. asm-1.5.3.jar
  3. axis2-spring-1.6.1.jar
  4. cglib-2.1_3.jar
  5. commons-collections-3.1.jar
  6. commons-dbcp-1.4.jar
  7. commons-logging-1.0.4.jar
  8. commons-pool-1.6.jar
  9. dom4j-1.6.1.jar
  10. hibernate-3.2.0.ga.jar
  11. hibernate-3.2.6.jar
  12. hibernate-annotations-3.4.0.GA.jar
  13. hibernate-commons-annotations-3.1.0.GA.jar
  14. hibernate-core-3.3.0.SP1.jar
  15. hibernate-entitymanager.jar
  16. hibernate-jpa-2.0-api-1.0.0.Final.jar
  17. jta-1.1.jar
  18. log4j-1.2.14.jar
  19. ojdbc14.jar
  20. org.springframework.asm-3.0.0.RELEASE.jar
  21. org.springframework.beans-3.0.0.RELEASE.jar
  22. org.springframework.context-3.0.0.RELEASE.jar
  23. org.springframework.core-3.0.0.RELEASE.jar
  24. org.springframework.expression-3.0.0.RELEASE.jar
  25. org.springframework.jdbc-3.0.0.RELEASE.jar
  26. org.springframework.orm-3.0.0.RELEASE.jar
  27. org.springframework.web.servlet-3.0.1.RELEASE-A.jar
  28. slf4j-api-1.6.1.jar
  29. spring-tx-3.0.0.RELEASE.jar


Wednesday, July 30, 2014

Two player game program - e.g. TIC TAC TOE...

This is an abstract State class

Extend the above State class and give some implementations...as follows:
Lets assume the class to be TttState...
We'll override the abstract methods of the parent class State..

Give a member variable that'll hold the current state of your game...In my case, I have taken it as array..

// This variable is going to hold the current state of your game.
 // It can be any depending on your game requirements...
 private String state[][] = null ;

Give a copy constructor

public TttState(State x)
 {
  TttState tState = (TttState)x;
  state = new String[3][3];
  for(int i=0;i<=2; i++)
  {
   for(int j=0; j<=2;j++)
   {
    this.state[i][j]=tState.state[i][j];
   }
  }
  this.turn = x.getTurn();
 }
Give a default constructor
public TttState() {
  state = new String[3][3];
  for(int i=0;i<=2; i++)
  {
   for(int j=0; j<=2;j++)
   {
    this.state[i][j]="";
   }
  }
  this.turn = "X";
 }
Give a toString implementation, so that you can print the current state
public String toString()
 {
  StringBuilder sb = new StringBuilder("");
  for(int i=0;i<=2; i++)
  {
   for(int j=0; j<=2;j++)
   {
    if(state[i][j].equals(""))
    {
     sb.append("-");
    }
    else
    {
     sb.append(state[i][j]);
    }
    sb.append("\t");
   }
   sb.append("\n");
  }
  return sb.toString();
 }
Override the method getWinner() as follows
public String getWinner()
 {
  // ROW CHECK BEGINS 
  if(state[0][0].equalsIgnoreCase("X") && state[0][1].equalsIgnoreCase("X") && state[0][2].equalsIgnoreCase("X"))
  {
   return "X";
  }
  if(state[0][0].equalsIgnoreCase("O") && state[0][1].equalsIgnoreCase("O") && state[0][2].equalsIgnoreCase("O"))
  {
   return "O";
  }
  if(state[1][0].equalsIgnoreCase("X") && state[1][1].equalsIgnoreCase("X") && state[1][2].equalsIgnoreCase("X"))
  {
   return "X";
  }
  if(state[1][0].equalsIgnoreCase("O") && state[1][1].equalsIgnoreCase("O") && state[1][2].equalsIgnoreCase("O"))
  {
   return "O";
  }
  if(state[2][0].equalsIgnoreCase("X") && state[2][1].equalsIgnoreCase("X") && state[2][2].equalsIgnoreCase("X"))
  {
   return "X";
  }
  if(state[2][0].equalsIgnoreCase("O") && state[2][1].equalsIgnoreCase("O") && state[2][2].equalsIgnoreCase("O"))
  {
   return "O";
  }
  
  // COLUMN CHECK BEGINS 
  if(state[0][0].equalsIgnoreCase("X") && state[1][0].equalsIgnoreCase("X") && state[2][0].equalsIgnoreCase("X"))
  {
   return "X";
  }
  if(state[0][0].equalsIgnoreCase("O") && state[1][0].equalsIgnoreCase("O") && state[2][0].equalsIgnoreCase("O"))
  {
   return "O";
  }
  if(state[0][1].equalsIgnoreCase("X") && state[1][1].equalsIgnoreCase("X") && state[2][1].equalsIgnoreCase("X"))
  {
   return "X";
  }
  if(state[0][1].equalsIgnoreCase("O") && state[1][1].equalsIgnoreCase("O") && state[2][1].equalsIgnoreCase("O"))
  {
   return "O";
  }
  if(state[0][2].equalsIgnoreCase("X") && state[1][2].equalsIgnoreCase("X") && state[2][2].equalsIgnoreCase("X"))
  {
   return "X";
  }
  if(state[0][2].equalsIgnoreCase("O") && state[1][2].equalsIgnoreCase("O") && state[2][2].equalsIgnoreCase("O"))
  {
   return "O";
  }
  // DIAGNONAL CHECKS 
  if(state[0][0].equalsIgnoreCase("X") && state[1][1].equalsIgnoreCase("X") && state[2][2].equalsIgnoreCase("X"))
  {
   return "X";
  }
  if(state[0][0].equalsIgnoreCase("O") && state[1][1].equalsIgnoreCase("O") && state[2][2].equalsIgnoreCase("O"))
  {
   return "O";
  }
  
  if(state[0][2].equalsIgnoreCase("X") && state[1][1].equalsIgnoreCase("X") && state[2][0].equalsIgnoreCase("X"))
  {
   return "X";
  }
  if(state[0][2].equalsIgnoreCase("O") && state[1][1].equalsIgnoreCase("O") && state[2][0].equalsIgnoreCase("O"))
  {
   return "O";
  }  
  int nonBlank = 0;
  for(int i=0;i<=2;i++)
  {
   for(int j=0;j<=2;j++)
   {
    if(!state[i][j].equals(""))
    {
     nonBlank++;
    }
   }
  }
  if(nonBlank==9)
  {
   return "draw";
  }
  
  return "";
 }
Override the method isGameOver()
public boolean isGameOver()
 {
  if(!getWinner().equals("") && !getWinner().equals("draw"))
  {
   return true;
  }
  else
  {
   return false;
  }
 }
Override the method getChildren()
@Override
 public List<State> getChildren() {
  List<State> children = new ArrayList<State>();
  if(turn.equals("X"))
  {
   for(int i=0;i<=2; i++)
   {
    for(int j=0; j<=2;j++)
    {
     if(state[i][j].equals(""))
     {
      TttState child = new TttState(this);
      child.state[i][j]="X";
      String newTurn = "O";
      child.setTurn(newTurn);
      children.add(child);
     }
    }
   }
  }
  else
  {
   for(int i=0;i<=2; i++)
   {
    for(int j=0; j<=2;j++)
    {
     if(state[i][j].equals(""))
     {
      TttState child = new TttState(this);
      child.state[i][j]="O";
      String newTurn = "X";
      child.setTurn(newTurn);
      children.add(child);
     }
    }
   }
  }
  return children;
 }
Override getTurn and setTurn
public String getTurn() {
  return turn;
 }

 public void setTurn(String turn) {
  this.turn = turn;
 }
Your main program will look something like this:
public static void main(String args[])
 {
  TttState x = new TttState();
  System.out.println("WINNER : " + x.getWinner());
  x.setTurn("X");
  Scanner sc = new Scanner(System.in);
  while(!x.isGameOver())
  {
   String xIndex = sc.nextLine();
   String yIndex = sc.nextLine();
   int xint = Integer.parseInt(xIndex);
   int yint = Integer.parseInt(yIndex);
   x.getState()[xint][yint]="X";
   x.setTurn("O");
   int minScore = 100;
   List<State> children = x.getChildren();
   TttState bestMove = new TttState(x);
   for(State child : children)
   {
    int childScore = child.minimax();
    // We are using < because we are always evaluating
    // the best move from the options that O player has....
    if(childScore < minScore)
    {
     minScore = childScore;
     bestMove = (TttState)child;
     bestMove.setTurn("X");
    }
   }
   System.out.print(bestMove);
   x = bestMove;
  }
  System.out.println("GAME OVER...");

 }


Monday, July 7, 2014

Things to remember while creating Custom Exception in Java

Things to remember while creating Custom Exception in Java

1) Don’t' use Exception to control application behaviour. Exception handling is very expensive as it require native calls to copy stacktrace, each time exception is created.

2) While creating custom exception, prefer to create an unchecked, Runtime exception than a checked exception, especially if you know that client is not going to take any reactive action other than logging.

3) If your custom exception is created by passing another exception, then always contain original Exception as source; use constructor which takes Exception rather than only message String.

4) Apart from providing default no argument constructor on your custom Exception class, consider providing at least two more constructors, one which should accept a failure message and other which can accept another Throwable as cause.

5) If possible avoid creating custom Exception and re-use existing, standard Exception classes from JDK itself. Most of the time you will realize that all you need is a form of IllegalArgumentException or ParseException or something similar.

6) While defining custom Exception, one of the most common mistake programmer make is to think that constructor is inherited from java.lang.Exception class, for example they think that their Exception class will automatically inherit default no argument constructor and the one which takes a String message. This is not true. Constructor is not inherited in Java, not even default constructor. It's actually added by compiler rather than inherited from parent class. That's why I have declared two constructor, one with String parameter and other as Throwable parameter :

public NoSuchProductException(String message, int productId) 
{ 
    super(message); 
    this.productId = productId; 
} 
public NoSuchProductException(String message, int productId, Throwable cause) 
{ 
    super(message, cause); 
    this.productId = productId; 
}

This is actually standard way of creating custom Exception in Java. In order to save time, you can even create template of above class in Eclipse IDE.

7) For readable code, it's good practice to append the string Exception to the names of all classes that inherit (directly or indirectly) from the Exception class e.g. instead of naming your class IncorrectPassword, name it IncorrectPasswordException.

There is lot more given on the following link:
http://javarevisited.blogspot.in/2014/06/how-to-create-custom-exception-in-java.html

How to use decorator pattern, when the class to decorate is final

I have an inbuilt class in java - String
Now I have made 3 classes
  1. AddHashCode
  2. ToLowerCase
  3. AddLength


I want to create a class, which has toString method overridden while selecting one or more of the above classes.

For example:
I want a class, which has toString method, which has the features of AddHashCode and ToLowerCase
or
I want a class, which has toString method, which has the features of all of the above classes.

So, lets do it with Decorator Pattern.

But the problem with Decorator Pattern is, that the classes you create must implement the String class.....But String class is final..
So I have tweaked the Decorator Design Pattern a bit, though it closely resembles the purpose of Decorator design pattern.

Create the following three classes

Class AddHashCode


Class ToLowerCase


Class AddLength


Use this as follows:
public class Main {
 public static void main(String[] args)
 {
                // Limitation and difference here will be, that on the LHS, the class used is ToLowerCase
                // and cannot be a String as was the case with usual Decorators.
  ToLowerCase x = new ToLowerCase
                                    (new AddHashCode
                                         (new String("YOGESH").toString()).toString());
  System.out.println(x.toString());
  AddHashCode y = new AddHashCode
                                    (new ToLowerCase
                                         (new AddLength(new String("YOGESH").toString())
                                    .toString())
                                .toString());
  System.out.println(y.toString());
 }
}

Friday, March 21, 2014

How to make a dropdown as readonly in html

I encountered a problem where in it was required to make a drop down readonly.

While searching over internet i found THIS
But the solution mentioned there, didn't appeal me much. As i had to make server side code changes while saving the value using the hidden field.

How do we do this? The common thought is to disable the drop down menu. Well, yes, but there's a choice

When you use disabled, it prevents the user from using the drop down, or form element. You can see the year, but it is grayed out. Your mouse can't select or change it, and you can't tab to it with the keyboard. Disabled is used a lot with checkboxes. Sounds like just what we want, but you unknowingly might have caused yourself a small development problem.

The problem is "disabled" does just that. Disabled means that in your $_POST or $_GET that element will not show up in your controller. If you want to use the year in your controller, you won't be able to recover it from that form. All you can do it look at the value on the web page.

What if we want to read the year, prevent the user from changing the year, and recover the year in the form data sent back to the controller. The solution for this is

Make a replica of your dropdown with a different name and different id.

Hide your original drop down with <span style="display:none">
This makes the element available in the form, so it will flow to the server side as well.
At the same time, it will give a look and feel of disabled to the user.

Example :

<span style="display:none">
<select style="width:400px;"  name="agentName">
            <option value="${coltuserprofile.belongsToOcn}">
                  <c:out value="${coltuserprofile.firstName}/${coltuserprofile.belongsToOcn}"/>
            </option>
</select>
</span>
<select style="width:400px;"  name="agentNameDisplay" disabled="disabled">
<option value="${coltuserprofile.belongsToOcn}">
            <c:out value="${coltuserprofile.firstName}/${coltuserprofile.belongsToOcn}"/>
      </option>
</select>


Friday, March 7, 2014

Exception handling in java

Thanks to https://today.java.net/article/2006/04/04/exception-handling-antipatterns#antipatterns

Basic Exception Concepts


Creating Your Own Exceptions


Antipatterns


Log and Throw


Throwing Exception


Throwing the Kitchen Sink


Catching Exception


Destructive Wrapping


Log and Return Null


Catch and Ignore


Throw from Within Finally


Multi-Line Log Messages


Unsupported Operation Returning Null





Wednesday, March 5, 2014

In JSTL/JSP when do I have to use and when can I just say ${myVar}

Source : http://stackoverflow.com/questions/6574776/in-jstl-jsp-when-do-i-have-to-use-cout-value-myvar-and-when-can-i-just

In JSTL/JSP when do I have to use <c:out value="${myVar}"/> and when can I just say ${myVar}


I've been doing this the whole time in my JSP code:
<c:out value="${myVar}"/>

Today I just realized for the first time that I seem to be able to use this shorter version just as well:
${myVar}

It works without <c:out>!

Perhaps this is because my page is declared like this:

<%@ page language="java" contentType="text/html; 
charset=utf-8" pageEncoding="utf-8" isELIgnored="false" %>

So, my question is, can I replace in my code with this shorter version? Is there any reason to keep using ? Or are there places where I might still need it?

Solution:


<c:out> does more than simply outputting the text. It escapes the HTML special chars.
Use it (or ${fn:escapeXml()}) every time you're not absolutely sure that the text doesn't contain any of these characters: ", ', <, >, &. Else, you'll have invalid HTML (in the best case), a broken page, or cross-site scripting attacks (in the worst case).

I'll give you a simple example so that you understand.
If you develop a forum, and someone posts the following message, and you don't use <c:out> to display this message, you'll have a problem:

<script>while (true) alert("you're a loser");</script>

Monday, March 3, 2014

duplicate import try, using auto-import="false"

How to use same entity class in two different packages in hibernate?


Source : http://isolasoftware.it/2011/10/14/hibernate-and-jpa-error-duplicate-import-try-using-auto-importfalse/

Using Hibernate and JPA you cannot have two classes with the same name (on different packages) mapped. This raise an error at runtime:
Caused by: org.hibernate.DuplicateMappingException: duplicate import: MyClass refers to both


To solve this issue on the Entity annotation of com.intre.MyClass and com.dummy.Class add the property name.

package com.intre;
@Entity(name = "com.intre.myclass")
@Table(name = "MyClass")
public class MyClass

package com.dummy;
@Entity(name = "com.dummy.myclass")
@Table(name = "MyClass")
public class MyClass

Wednesday, February 26, 2014

SOAP Version Mismatch: SOAP Version "SOAP 1.2 Protocol" in request does not match the SOAP version "SOAP 1.1 Protocol" of the Web service.

We were getting the below error in our project, when trying to invoke a web service.

[Server:server-one] 07:29:12,927 ERROR [stderr] (http-/10.99.12.28:8080-13) org.springframework.ws.soap.client.SoapFaultClientException: [ISS.0088.9168] SOAP Version Mismatch: SOAP Version "SOAP 1.2 Protocol" in request does not match the SOAP version "SOAP 1.1 Protocol" of the Web service.
[Server:server-one] 07:29:12,928 ERROR [stderr] (http-/10.99.12.28:8080-13)   at org.springframework.ws.soap.client.core.SoapFaultMessageResolver.resolveFault(SoapFaultMessageResolver.java:37)
[Server:server-one] 07:29:12,929 ERROR [stderr] (http-/10.99.12.28:8080-13)   at org.springframework.ws.client.core.WebServiceTemplate.handleFault(WebServiceTemplate.java:774)
[Server:server-one] 07:29:12,929 ERROR [stderr] (http-/10.99.12.28:8080-13)   at org.springframework.ws.client.core.WebServiceTemplate.doSendAndReceive(WebServiceTemplate.java:600)
[Server:server-one] 07:29:12,929 ERROR [stderr] (http-/10.99.12.28:8080-13)   at org.springframework.ws.client.core.WebServiceTemplate.sendAndReceive(WebServiceTemplate.java:537)
[Server:server-one] 07:29:12,930 ERROR [stderr] (http-/10.99.12.28:8080-13)   at org.springframework.ws.client.core.WebServiceTemplate.marshalSendAndReceive(WebServiceTemplate.java:384)
[Server:server-one] 07:29:12,930 ERROR [stderr] (http-/10.99.12.28:8080-13)   at org.springframework.ws.client.core.WebServiceTemplate.marshalSendAndReceive(WebServiceTemplate.java:378)
[Server:server-one] 07:29:12,931 ERROR [stderr] (http-/10.99.12.28:8080-13)   at org.springframework.ws.client.core.WebServiceTemplate.marshalSendAndReceive(WebServiceTemplate.java:370)

Solution:
The solution lies in the configuration files used by spring.
Here in our project, the version specified in this file was 1.2 where as the web service was expecting 1.1

<bean id="messageFactory" class="org.springframework.ws.soap.saaj.SaajSoapMessageFactory">
    <property name="soapVersion">
        <util:constant static-field="org.springframework.ws.soap.SoapVersion.SOAP_11" />
    </property>
</bean>



How to break a list into smaller sublists of equal size

// chops a list into non-view sublists of length L
static <T> List<List<T>> chopped(List<T> list, final int L) {
    List<List<T>> parts = new ArrayList<List<T>>();
    final int N = list.size();
    for (int i = 0; i < N; i += L) {
        parts.add(new ArrayList<T>(
            list.subList(i, Math.min(N, i + L)))
        );
    }
    return parts;
}

Usage:
List<Integer> numbers = Collections.unmodifiableList(
    Arrays.asList(5,3,1,2,9,5,0,7)
);
List<List<Integer>> parts = chopped(numbers, 3);
System.out.println(parts); // prints "[[5, 3, 1], [2, 9, 5], [0, 7]]"
parts.get(0).add(-1);
System.out.println(parts); // prints "[[5, 3, 1, -1], [2, 9, 5], [0, 7]]"
System.out.println(numbers); // prints "[5, 3, 1, 2, 9, 5, 0, 7]" (unmodified!)

Monday, February 24, 2014

Generate java classes using xjc

Source : Generate java class from xml schema using jaxb xjc command


Before using JAXB to create or access an XML document from Java application, we have to do the following steps:

1.Binding the schema
* Binding a schema means generating a set of Java classes that represents the schema for the XML document (Schema is not required for simple marshalling and unmarshalling).

2.Marshal the content tree /Unmarshal the XML document.
* After binding the schema, you can convert Java objects to and from XML document.
In this example we will see how to bind the schema. For that, we use Java Architecture for XML Binding (JAXB) binding compiler tool, xjc, to generate Java classes from XML schema.

‘xjc’ Command Line Options

Generate Java classes using ‘xjc’

Follow the steps below to generate a set of Java source files from XML schema.
  1. Create a new Java project folder and name it as “JAXBXJCTool”.
  2. Create a new XSD file and name it as “employee.xsd” and copy the following lines. This is the XML schema in our example which is to be bound to java classes
  3. Employee.xsd

  4. Save the file
  5. Create a new folder ‘src’ inside the project folder.
  6. In Windows open Command Prompt (Windows button + R and type cmd) or Terminal in Linux and go to the project folder (use cd command) where it exists in your machine and type the following command
  7. C:\Users\iByteCode\Desktop\JAXBXJCTool>xjc -d src -p com.theopentutorials.jaxb.beans employee.xsd
  8. This will generate set of Java source files with appropriate annotation inside ‘src’ folder



Wednesday, February 19, 2014

How to make ajax call in spring framework

Write a server side method, with a mapping something as follows:


@RequestMapping("/getKids.html")   
public @ResponseBody  
String getChildren(@RequestParam(value = "ocn") String ocn, 
HttpServletRequest request, HttpServletResponse response) 
{
       return ocn.toUpperCase();   
}
Here @ResponseBody tells the framework to return value of the method to the browser and not lookup for a view with that name.
You can optionally omit request and response parameters in the signature of the method, if you like to.

After removal of request and response the method will look like

@RequestMapping("/getKids.html")   
public @ResponseBody  
String getChildren(@RequestParam(value = "ocn") String ocn) 
{
       return ocn.toUpperCase();   
}



Write a javascript method as follows (This uses jquery to fire ajax request)

function populateSubAgents(obj)
{
   $.ajax({
    url: "getKids.html?ocn="+obj.value,
    success: function(data) {
      $("#subAgentName").html(data);
    },
    error: function(XMLHttpRequest, textStatus, errorThrown) { 
      if (XMLHttpRequest.status == 0) {
        alert(' Check Your Network.');
      } else if (XMLHttpRequest.status == 404) {
        alert('Requested URL not found.');
      } else if (XMLHttpRequest.status == 500) {
        alert('Internel Server Error.');
      }  else {
         alert('Unknown Error.\n' + XMLHttpRequest.responseText);
      }     
    }
  });   
}