Posting JSON from ajax to Struts2 Action - java

Hey I am trying to post JSON from Ajax to Struts2 action class method. Little more info: I am running client on WAMP server and Struts2 on Eclipse Tomcat.
My client side code:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
var dataObj = {
"data": [{
"id": "1",
"name": "Chris"
}, {
"id": "2",
"name": "Kate"
}, {
"id": "3",
"name": "Blade"
}, {
"id": "4",
"name": "Zack"
}]
};
var data1 = JSON.stringify(dataObj);
$(document).ready(function(){
$("button").click(function(){
$.ajax({url:"http://localhost:8080/Core/add",type: "post", data: data1, dataType: 'json', contentType:"application/json;charset=utf-8",async: true,success:function(result){
$("#div1").html(result);
}});
});
});
</script>
</head>
<body>
<div id="div1"><h2>Let jQuery AJAX Change This Text</h2></div>
<button>Get External Content</button>
</body>
</html>
And this is my Java application stuff:
struts.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN"
"http://struts.apache.org/dtds/struts-2.1.7.dtd">
<struts>
<package name="addMenu" namespace="/" extends="json-default">
<action name="registrate" class="com.coreRestaurant.menu.MenuAction">
<result type="json" >
<param name="root">json</param>
</result>
</action>
<action name="read" class="com.coreRestaurant.menu.MenuAction" method="readMenuById">
<result type="json" >
<param name="root">json</param>
</result>
</action>
<action name="add" class="com.coreRestaurant.menu.MenuAction" method="addMenu">
<result type="json" >
<param name="root">data</param>
</result>
</action>
</package>
</struts>
And this is my java code (MenuAction.java):
package com.coreRestaurant.menu;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import com.google.gson.Gson;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
public class MenuAction extends ActionSupport implements ModelDriven<Menu>, Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private Menu menu = new Menu();
private String json;
private List<Menu> data = new ArrayList<Menu>();
public String execute(){
MenuService menuService = new MenuService();
setJson(new Gson().toJson(menuService.getMenuNames()));
if(menuService.isDatabaseConnectionDown()==false){
return SUCCESS;
}else{
setJson(new Gson().toJson("Failed to connect to Database"));
return ERROR;
}
}
public String readMenuById(){
MenuService menuService = new MenuService();
setJson(new Gson().toJson(menuService.getSpecificalMenuNameById(menu.getId())));
return SUCCESS;
}
public String addMenu(){
MenuService menuService = new MenuService();
System.out.println(data);
for(int i=0; i<data.size(); i++){
System.out.println(data.get(i));
}
menu.setName("Postitus");
menuService.addMenu(menu);
return SUCCESS;
}
public String getJson() {
return json;
}
public void setJson(String json) {
this.json = json;
}
#Override
public Menu getModel() {
return menu;
}
public List<Menu> getData() {
System.out.println("Getter Call");
return data;
}
public void setData(List<Menu> data) {
System.out.println("Setter Call Flow");
this.data = data;
}
}
And the Menu.java itself:
package com.coreRestaurant.menu;
import java.io.Serializable;
public class Menu implements Serializable{
private static final long serialVersionUID = 1L;
private String name;
private int id;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
All the time when I run my client side code, I can see the following input only from Eclipse console:
[]
Getter Call
Why is it empty? I expect to have that JSON array from client side but no success.

To send JSON data via Ajax you need to parse it by the Struts2 json interceptor. It will also populate your data property of the action object, but you should remove ModelDriven fom the action class. Unless you define a property to populate a list data from the json interceptor on the model you can't use model driven with json. To add json interceptor to the action config, you can override its interceptors.
<action name="add" class="com.coreRestaurant.menu.MenuAction" method="addMenu">
<interceptor-ref name="json"/>
<result type="json" >
<param name="root">data</param>
</result>
</action>

Related

Custom debugging interceptor with JSP in Struts 2

I'm using Struts 2.
I want to create a custom interceptor debug class to display in interceptor debugging mode browser all attributes field value when user click save button.
ProduitDto:
public class ProduitDto {
private String reference;
private String designation;
private double prix;
private int quantite;
private boolean promo;
public ProduitDto(String reference, String designation, double prix, int quantite, boolean promo) {
this.reference = reference;
this.designation = designation;
this.prix = prix;
this.quantite = quantite;
this.promo = promo;
}
public ProduitDto() {
}
public String getReference() {
return reference;
}
public void setReference(String reference) {
this.reference = reference;
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
public double getPrix() {
return prix;
}
public void setPrix(double prix) {
this.prix = prix;
}
public int getQuantite() {
return quantite;
}
public void setQuantite(int quantite) {
this.quantite = quantite;
}
public boolean isPromo() {
return promo;
}
public void setPromo(boolean promo) {
this.promo = promo;
}
}
ProduitAction:
import com.id.dto.ProduitDto;
import com.id.entites.Produit;
import com.id.service.ICatalogueService;
import com.id.service.SingletonService;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
public class ProduitAction extends ActionSupport implements ModelDriven<Produit> {
private ProduitDto produitDto = new ProduitDto();
private Produit produit = new Produit();
private List<Produit> produits;
private String ref;
private boolean editMode = false;
private ICatalogueService service = SingletonService.getService();
public String index( ) {
produits = service.listProduit();
return SUCCESS;
}
public String save() {
if (!editMode)
service.ajouterProduit(produit);
else
service.miseAjourProduit(produit);
produits = service.listProduit();
return SUCCESS;
}
public String delete() {
service.supprimerProduit(ref);
produits = service.listProduit();
return SUCCESS;
}
public String edit() {
editMode = true;
produit = service.recupererProduit(ref);
service.miseAjourProduit(produit);
produits = service.listProduit();
return SUCCESS;
}
public Produit getProduit() {
return produit;
}
public String getRef() {
return ref;
}
public void setRef(String ref) {
this.ref = ref;
}
public void setProduit(Produit produit) {
this.produit = produit;
}
public List<Produit> getProduits() {
return produits;
}
public void setProduits(List<Produit> produits) {
this.produits = produits;
}
public ProduitDto getProduitDto() {
return produitDto;
}
public void setProduitDto(ProduitDto produitDto) {
this.produitDto = produitDto;
}
public boolean isEditMode() {
return editMode;
}
public void setEditMode(boolean editMode) {
this.editMode = editMode;
}
#Override
public Produit getModel() {
return produit;
}
}
JSP:
<%#taglib uri="/struts-tags" prefix="s" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Produits</title>
<link rel="stylesheet" type="text/css" href="css/style.css"/>
</head>
<body>
<div>
<s:form action="save" method="post">
<s:textfield label="REF" name="produit.reference"></s:textfield>
<s:textfield label="Designation" name="produit.designation"></s:textfield>
<s:textfield label="Prix" name="produit.prix"></s:textfield>
<s:textfield label="Quantite" name="produit.quantite"></s:textfield>
<s:checkbox label="Promo" name="produit.promo"></s:checkbox>
<!-- <s:textfield name="editMode"></s:textfield> permet de voir une valeur du model -->
<s:hidden name="editMode"></s:hidden>
<s:submit value="Save"></s:submit>
</s:form>
</div>
<div>
<table class="table1">
<tr>
<th>REF</th>
<th>DES</th>
<th>PRIX</th>
<th>QUANTITE</th>
<th>PROMO</th>
</tr>
<s:iterator value="produits">
<tr>
<td><s:property value="reference"/></td>
<td><s:property value="designation"/></td>
<td><s:property value="prix"/></td>
<td><s:property value="quantite"/></td>
<td><s:property value="promo"/></td>
<s:url namespace="/" action="delete" var="lien1">
<s:param name="ref">
<s:property value="reference"/>
</s:param>
</s:url>
<s:url namespace="/" action="edit" var="lien2">
<s:param name="ref">
<s:property value="reference"/>
</s:param>
</s:url>
<td><s:a href="%{lien1}">Suppr</s:a></td>
<td><s:a href="%{lien2}">Edit</s:a></td>
</tr>
</s:iterator>
</table>
</div>
</body>
</html>
struts.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
"http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
<package name="default" namespace="/" extends="struts-default">
<default-action-ref name="index"></default-action-ref>
<action name="index">
<result>views/index.jsp</result>
</action>
<action name="produits" class="com.id.web.ProduitAction" method="index">
<result name="success">views/Produits.jsp</result>
</action>
<action name="save" class="com.id.web.ProduitAction" method="save">
<result name="success">views/Produits.jsp</result>
<result name="input">views/Produits.jsp</result>
</action>
<action name="delete" class="com.id.web.ProduitAction" method="delete">
<result name="success">views/Produits.jsp</result>
</action>
<action name="edit" class="com.id.web.ProduitAction" method="edit">
<result name="success">views/Produits.jsp</result>
</action>
</package>
</struts>
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="struts_blank" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Struts Blank</display-name>
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
Interceptor product :
public class ProductCustomInterceptor implements Interceptor
{
private static final long serialVersionUID = 1L;
#Override
public String intercept(ActionInvocation invocation) throws Exception
{
System.out.println("ProductCustomInterceptor intercept() is called...");
System.out.println(invocation.getAction().getClass().getName());
return invocation.invoke();
}
}
How can I intercept all filed value of my class product when I click save button in my jsp page by using interceptor class with debugging mode browser?

Struts delete action setters not called [duplicate]

This question already has an answer here:
How to set the property value for model object in action class using ModelDriven in Struts 2? [closed]
(1 answer)
Closed 5 years ago.
I have a Struts action class like so:
public class OrderDetailAction extends BaseActionSupport {
private String ID = new OID().toString();
private Collection<OrderDetail> orderdetailList;
private String orderStatus;
private String shippingAddressId;
private java.util.Date createdDate;
private java.util.Date updatedDate;
private String billingAddressId;
public void setOrderStatus(String orderStatus) {
this.orderStatus = orderStatus;
}
public String getOrderStatus() {
return orderStatus;
}
public void setShippingAddressId(String shippingAddressId) {
this.shippingAddressId = shippingAddressId;
}
public String getShippingAddressId() {
return shippingAddressId;
}
public void setCreatedDate(java.util.Date createdDate) {
this.createdDate = createdDate;
}
public java.util.Date getCreatedDate() {
return createdDate;
}
public void setUpdatedDate(java.util.Date updatedDate) {
this.updatedDate = updatedDate;
}
public java.util.Date getUpdatedDate() {
return updatedDate;
}
public void setBillingAddressId(String billingAddressId) {
this.billingAddressId = billingAddressId;
}
public String getBillingAddressId() {
return billingAddressId;
}
public String getID() {
return ID;
}
public void setID(String ID) {
this.ID = ID;
}
public Collection<OrderDetail> getOrderDetailList() {
return orderdetailList;
}
public void setOrderDetailList(Collection<OrderDetail> orderdetailList) {
this.orderdetailList = orderdetailList;
}
// some more logic
}
Whenever I run a create action, a display action or an edit action, struts calls all of the setters. However, when I run my delete action struts fails to call all the setters EXCEPT setID().
Is there a reason why this happens?
Here is my struts.xml for reference:
<struts>
// some other stuff here
<action name="getOrderDetails" class="presentation.OrderDetailAction" method="getOrderDetails">
<result name="success">OrderDetailList.jsp</result>
</action>
<action name="displayOrderDetail" class="presentation.OrderDetailAction" method='displayOrderDetail'>
<result name="success">OrderDetail.jsp</result>
</action>
<action name="displayCreateOrderDetail" class="presentation.OrderDetailAction" method='displayCreate'>
<result name="success">CreateOrderDetail.jsp</result>
</action>
<action name="createOrderDetail" class="presentation.OrderDetailAction" method='create'>
<result name="success" type="chain">getOrderDetails</result>
<result name="input">CreateOrderDetail.jsp</result>
<result name="error">CreateOrderDetail.jsp</result>
</action>
<action name="displayEditOrderDetail" class="presentation.OrderDetailAction" method='displayUpdate'>
<result name="success">EditOrderDetail.jsp</result>
</action>
<action name="editOrderDetail" class="presentation.OrderDetailAction" method='update'>
<result name="success" type="chain">getOrderDetails</result>
<result name="input">EditOrderDetail.jsp</result>
<result name="error">EditOrderDetail.jsp</result>
</action>
<action name="deleteOrderDetail" class="presentation.OrderDetailAction" method='delete'>
<result name="success" type="chain">getOrderDetails</result>
</action>
// some more stuff here
</sturts>
There is no difference between what the input looks like form the JSP either:
<input name="action:displayEditOrderDetail" class="btn btn-success" value="Edit" type="submit" id="displayOrderDetail_displayEditOrderDetail"/>
<input name="action:deleteOrderDetail" class="btn btn-danger" value="Delete" type="submit" id="displayOrderDetail_deleteOrderDetail"/>
<input name="action:getOrderDetails" class="btn btn-default" value="Cancel" type="submit" id="displayOrderDetail_getOrderDetails"/>
For every other CRUD operation, Struts successfully calls all the setters. Except in the case of Delete where it only calls setID(). Is there something different I am supposed to be doing for Delete?
After deleting an object you should return redirectAction result.
<result name="success" type="redirectAction">getOrderDetails</result>

Conversion and validation issue in Struts2

I have been working on struts for a long time.
I am simulating programmatic validations and conversion errors in an application using Struts 2.
In my application I have a model class called Product which is as shown below:
public class Product {
private String productId;
private String productName;
private int price;
public Product() {}
public Product(String productId, String productName, int price) {
this.productId = productId;
this.productName = productName;
this.price = price;
}
public String getProductId() {
return productId;
}
public void setProductId(String productId) {
System.out.println("Product.setProductId() : '"+productId+"'");
this.productId = productId;
System.out.println("This.pid : "+this.productId);
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
System.out.println("Product.setProductName() : '"+productName+"'");
this.productName = productName;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
System.out.println("Product.setPrice() : '"+price+"'");
this.price = price;
}
}
I have jsp called ProductForm.jsp where I ask user to enter product info like below:
<%#taglib uri="/struts-tags" prefix="s" %>
<html>
<head>
<title>Add Product Form</title>
<style type="text/css">#import url(css/main.css);</style>
</head>
<body>
<div id="global">
<h3>Add a product</h3>
<s:form method="post" action="Product_Save.action">
<s:textfield label="Id" key="productId"/>
<s:textfield label="Name" key="productName"/>
<s:textfield label="Price" key="price"/>
<s:submit value="Add Product"/>
</s:form>
<s:debug/>
</div>
</body>
</html>
If user clicks on Add Productbutton by giving correct info data will be saved to database according to normal flow which is configured in struts.xml which is as below:
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="product_module" extends="struts-default">
<action name="Product_Input">
<result>/jsp/ProductForm.jsp</result>
</action>
<action name="Product_Save" class="com.way2learnonline.ui.ProductAction">
<result name="success">/jsp/ProductDetails.jsp</result>
<result name="input">/jsp/ProductForm.jsp</result>
<param name="test">MyTest</param>
</action>
</package>
</struts>
My Action class is ProductAction which is as shown below:
public class ProductAction extends ActionSupport implements ModelDriven<Product>{
private static final long serialVersionUID = 1L;
private Product product;
private String test;
public ProductAction() {}
public String execute(){
DatabaseManager databaseManager=new DatabaseManager();
databaseManager.write(product);
return Action.SUCCESS;
}
#Override
public void validate() {
System.out.println("p : "+product.getProductId());
if(product.getProductId().trim().equals("")){
addFieldError("productId", "Product Id should be present");
}
if(product.getPrice()<=0){
addFieldError("price", getText("price.negative"));
}
}
#Override
public Product getModel() {
product=new Product();
return product;
}
public void setTest(String test) {
this.test = test;
}
public String getTest() {
return test;
}
}
If we give invalid data like price less than or equal to zero or productId is empty then validation will be triggered.
If we give alphabets in price field then conversion error will be triggered.
But If I give alphabets in price field then my product object all variables are becoming nulls while it goes to validate() method, which is resulting null pointer exception in validate() method when I try to access productId from product object of ProductAction class.
Here why is my product object variables of ProductAction class are becoming null if I give alphabets in price field in ProductForm.jsp.
Put the model initialization in the declaration, not in the getter:
private Product product = new Product();
#Override
public Product getModel() {
return product;
}

Struts2 interceptor session get null value when authenticate login page

I am a beginner in Struts2 and I'm trying to do this scenario on my own web project :
When user access login page, server will authenticate whether that he/she has login as "admin" / "user" by accessing the session using interceptor, If the user has no privilege data (it's null) inside the session, they will be passed to login page.
If the user has login as "admin", user will be redirected to "admin" page.
If the user has login as "user", user will be redirected to "user" page.
I was trying these codes, If i don't use interceptor, I can access the session, but if i use the interceptor what I get is, the session is still null and giving error 500 instead with NPE. I don't know what is wrong with it.
Thanks for any of you who help me.
struts.xml
<struts>
<constant name="struts.action.extension" value=","/>
<constant name="struts.custom.i18n.resources" value="global" />
<constant name="struts.devMode" value="true" />
<!-- Configuration for the default package. -->
<include file="strutsconf/struts-user.xml"/>
</struts>
struts-pageauth.xml
<struts>
<package name="struts-pageauth" namespace="/" extends="struts-default">
<interceptors>
<interceptor name="loginpageauth" class="control.intercept.UserAuthenticationLogin"/>
<interceptor-stack name="loginauth">
<interceptor-ref name="createSession"/>
<interceptor-ref name="loginpageauth"/>
<interceptor-ref name="defaultStack"/>
</interceptor-stack>
</interceptors>
</package>
</struts>
strusts-user.xml
<struts>
<constant name="struts.custom.i18n.resources" value="prop-user" />
<include file="strutsconf/struts-pageauth.xml"/>
<package name="struts-user" namespace="/" extends="struts-default, struts-pageauth">
<action name="login" method="login" class="control.action.Login">
<interceptor-ref name="loginauth"/>
<result name="admin">/main/admin/Admin.jsp</result>
<result name="user">/main/user/User.jsp</result>
<result name="error">/Login.jsp</result>
</action>
<action name="logout" method="logout" class="control.action.Login">
<result name="success">/Login.jsp</result>
<result name="error">/Login.jsp</result>
</action>
</package>
</struts>
UserAuthenticationLogin.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package control.intercept;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.interceptor.Interceptor;
import java.util.Map;
import org.apache.struts2.interceptor.SessionAware;
public class UserAuthenticationLogin extends ActionSupport implements SessionAware, Interceptor {
public void setSession(Map<String, Object> map) {
this.sessionMap = map;
}
public void destroy() {
System.out.println("UserAuthentication Interceptor destroy() called");
}
public void init() {
System.out.println("UserAuthentication Interceptor init() called");
}
public String intercept(ActionInvocation ai) throws Exception {
System.out.println("=========================DEBUG========================");
System.out.println("UserAuthentication Interceptor intercept() called");
System.out.println(getText("auth.privilage")); // I can access this properties
System.out.println(this.sessionMap); // It gets NULL ??
// System.out.println(this.sessionMap.get(getText("auth.privilage")));
if(this.sessionMap.get(getText("auth.privilage"))==null) {
return ai.invoke();
}
else if(this.sessionMap.get(getText("auth.privilage")).equals("admin")) {
return "admin";
}
else if(this.sessionMap.get(getText("auth.privilage")).equals("user")) {
return "user";
}
else {
return "login";
}
}
private String id;
private String password;
private String admin;
private Map<String, Object> sessionMap;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getAdmin() {
return admin;
}
public void setAdmin(String admin) {
this.admin = admin;
}
public Map<String, Object> getSessionMap() {
return sessionMap;
}
public void setSessionMap(Map<String, Object> sessionMap) {
this.sessionMap = sessionMap;
}
}
Login.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package control.action;
import com.opensymphony.xwork2.ActionSupport;
import java.util.Map;
import org.apache.struts2.interceptor.SessionAware;
public class Login extends ActionSupport implements SessionAware {
public void setSession(Map<String, Object> map) {
this.sessionMap = map;
}
public String login() throws Exception {
if(id.equals("admin") && password.equals("admin")) {
this.sessionMap.put("id", "admin");
this.sessionMap.put("priv", "admin");
return "admin";
}
if(id.equals("user") && password.equals("user")) {
this.sessionMap.put("id", "user");
this.sessionMap.put("priv", "user");
return "user";
}
else {
setErr_msg(super.getText("error.login"));
return super.ERROR;
}
}
public String logout() throws Exception {
this.sessionMap.remove("id");
this.sessionMap.remove("priv");
return super.SUCCESS;
}
private String id;
private String password;
private String err_msg;
private String admin;
private Map<String, Object> sessionMap;
public Map<String, Object> getSessionMap() {
return sessionMap;
}
public void setSessionMap(Map<String, Object> sessionMap) {
this.sessionMap = sessionMap;
}
public String getAdmin() {
return admin;
}
public void setAdmin(String admin) {
this.admin = admin;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getErr_msg() {
return err_msg;
}
public void setErr_msg(String err_msg) {
this.err_msg = err_msg;
}
}
The sessionMap is injected by ServletConfigInterceptor in Actions implementing the SessionAware interface, not Interceptors.
The right way to get the Session Map in an Interceptor is:
Map<String, Object> session = ActionContext.getContext().getSession();
Note: be careful in messing with Actions and Interceptors together: it's strange to see an Interceptor implementing ActionSupport... It's not a problem with your code because you are using declarative xml configuration, but Convention Plugin would scan the packages (luckily you have a package with an unmatching name) for classes extending ActionSupport and would detect it as an Action, making it ThreadLocal, that is not what an Interceptor has meant to be. Then you have to remember to be careful upgrading your code in the future to avoid unexpected result.

JSON Data not displayed in JSP

I have been trying to display my JSON data returned from action class in my JSP, but in vain...
I am using struts 2.1.8..
The following is the struts.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.enable.DynamicMethodInvocation" value="false"></constant>
<constant name="struts.devMode" value="false" />
<constant name="struts.custom.i18n.resources" value="ApplicationResources"> </constant>
<package name="sampleStrutapp" extends="struts-default">
<action name="login" class="struts2.LoginAction">
<result name="success">/checkValidation.jsp</result>
<result name="error">/HelloWorld.jsp</result>
</action>
</package>
<package name="struts2" extends="json-default">
<action name="populate" class="struts2.Populating">
<result type="json">
<param name="root">popdata</param>
<param name="noCache">true</param>
</result>
</action>
</package>
</struts>
My action class is the following..
package struts2;
import java.util.List;
import com.opensymphony.xwork2.*;
import net.sf.json.JSONObject;
import org.apache.catalina.connector.Request;
import data.Details;
import com.Various_functions;
public class Populating extends ActionSupport {
/**
*
*/
private static final long serialVersionUID = 1L;
public String usrname;
public String email;
public String lang;
public String gender;
public String comp;
public String desg;
public int rownum;
public int row;
public int getRow() {
return row;
}
public void setRow(int row) {
this.row = row;
}
private String popdata;
public String getPopdata() {
return popdata;
}
public void setPopdata(String popdata) {
this.popdata = popdata;
}
public int getRownum() {
return rownum;
}
public void setRownum(int rownum) {
this.rownum = rownum;
}
public String execute(){
Various_functions funct = new Various_functions();
List<Details> dev = funct.populate(this.getRow());
this.popdata = dev.get(0).getCompName()+","+dev.get(0).getDesig()+","+dev.get(0).getEmailId()+","+dev.get(0).getGender()+","+dev.get(0).getLang()+","+dev.get(0).getUserName();
System.out.println("In action class");
return "success";
}
public String getUsrname() {
return usrname;
}
public void setUsrname(String usrname) {
this.usrname = usrname;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getLang() {
return lang;
}
public void setLang(String lang) {
this.lang = lang;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getComp() {
return comp;
}
public void setComp(String comp) {
this.comp = comp;
}
public String getDesg() {
return desg;
}
public void setDesg(String desg) {
this.desg = desg;
}
}
and my javascript is the following..
function populate(rownum){
alert(rownum);
var inputData = { "row" : 1
};
// alert(inp);
$.post('populate.action', inputData, populatecallback, "json");
}
function populatecallback(popdata) {
alert("in call back!!");
var result = popdata.split(",");
usrname= result[5];
email= result[2];
desg= result[1];
lang= result[4];
comp= result[0];
gender= result[3];
$('#txtName').val(usrname);
$('#txtEmail').val(email);
$('#txtCmp').val(comp);
$('#txtDesg').val(desg);
$('#lan').val(lang);
$('#gen').val(gender);
}
Now, the jquery post is not working.
The following is the current library structure..
commons-collections-3.1.jar,
commons-fileupload-1.2.1.jar,
commons-io-1.3.2.jar,
commons-logging-1.1.1.jar,
freemarker-2.3.15.jar,
slf4j-api-1.5.8.jar,
slf4j-simple-1.5.8.jar,
struts2-core-2.1.8.1.jar,
struts2-jquery-plugin-1.8.3.jar,
xwork-core-2.1.6.jar
My js files are the following..
jquery-1.6.4.min.js,
json.js
Suggestions appreciated.
Thanks and regards,
hemanth.
Might not be relevant now, but back in 2009, there was an issue with Struts and writing json, namely:
http://code.google.com/p/jsonplugin/issues/detail?id=91
Perhaps its a similar issue you are hitting.
The exception is caused by a library version mismatch; in your case you're deploying multiple versions of XW, which is even worse. S2.1.8.1 requires xwork-core 2.1.6. Having both on the path is a bad idea. Consider using Maven to handle your dependency management, and avoid these kinds of headaches.
I did not verify the remaining versions on your list; you need to do so. The easiest way is to use Maven, or check against something like mvnrepository.com (where I got the S2.1.8.1 XW dependency from).

Categories