Wednesday, September 18, 2013

How to get elements of list FROM JSP using JSTL and spring MVC 3

As we know we can populate the elements of list in JSP using JSTL tags. My requirement is to get the list of elements from JSP to controller.

I have one DTO class (ParentDTO) which internally contains the list of DTO (ChildDTO) and it looks like,
public class ParentDTO {

    private Long id;

    private List<ChildDTO> childs;

    //getters and setters here....

}

and ChildDTO looks like,

public class ChildDTO {

    private String name;

    private Long age;

    //getters and setters here....

}

In controller,
List<ChildDTO> childList = new ArrayList<ChildDTO>();
ChildDTO childOne = new ChildDTO();
childOne.setName("ABC");
childOne.setAge(10);

ChildDTO childTwo = new ChildDTO();
childTwo.setName("XYZ");
childTwo.setAge(5);

childList.add(childOne);
childList.add(childTwo);

model.addAttribute("childList", childList);

In JSP
<c:forEach var="child" items="${childList}">
    <tr>
        <td>Name :
          <input type="text" name="name" value="${child.name}"/>
        </td>
        <td>Age :
          <input type="text" name="age" value="${child.age}"/>
        </td>
    </tr>
</c:forEach>

Above code will populate the list properly. My requirement when user modify the details(name, age) and clicks on submit method.
When user clicks on submit I need to get the list of elements in the controller from the JSP and persist in DB.


SOLUTION:

Declare HTTPServletRequest in method argument and using request parameter get the column values as explained below,

String[] nameArr = request.getParameterValues("name");
String[] ageArr = request.getParameterValues("age");
List<ChildDTO> childList = new ArrayList<ChildDTO>();
if(nameArr != null && nameArr.length > 0 
        && ageArr != null && ageArr.length > 0
          && nameArr.length == ageArr.length) {
    for(int i = 0; i < nameArr.length; i++) {
        ChildDTO childOne = new ChildDTO();
        childOne.setName(nameArr[i]);
        childOne.setAge(Long.valueOf(ageArr[i]));
        childList.add(childOne);
    }
}

Once you convert it to DTO object then persist in DB.

Thursday, August 1, 2013

Java Vocabulory

There are total 243 java terms defined below.

Terms Definitions
abstract

Wednesday, May 9, 2012

How to avoid Duplicate submission using Struts Token with code example


There are many scenarios where we face duplicate submission problem like,

  • Using Refresh button
  • Using browser back button traverse back and re-submitting the form
  • Using browser history feature and re-submit the form and so on
To avoid this problem Struts provide 'Struts Token' concept.

How does it work? 

  1. saveToken generates a unique token and saves it in the session under the key org.apache.struts.action.TOKEN. 
  2. When the form is rendered, the struts html:form tag generates a hidden field named org.apache.struts.action.TOKEN. 
  3. Upon form submission, isTokenValid compares the token stored in the session with that submitted from the form. If they are equal, return true. Otherwise, return false.
  4. resetToken removes the token stored in the session. 

Step by step procedure to implement using Token in struts,

Step 1 :
Save the token in session using 'saveToken()' method which is implemented in Action class.


public class EmployeeLoadAction extends Action{
private final static String SUCCESS = "success";
@Override
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
ActionForward forward;
forward = mapping.findForward(SUCCESS);
saveToken(request);
return forward;
}
}


Step 2 :
In JSP file. Here in this example employee.jsp
Store the token using Hidden variable in JSP file as shown below.
Don't forget to import Globals and Constants class inside JSP file to avoid Jasper Exception

TRANSACTION_TOKEN_KEY variable inside Action class is deprecated, so use it from Globlas class instead.

<%@ page import="org.apache.struts.Globals"%> 
<%@ page import="org.apache.struts.taglib.html.Constants"%> 
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form name="employee" action="EmployeeSubmit.do" method="POST">
<input type="hidden" name="<%= Constants.TOKEN_KEY %>" 
value="<%= session.getAttribute(Globals.TRANSACTION_TOKEN_KEY) %>" > 
<TABLE>
<TR>
<TD>Name</TD>
<TD><input type="text" name="empName"></TD>
</TR>
<TR>
<TD>ID</TD>
<TD><input type="text" name="empId"></TD>
</TR>
<TR>
<TD colspan="2"><input type="submit" value="Submit"></TD>
</TR>
</TABLE>
</form>
</body>
</html>


Step 3 :

Now actual logic for duplicate submission inside EmployeeSubmit action class.
Method 'isTokenValid()' will validate the token and returns the boolean. 
Based on that we can decide whether form has re-submitted.


public class EmployeeSubmitAction extends Action{
private final static String SUCCESS = "success";
@Override
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
ActionForward forward;
forward = mapping.findForward(SUCCESS);
EmployeeSubmitForm frm = (EmployeeSubmitForm) form;
if (isTokenValid(request)) {
System.out.println("frm.getName() : " + frm.getEmpName());
resetToken(request);
} else {
System.out.println("frm.getName() : " + frm.getEmpName());
System.out.println("Duplicate Submission of the form");
}
return forward;
}
}


Wednesday, April 25, 2012

Use of intern() method in String class

intern() method is present in String class. 

Lets take an example 
String str = new String("abc");
String strComp = "abc";

str.equals(strComp) returns true, because equals method will checks the contents of strings.

But, (str == strComp) returns false, because it will compare the references.
In this case, because we used the new keyword, Java will create a new String object in normal (nonpool) memory, and str will refer to it. In addition, the literal "abc" will be placed in the pool.

If we use intern() 
str = str.intern();

Now the reference of 'str' will change from object outside the string pool to "abc" literal present inside string pool.

After execution (str == strComp) will return TRUE.