How to exclude action methods from validation in struts2 - struts2

My Action class have the following methods,
1.add
2.edit
3.loadEdit
4.remove
5.list
6.execute
in this i need to apply validation for add and edit..how do need to config in struts.xml.I followed,
<action name="editComment" method="edit"
class="com.mmm.ehspreg2.web.action.product.CommentAction">
<result name="success">/jsp/propertyManager/loadList.jsp</result>
</action>
<action name="removeComment" method="remove"
class="com.mmm.ehspreg2.web.action.product.CommentAction">
<interceptor-ref name="validation">
<param name="excludeMethods">remove</param>
</interceptor-ref>
<result type="tiles">listComment</result>
<result type="tiles" name="input">listComment</result>
</action>
When I configure it like this, remove action method is not getting called. I don't understand the problem. Please assist.

you can also use #SkipValidation before method initialization in action class
e.g.
#SkipValidation
public String save() {
String result = super.save();
if (result.equals(SAVE)) {
setMessage1(getText("save.successful"));
} else {
setMessage1(getText("save.unsuccessful"));
}
jsonResponse = new Hashtable<String, Object>();
jsonResponse.put(FIELD_JSONRESPONSE_STATUS,
KEY_JSONRESPONSE_MESSAGE_SUCCESS);
jsonResponse.put(FIELD_JSONRESPONSE_MESSAGE,
KEY_JSONRESPONSE_EMPTY_STRING);
jsonResponse.put(FIELD_JSONRESPONSE_VALUE, domainModel.getId());
// System.out.println("domainModel>>>>>>" + domainModel.getId());
return result;
}

Simply list all the methods you don't want to be run through the validation framework in the excludeMethods parameter. Since you only want add and edit validated, list the other 4 as follows:
<interceptor-ref name="validation">
<param name="excludeMethods">loadEdit,remove,list,execute</param>
</interceptor-ref>
You can read more about it in the Validation Interceptor docs.

Related

struts2 + jfreechart + jsp : lost request parameters in action which generates Jfreechart

