Struts delete action setters not called [duplicate] - java

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>

Related

Why do I often get exceptions when uploading files using "multipart/form-data"? [duplicate]

UploadvideoAction.java
private File id;
private String title;
private String url;
private String name="";
private String message="";
private String idContentType;
private String idFileName;
public String getIdContentType() {
return idContentType;
}
public void setIdContentType(String idContentType) {
this.idContentType = idContentType;
}
public String getIdFileName() {
return idFileName;
}
public void setIdFileName(String idFileName) {
this.idFileName = idFileName;
}
public void setServletRequest(HttpServletRequest servletRequest) {
this.servletRequest = servletRequest;
}
public String getMessage() {
return message;
}
public void setMessage(String message1) {
this.message = message;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public File getId() {
return id;
}
public void setId(File id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
struts.xml:
<action name="uploadvideo" class="com.myapp.ysrcptv.UploadvideoAction">
<interceptor-ref name="fileUpload">
<param name="allowedTypes">video/mp4,video/ogg,video/webm</param>
</interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>
<result>${url}</result>
<result name="login">adminlogin.jsp</result>
<result name="input">${url}</result>
</action>
uploadvideos.jsp:
<s:form cssClass="form" action="uploadvideo" method="post" validate="false" enctype="multipart/form-data">
<s:file cssClass="input" name="id" value="" placeholder="Video"></s:file>
<s:textfield cssClass="input" name="title" value="" placeholder="Video Title"></s:textfield>
<input type="hidden" name="name" value="gellery pic"/>
<input type="hidden" name="url" value="uploadvideos.jsp"/>
<s:submit cssClass="btn" value="Upload"></s:submit>
<div class="formdiv"><s:property value="message"/></div>
</s:form>
UploadvideoAction-validation.xml:
<!DOCTYPE validators PUBLIC "-//Apache Struts//XWork Validator 1.0.3//EN"
"http://struts.apache.org/dtds/xwork-validator-1.0.3.dtd">
<validators>
<field name="id">
<field-validator type="requiredstring">
<message>File is required.</message>
</field-validator>
</field>
Problem: Only server side file id validation is not working. Even if I selects a file its also showing validation message File is required. Remaining validations are working perfectly. Here I'm placing some stuff. Before its worked. After restarting my server this validation not working.
You have used wrong validator. "requiredstring" validator is used to validate textfields. You can use "required" validator that validates the field to be not null.
<field name="id">
<field-validator type="required">
<message>File is required.</message>
</field-validator>
</field>

How to map Addresses class with list of Address in EmployeeMap using Mybatis?

**How to map Addresses class with list of Address in EmployeeMap using Mybatis? is my code below correct? **
Below is query is to get employeeId and hos multiple address locations. How to map those fields in MyBatis? Appreciate your help to map the fields. FYI, I could not post complete Address class with other fields
<resultMap id="EmployeeMap" type="Employee">
<result column="emplId" property="emplId"/>
<collection property="addressList" >
<result column="addressLineOne" property="addressLineOne"/>
<result column="addressLineTwo" property="addressLineTwo"/>
<result column="city" property="city"/>
<result column="country" property="country"/>
<result column="zipCode" property="zipCode"/>
</collection>
</resultMap>
<select id="employeeData" resultMap="EmployeeMap">Select * from employee</select>
Here is My Java code
public class Employee{
String emplId;
Addresses addressList;
public String getEmplId() {
return emplId;
}
public void setEmplId(Addresses value) {
this.emplId = value;
}
public Addresses getAddressList() {
return addressList;
}
public void setAddressList(Addresses value) {
this.addressList = value;
}
}
public class Addresses{
List<Address> addresses;
public List<Address> getAddresses() {
if (addresses == null) {
addresses = new ArrayList<Address>();
}
return this.addresses;
}
}
public class Address{
String city;
public String getCity(){
return city;
}
public void setCity(String value) {
this.city = value;
}
}
The target property of <collection /> is addressList.addresses, so the result map should look as follows:
<resultMap id="EmployeeMap" type="Employee">
<id column="emplId" property="emplId"/>
<collection property="addressList.addresses"
javaType="list" ofType="Address">
<result column="addressLineOne" property="addressLineOne"/>
<result column="addressLineTwo" property="addressLineTwo"/>
<result column="city" property="city"/>
<result column="country" property="country"/>
<result column="zipCode" property="zipCode"/>
</collection>
</resultMap>
Note: You should specify <id /> in the parent result map.

How to validate file upload in Struts 2

UploadvideoAction.java
private File id;
private String title;
private String url;
private String name="";
private String message="";
private String idContentType;
private String idFileName;
public String getIdContentType() {
return idContentType;
}
public void setIdContentType(String idContentType) {
this.idContentType = idContentType;
}
public String getIdFileName() {
return idFileName;
}
public void setIdFileName(String idFileName) {
this.idFileName = idFileName;
}
public void setServletRequest(HttpServletRequest servletRequest) {
this.servletRequest = servletRequest;
}
public String getMessage() {
return message;
}
public void setMessage(String message1) {
this.message = message;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public File getId() {
return id;
}
public void setId(File id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
struts.xml:
<action name="uploadvideo" class="com.myapp.ysrcptv.UploadvideoAction">
<interceptor-ref name="fileUpload">
<param name="allowedTypes">video/mp4,video/ogg,video/webm</param>
</interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>
<result>${url}</result>
<result name="login">adminlogin.jsp</result>
<result name="input">${url}</result>
</action>
uploadvideos.jsp:
<s:form cssClass="form" action="uploadvideo" method="post" validate="false" enctype="multipart/form-data">
<s:file cssClass="input" name="id" value="" placeholder="Video"></s:file>
<s:textfield cssClass="input" name="title" value="" placeholder="Video Title"></s:textfield>
<input type="hidden" name="name" value="gellery pic"/>
<input type="hidden" name="url" value="uploadvideos.jsp"/>
<s:submit cssClass="btn" value="Upload"></s:submit>
<div class="formdiv"><s:property value="message"/></div>
</s:form>
UploadvideoAction-validation.xml:
<!DOCTYPE validators PUBLIC "-//Apache Struts//XWork Validator 1.0.3//EN"
"http://struts.apache.org/dtds/xwork-validator-1.0.3.dtd">
<validators>
<field name="id">
<field-validator type="requiredstring">
<message>File is required.</message>
</field-validator>
</field>
Problem: Only server side file id validation is not working. Even if I selects a file its also showing validation message File is required. Remaining validations are working perfectly. Here I'm placing some stuff. Before its worked. After restarting my server this validation not working.
You have used wrong validator. "requiredstring" validator is used to validate textfields. You can use "required" validator that validates the field to be not null.
<field name="id">
<field-validator type="required">
<message>File is required.</message>
</field-validator>
</field>

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 validation message appearing twice

I am trying struts validation but the error messages are getting printed twice. my action class is as follow.OSAction.java . I am so using hibernate in it. I think the validate method is called twice,
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;
}
*/
public void validate()
{
if (osdetail.getOSname() == null || osdetail.getOSname().trim().equals(""))
{
addFieldError("osdetail.OSname","The OS Name is required");
}
if (osdetail.getOSversion() == null || osdetail.getOSversion().trim().equals(""))
{
addFieldError("osdetail.OSversion","The OS Version is required");
}
}
}
My Index.jsp is below
<%# 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:hidden name="OSid" value="%{id}" />
    <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:reset value="Reset" />
</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>
Struts.xml is below
![<?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>
<result name="input">/index.jsp</result>
</action>
</package>
</struts>][2]
enter code here
This is because you are incorrectly using a "chain" result. Don't use it unless you know what are you doing. To fix error you should change the configuration like this
<action name="add" class="net.ajeet.os.view.OSAction" method="add">
<result type="redirectAction">index</result>
<result name="input">/index.jsp</result>
</action>
<action name="index" class="net.ajeet.os.view.OSAction">
<result>/index.jsp</result>
</action>
Just implement interceptor-ref name="defaultStack" before your action in struts.xml

Categories