JSON Data not displayed in JSP - java

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

Related

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;
}

Posting JSON from ajax to Struts2 Action

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>

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.

How to access properties in the POJO using Struts 2 ModelDriven interface when you are using JSP?

I have an action class that implements ModelDriven interface. This ModelDriven is a regular POJO, the problem is that one of its properties is another object.
Imagine that my ModelDrivenis a object calledPersonand my person has an attribute calledAddressthat is another object.Addresshas regular properties such asString, Long` and etc.
In the JSP when I submit the form, all the regular properties used such as String, int, long in Person are mapped correctly, but all the data that should be mapped to address are not.
<s:textfield name="name" id="name" size="25" maxlength="15" />
<s:textfield name="address.zipcode" id="zipcode" size="25" maxlength="15" />
That's how I try mapping the properties. The name property I can get it right, but when it comes to map the properties in the person's address this approach does not work.
What am I doing wrong?
In time, my Address property is declared in Person instantiating the object, so it's never null.
EDIT: As requested, here the action source and the DTOs:
The Action:
#Controller
#Scope("request")
public class AnAction extends BaseAction implements ModelDriven<FakeDTO> {
private static final long serialVersionUID = 8238033889271514835L;
#Autowired
private FakeFacade facade;
private FakeDTO fakeDTO = new FakeDTO();
public String action01() {
return Action.SUCCESS;
}
public String action02() {
this.fakeDTO.setAnswer(this.fakeFacade.fakeFacadeMethod(this.fakeDTO.getComplexObject()));
return Action.SUCCESS;
}
#Override
public FakeDTO getModel() {
return this.fakeDTO;
}
}
The main class FakeDTO:
public class FakeDTO implements BaseDTO {
private static final long serialVersionUID = -2093038083351846003L;
private FakeFilterDTO filter = new FakeFilterDTO();
private String name;
public FakeDTO() {
super();
}
#Override
public FakeFilterDTO getFilter() {
return this.filter;
}
public void setFilter(final FakeFilterDTO filterParam) {
this.filter = filterParam;
}
public String getName() {
return this.name;
}
public String setName(final String nameParam) {
this.name = nameParam;
}
}
The class FakeFilterDTO:
public class FakeFilterDTO extends BaseFilterDTO {
private static final long serialVersionUID = 4528040257605851210L;
private Date aDate;
private Long aLong;
private Integer anInteger;
private String aString;
public Date getADate() {
return this.aDate;
}
public void setDataInicial(final Date aDateParam) {
this.aDate = aDateParam;
}
public Long getALong() {
return this.aLong;
}
public void setALong(final Long aLongParam) {
this.aLong = aLongParam;
}
public Integer getAnInteger() {
return this.anInteger;
}
public void setAnInteger(final Integer anIntegerParam) {
this.anInteger = anIntegerParam;
}
public String getAString() {
return this.aString;
}
public void setAString(final String aStringParam) {
this.aString = aStringParam;
}
}
The 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>
<include file="META-INF/bsad/struts2/struts-config.xml" />
<package name="reports" namespace="/reports" extends="project-default">
<action name="anAction" class="anAction" method="action01">
<result>/WEB-INF/pages/success.jsp</result>
<result name="input">/WEB-INF/pages/input.jsp</result>
</action>
<action name="generateReport" class="anAction" method="action02">
<result>/WEB-INF/pages/reportGenerated.jsp</result>
</action>
</package>
</struts>
The project-default is placed in the include struts-config.xml and extends struts-default package that contains the ModelDrivenInterceptor. I can assure that because I placed a break point in this interceptor and its passing through there.
The JSP that I used as an example before would become as follows:
<s:textfield name="name" id="name" size="25" maxlength="15" />
<s:textfield name="filter.aString" id="zipcode" size="25" maxlength="15" />
For company policies I'm not allowed to copy/paste the actual objects and its names. But that's the idea.
In the fakeDTO that is your model you should have a property address which should return an object like AddressDTO in this object there should be a property zipcode.
public class FakeDTO implements BaseDTO {
private AddressDTO address;
public AddressDTO getAddress() {
return address;
}
public void setAddress (AddressDTO address) {
this.address = address;
}
...
}
public class AddressDTO implements BaseDTO {
private String zipcode;
public String getZipcode() {
return zipcode;
}
public void setZipcode(String zipcode) {
this.zipcode = zipcode;
}
...
}
as you haven't posted struts.xml your action configuration should include modelDriven interceptor which include in the defaultStack by default is used when you extend struts-default package. See example of using ModelDriven. The model is pushed to the top of the valueStack by the interceptor, so the object like address should be available if it has a default constructor it will be created by the OGNL and zipcode set there. When you display the fields in the JSP the address.zipcode is evaluated as an OGNL expression and retrieve zipcode from the address bean if the model is initialized that bean and zipcode itself. All beans referenced in OGNL expression should be initialized and have getter/setter properties.

Saving values to mysql using struts2

I am new to struts and was trying to save some values to DB (mysql) from jsp page using struts and hibernate.
But, the application is saving null value every time and auto increment ID is increasing.
My Database structure. :
Table Name | osdetail
-------------------------
Columns | os_name,
| os_version,
| id,
| created,
| notes.
The index.jsp page
<%# page contentType="text/html; charset=UTF-8"%>
<%# taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
    <title>OS Manager - Struts2 Hibernate Example</title>
</head>
<body>
 
<h1>OS Manager</h1>
<s:actionerror/>
 
<s:form action="add" method="post">
    <s:textfield name="osdetail.OSname" label="name"/>
    <s:textfield name="osdetail.OSversion" label="version"/>
    <s:textfield name="osdetail.OSnotes" label="notes"/>
    <s:submit value="Add OS Details" align="center"/>
</s:form>
 
 
<h2>OS Details</h2>
<table>
<tr>
    <th>OS Name</th>
    <th>OS Version</th>
    <th>OS Notes</th>
</tr>
<s:iterator value="osdetails_list" var="osdetail">
    <tr>
        <td><s:property value="OSname"/></td>
        <td><s:property value="OSversion"/></td>
        <td><s:property value="OSnotes"/></td>
    </tr>
</s:iterator>
</table>
</body>
</html>
My View : OSAction.java
package net.ajeet.os.view;
import java.util.List;
import net.ajeet.os.controller.OSManager;
import net.ajeet.os.model.OSDetail;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
public class OSAction extends ActionSupport implements ModelDriven<OSDetail> {
private static final long serialVersionUID = 9149826260758390091L;
private OSDetail osdetail= new OSDetail();
private List<OSDetail> osdetails_list;
private Long id;
private OSManager linkController= new OSManager();
#Override
public OSDetail getModel() {
return osdetail;
}
public OSAction() {
linkController = new OSManager();
}
public String execute() {
this.osdetails_list = linkController.list();
return SUCCESS;
}
public String add() {
System.out.println("this is oS detail get ID"+osdetail.getId());
try {
//linkController.add(getOSDetail());
linkController.add(osdetail);
System.out.println("this is oS detail after add "+getOSDetail());
} catch (Exception e) {
e.printStackTrace();
}
this.osdetails_list = linkController.list();
return SUCCESS;
}
public String delete() {
linkController.delete(getId());
return SUCCESS;
}
public OSDetail getOSDetail() {
return osdetail;
}
public List<OSDetail> getOSDetail_list() {
return osdetails_list;
}
public void setOSDetail(OSDetail osdetail) {
this.osdetail = osdetail;
}
public void setOSDetail_list(List<OSDetail> osdetails_list) {
this.osdetails_list = osdetails_list;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
My Model: OSDetail.java
package net.ajeet.os.model;
import java.io.Serializable;
import java.sql.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="osdetail")
public class OSDetail implements Serializable{
private static final long serialVersionUID = -8767337896773261247L;
private Long OSid;
private String OSname;
private String OSversion;
private String OSnotes;
private Date OScreated;
#Id
#GeneratedValue
#Column(name="id")
public Long getId() {
System.out.println("set os name is os id"+OSid);
return OSid;
}
#Column(name="os_name")
public String getOS_name() {
return OSname;
}
#Column(name="os_version")
public String getOS_version() {
return OSversion;
}
#Column(name="notes")
public String getNotes() {
return OSnotes;
}
#Column(name="created")
public Date getCreated() {
return OScreated;
}
public void setId(Long OSid) {
this.OSid = OSid;
}
public void setOS_name(String OSname) {
this.OSname = OSname;
}
public void setOS_version(String OSversion) {
this.OSversion = OSversion;
}
public void setNotes(String OSnotes) {
this.OSnotes = OSnotes;
}
public void setCreated(Date OScreated) {
this.OScreated = OScreated;
}
My Contoller :OSManager.java
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.classic.Session;
import net.ajeet.os.model.OSDetail;
import net.ajeet.os.util.HibernateUtil;
public class OSManager extends HibernateUtil {
public OSDetail add(OSDetail osdetail) {
System.out.println("value of the os in OSManager"+osdetail.getId());
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
session.save(osdetail);
session.getTransaction().commit();
return osdetail;
}
public OSDetail delete(Long id) {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
OSDetail osdetail = (OSDetail) session.load(OSDetail.class, id);
if(null != osdetail) {
session.delete(osdetail);
}
session.getTransaction().commit();
return osdetail;
}
#SuppressWarnings("unchecked")
public List<OSDetail> list() {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
List<OSDetail> osdetails_list = null;
try {
osdetails_list = (List<OSDetail>)session.createQuery("from OSDetail").list();
} catch (HibernateException e) {
e.printStackTrace();
session.getTransaction().rollback();
}
session.getTransaction().commit();
return osdetails_list;
}
}
The values saved in DB are always null...except the ID..Please help
Changed the Action...updated getter/setter
package net.ajeet.os.view;
import java.util.List;
import net.ajeet.os.controller.OSManager;
import net.ajeet.os.model.OSDetail;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
public class OSAction extends ActionSupport {
private static final long serialVersionUID = 9149826260758390091L;
public OSDetail osdetail= new OSDetail();
private List<OSDetail> osdetails_list;
public OSDetail getOsdetail() {
return osdetail;
}
public void setOsdetail(OSDetail osdetail) {
this.osdetail = osdetail;
}
private Long id;
private OSManager linkController= new OSManager();
/* #Override
public OSDetail getModel() {
return osdetail;
}*/
public OSAction() {
linkController = new OSManager();
}
public String execute() {
this.osdetails_list = linkController.list();
return SUCCESS;
}
public String add() {
try {
linkController.add(getOsdetail());
//linkController.add(osdetail);
} catch (Exception e) {
e.printStackTrace();
}
this.osdetails_list = linkController.list();
return SUCCESS;
}
public String delete() {
linkController.delete(getid());
return SUCCESS;
}
public List<OSDetail> getOsdetails_list() {
return osdetails_list;
}
public void setOsdetails_list(List<OSDetail> osdetails_list) {
this.osdetails_list = osdetails_list;
}
public Long getid() {
return id;
}
public void setid(Long id) {
this.id = id;
}
}
Corrected OSDetail.java, automatically created getter/setter.
package net.ajeet.os.model;
import java.io.Serializable;
import java.sql.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="osdetail")
public class OSDetail implements Serializable{
private static final long serialVersionUID = -8767337896773261247L;
private Long OSid;
private String OSname;
private String OSversion;
private String OSnotes;
private Date OScreated;
#Id
#GeneratedValue
#Column(name="id")
public Long getOSid() {
return OSid;
}
public void setOSid(Long oSid) {
OSid = oSid;
}
#Column(name="os_name")
public String getOSname() {
return OSname;
}
public void setOSname(String oSname) {
OSname = oSname;
}
#Column(name="os_version")
public String getOSversion() {
return OSversion;
}
public void setOSversion(String oSversion) {
OSversion = oSversion;
System.out.println("value of the os in OSversion in setter"+OSversion);
}
#Column(name="notes")
public String getOSnotes() {
return OSnotes;
}
public void setOSnotes(String oSnotes) {
OSnotes = oSnotes;
}
#Column(name="created")
public Date getOScreated() {
return OScreated;
}
public void setOScreated(Date oScreated) {
OScreated = oScreated;
}
}
Adding struts.xml to
<?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 name="struts.devMode" value="false" />
<package name="default" extends="struts-default" namespace="/">
<action name="add"
class="net.ajeet.os.view.OSAction" method="add">
<result name="success" type="chain">index</result>
<result name="input" type="chain">index</result>
</action>
<action name="index"
class="net.ajeet.os.view.OSAction">
<result name="success">index.jsp</result>
</action>
</package>
</struts>
And 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="connection.driver_class">
com.mysql.jdbc.Driver
</property>
<property name="connection.url">
jdbc:mysql://localhost:3306/test
</property>
<property name="connection.username">root</property>
<property name="connection.password">Asmita24</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">
org.hibernate.dialect.MySQLDialect
</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">
org.hibernate.cache.NoCacheProvider
</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">update</property>
<mapping class="net.ajeet.os.model.OSDetail" />
</session-factory>
</hibernate-configuration>
Your getter function is wrongly named for the variable osdetail. It should be getOsdetail() instead of getOSDetail(). That is the reason your values from the form are not set and the variable osdetail has blank values. Try changing it. Same goes for the setter method, it should be setOsdetail(). Also, to prevent making such mistake in fututre, you can generate your getter and setter functions automatically from eclipse instead of manually creating it.
I don't see anywhere in your OSAction the code to read the values from the jsp. And that is the reason why I think the values are going in as null in the DB.
I suppose it'll work if you get the details from the jsp and set it to osdetail before calling linkController.add(osdetail);.
I am not too well versed with ActionSupport but I think you can read the values from the jsp using getText() method...
Try adding these lines before linkController.add(osdetail); line...
osdetail.setOS_name(getText("osdetail.OSname"));
osdetail.setOS_version(getText("osdetail.OSversion"));
osdetail.setNotes(getText("osdetail.OSnotes"));

Categories