1)I called action which generates jfreechart using next jsp(using tiles) code :
<s:url var="chart" action="resultChart"/>
<img src="<s:property value="%{chart}"/>"/>
2)struts.xml
<package name="chart" extends="jfreechart-default" namespace="/">
<action name="resultChart" class="com.examples.actions.ChartAction">
<result name="success" type="chart">
<param name="width"> 1200 </param>
<param name="height"> 600 </param>
</result>
</action>
</package>
3)to generate chart - I use request parameters from previous action :
public class ChartAction extends ActionSupport implements RequestAware {
private static final long serialVersionUID = 1L;
private Map request;
private JFreeChart chart;
public String execute() throws Exception {
DataBean dataBean = (DataBean)request.get("dataBean");
.....
}
My problem next : I cant draw chart because request return null(dataBean=null)
NOTE : Without passing request parameters all works fine
My research - I used next code in ChartAction(before request.get) to investigate problem:
ValueStack valuestack = ActionContext.getContext().getValueStack();
System.out.println("valuestack.size() = " + valuestack.size());
System.out.println("valuestack root = " + valuestack.getRoot().toString());
And I saw that in ValueStack no records from action which put parameter(dataBean) into request
Please help

Struts2 addActionError setting result to input automatically on redirect result

I have a struts2 action, which sets some error using addActionError something like below
public String del() {
if (new OrdersService().get(idorder) == null) {
addActionError("Order not found");
} else {
new OrdersService().remove(idorder);
addActionMessage("Order deleted successfully");
}
return SUCCESS;
}
So the above method NO MATTER WHAT always return "success" result.
But in struts.xml I've used the redirect result-type to redirect to another action
and that action is never executed instead I'm getting result "input", I'm unable to understand what's going wrong ?
Is it something like
If an action sets an actionError, another action can't be executed and straight away "input" result will be thrown. But it doesn't make sense (at least to me)!
[EDIT] including some part of struts.xml
<action name="/order/{idorder:[0-9]+}/del" class="actions.OrderAction" method="del">
<interceptor-ref name="store">
<param name="operationMode">AUTOMATIC</param>
</interceptor-ref>
<interceptor-ref name="defaultStack" />
<result name="success" type="redirect">orders</result>
</action>
The default stack includes the "workflow" interceptor.
If there are action or field errors this interceptor returns the "input" result, because there was an error.
Reading some documentation will point you in the right direction. Note that your errors will be lost on a redirect anyway, unless you specifically save them.
Also, if you want to redirect to an action, use the "actionRedirect" result type.
public String del() {
if (new OrdersService().get(idorder) == null) {
addActionError("Order not found");
return ERROR;
} else {
new OrdersService().remove(idorder);
addActionMessage("Order deleted successfully");
return SUCCESS;
}
}
Also include return type 'error' as you have done for return type 'success' in your action mapping in struts.xml

struts 2 rest plugin client program

i am writing the client web jsp page just like having one form(get) with user name search text box and submit button
when the user submits it returns the json format of user
but the url looks like when i submit it
http://myhost.net:8080?user=pavan&method.execute=submit
how can i convert this url to below one in struts2 .
http://myhost.net:8080/user/pavan
is there any .htaccess file in struts2
#Results( { #Result(name = "success", type = "redirectAction") })
public class UsersController implements ModelDriven<Object>,
ServletRequestAware {
private String username;
private HttpServletRequest request;
private String representation;
// GET /users/{username}
public HttpHeaders show() {
String acceptHeader = request.getHeader("Accept");
String type = "xml";
if (acceptHeader == null || acceptHeader.isEmpty() ||
acceptHeader.equals("application/xml")) {
representation = UserBO.getXML(username);
} else if (acceptHeader.equals("application/json")) {
representation = UserBO.getJSON(username);
type = "json";
}
return new DefaultHttpHeaders(type).disableCaching();
}
You can use Parameters after the Action name.
To use parameters in the URL, after the action name, make sure this is set:
<constant name="struts.enable.SlashesInActionNames" value="true"/>
<constant name="struts.mapper.alwaysSelectFullNamespace" value="false"/>
Then the action mapping will look like:
<package name="edit" extends="struts-default" namespace="/edit">
<action name="/person/*" class="org.apache.struts.webapp.example.EditAction">
<param name="id">{1}</param>
<result>/mainMenu.jsp</result>
</action>
</package>
When a URL like /edit/person/123 is requested, EditAction will be called, and its "id" field will be set to 123.

composite component button action issue in jsf2 mojarra

Trying to develop a composite component using jsf2.0 (Mojarra) which should render command buttons dynamically based on the list from the bean. I was able to render the buttons but action is not getting triggered.Could any one please help me to resolve the issue?
Here follows the code
<composite:interface>
<composite:attribute name="buttonList" required="true"
type="java.util.List" />
<composite:attribute name="beanName" required="true"
type="java.lang.Object" />
</composite:interface>
<composite:implementation>
<ui:repeat var="listItem" value="#{cc.attrs.buttonList}">
<h:commandButton value="#{listItem.buttonName}"
action="#{cc.attrs.beanName.listItem.buttonAction}">
</h:commandButton>
</ui:repeat>
</composite:implementation>
This is used as
<utils:buttonGroup buttonList="#{testButtonBean.buttonList}"
beanName="#{testButtonBean}" />
The bean looks like
public class TestButtonBean {
public List<ButtonPOJO> buttonList = new ArrayList<ButtonPOJO>();
public List<ButtonPOJO> getButtonList() {
return buttonList;
}
public void setButtonList(List<ButtonPOJO> buttonList) {
this.buttonList = buttonList;
}
public void preProcess() {
if (null != buttonList && buttonList.size() == 0) {
ButtonPOJO ob1 = new ButtonPOJO("Continue", "next");
ButtonPOJO ob2 = new ButtonPOJO("Back", "prev");
buttonList.add(ob1);
buttonList.add(ob2);
}
}
public String next() {
return "page1";
}
public String prev() {
return "page2";
}
}
action="#{cc.attrs.beanName.listItem.buttonAction}"
This is not right. This syntax is basically looking for a property listItem on beanName and then trying to invoke the literal action buttonAction() on it.
You need the brace notation action="#{bean[methodName]}" if you want to specify the action method name as string coming from another bean property.
action="#{cc.attrs.beanName[listItem.buttonAction]}"
Unrelated to the concrete problem, if the above solution still fails, then that can only mean that the value="#{cc.attrs.buttonList}" has incompatibly changed during the form submit request. You need to make sure that exactly the same list is prepared during the postback as it was during the initial request. See also point 4 of commandButton/commandLink/ajax action/listener method not invoked or input value not updated.

Struts2 : The requested list key could not be resolved Error

I'm sorry for posting so many questions, I think I need to read up more...
But first of all I was wondering if you guys can help me on this cos it's been bugging me for quite some time already and have been wondering why it's not working.
(This has nothing to do with the previous errors. Haven't got to solve that, and a new one is out :x)
I have a list that I want to populate to another, but in the process of doing so I got the error as titled :The requested list key could not be resolved as a collection/array/map/enumeration/iterator type.
I've looked around and tried the code but still it doesn't really seem to work. Here's my code:
JSP (and jquery):
<s:select id="feb" name="feb" headerKey="-1" list="febList"
listKey="key" listValue="description" theme="simple" cssClass="formfields" />
$('select#feb').change(function() {
$.ajax({
url: "AnnotateSearchList?feb="+$(this).val()+"&dept="+$("#dept").val(),
dataType :'json',
type:'GET',
contentType: 'application/json',
success : function(data) {
alert('test');
},
error: function(){
alert('Error');
}
})
});
The method:
public String doGetSelectedList()
{
this.output = new StringBufferInputStream("");
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy");
Calendar startCalendar = Calendar.getInstance();
startCalendar.add(Calendar.DAY_OF_YEAR, -3);
Calendar endCalendar = Calendar.getInstance();
if (this.startDate == null || this.startDate.equals("")) {
this.startDate = sdf.format(startCalendar.getTime()).toString();
}
if (this.endDate == null || this.endDate.equals("")) {
this.endDate = sdf.format(endCalendar.getTime()).toString();
}
System.out.println("Feb "+this.feb);
System.out.println("Dept "+this.dept);
this.optionList =xxx.getList(this.feb, this.dept, this.startDate, this.endDate);
ArrayList<SelectItemsData> optList = new ArrayList<SelectItemsData>();
for(String list : optionList){
optList.add(new SelectItemsData(list, list));
}
System.out.println("Size of list: "+this.optionList.size());
System.out.println(optList.size());
String json = new Gson().toJson(optList);
logger.sendMessage(getClass().getSimpleName(), LogHandler.INFO, json);
//System.out.println(json);
try {
response.setContentType("Application/json");
response.getWriter().write(json);
this.output = new StringBufferInputStream(json);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return SUCCESS;
}
//The Data holder for SelectItemsData:
SelectItemsData(String key, String description);
struts/xml:
<action name="AnnotateSearchList" class="mycompanyName.ajax.actions.ParetoChartCore" method="doGetSelectedList">
<result type="stream">
<param name="contentType">application/json</param>
<param name="inputName">output</param>
</result>
<result name="success">/ParetoChart.jsp</result>
</action>
Am I going on wrong anywhere? My results are actually returning to the same page, so I thought that might be the possible cause of the error.
Thanks.
I changed the "success" to "SUCCESS" in struts.xml and it worked.

Resources