JsonObject null when sending from javascript to action struts2 - struts2

Im working with struts2 .
and when Im Sending A JsonObject from js to action , JsonObject is null.
Code :
Js file :
var data = {"data":[{"name":"ABC","age":"20"},{"name":"XYZ","age":"22"}]};
$.ajax({
url: "Exam1/start",
data: data,
dataType: 'json',
type: 'POST',
contentType: 'application/json',
success: function (res) {
alert("OK");
}
});
and struts.xml :
<package name="default" extends="json-default" namespace="/">
<action name="start" method="init" class="ta.action.InitAction">
<param name="enableSMD">true</param>
<param name="ignoreInterfaces">false</param>
<param name="root">data</param>
<result type="json"/>
</action>
</package>
and Action :
public class InitAction extends ActionSupport{
private List<Student> data; // set and get
public String init() {
System.out.println("Data" + data );// data is null ( Why ??? )
}
}
and Class Student :
public class Student {
private String name;
private String age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}

Related

Setting varible in action class and fetching value in JSP using struts2

I am calling struts2 action class through a ajax call from javascript, which redirect it to b.jsp on success return. In action class I am setting a parameter called dummyValue, for which i have defined getter and setter in the action class. But when i try to display the value of this dummyValue using it does not shows any value.
struts.xml
<package name="AbcAction" namespace="/" extends="struts-default">
<action name="abcAction" class="com.AbcAction">
<result type="stream">
<param name="contentType">text/html</param>
<param name="inputName">stream</param>
</result>
<result name="input" type="dispatcher">/errorPage.jsp</result>
</action>
Setting the result type as stream on purpose.
AbcAction class
public class AbcAction extends ActionSupport {
private InputStream stream;
private String dummyValue;
public String execute() {
dummyValue = "Hello";
try
String str = "success";
stream = new ByteArrayInputStream(str.getBytes());
return SUCCESS;
}
catch (Exception e) {
e.printStackTrace();
String str = "error";
stream = new ByteArrayInputStream(str.getBytes());
return ERROR;
}
}
public InputStream getStream() {
return stream;
}
public void setStream(InputStream stream) {
this.stream = stream;
}
public String getDummyValue() {
return dummyValue;
}
public void setDummyValue(String dummyValue) {
this.dummyValue = dummyValue;
}
}
Javascript function to call action class
function callAbcAction() {
$.ajax({
url : "abcAction",
type: 'post',
data: { },
success : function(result){
if (result == "success") {
window.location='b.jsp';
}
else {
window.location='errorPage';
}
},
});
}
Tag to print dummyMsg in b.jsp
<div class="col-md-3">
<p>Dummy Value is : <s:property value="dummyValue"/></p>
</div>
It is redirecting to b.jsp on success return, but println only "Dummy Value is : " no value is coming.
Please help.
Thanks,
Savvy

How to map json payload to model bean in struts2

Is there any way to map json payload to Model bean.? If possible, please provide me an example.
Following are the classes I am using.
package com.sample;
import java.io.Serializable;
public class Employee implements Serializable{
private String firstName;
private String lastName;
private int id;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Employee [firstName=").append(firstName)
.append(", lastName=").append(lastName).append(", id=")
.append(id).append("]");
return builder.toString();
}
}
Following is my action class.
package com.sample.controller;
import com.opensymphony.xwork2.ModelDriven;
import com.sample.Employee;
public class EmployeeController implements ModelDriven<Employee> {
private String name = "Hari krishna";
Employee emp = new Employee();
public String addEmployee() {
System.out.println(emp);
return "success";
}
#Override
public Employee getModel() {
return emp;
}
}
Following is my struts.xml
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="default" extends="json-default">
<interceptors>
<interceptor-stack name="jsonStack">
<interceptor-ref name="json">
<param name="enableSMD">true</param>
</interceptor-ref>
</interceptor-stack>
</interceptors>
<action name="addEmployee" class = "com.sample.controller.EmployeeController" method = "addEmployee">
<interceptor-ref name="jsonStack"></interceptor-ref>
<result type="json" />
</action>
</package>
</struts>
When I call the action "addEmployee", with json data "{"firstName":"Hari","id":123,"lastName":"assds"}" I am getting following response. I set content type to text/json.
{
"model": {
"firstName": null
"id": 0
"lastName": null
}-
}
I am posting data using Advanced Rest Client.
when you send the json data from client to server, send them as string and in action class create a normal String variable to receive and hold the json's string.
Then, you can manually populate your bean from string using json parser,
or use a lib like google gson that has a build in features for this purposes.
Google Gson is a Java serialization/deserialization library that can convert Java Objects into JSON and back.
You can create your own struts Interceptor to wrap this process or implements it directly inside your action class.

Struts 2.0 error

I am developing a simple HelloWorld struts application. I am doing the configuration using struts.xml file. the welcome page is displayed but when I click on the form submit button, it gives 404 error.
Kindly provide some pointers.
action class:
package client;
public class Hello {
public String name;
public String message;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String execute() {
message = "Hello " + name;
return "success";
}
}
namecollect.jsp
<s:form action="hello" method="post">
<s:textfield name="name">Enter name</s:textfield>
<s:submit></s:submit>
</s:form>
struts.xml
<package name="default" namespace="/" extends="struts-default">
<action name="hello" class="client.Hello">
<result name="success">hello.jsp</result>
</action>
</package>
This is the package structure:
Your config file is in the wrong place.
By default struts.xml is expected to be at the root of your classpath.

How can i invoke the "execute" method of an Action redirected from another action in Struts 2?

I've got a problem with redirecting from one action to another in struts 2.
In action one (called: StudentZuPruefungHinzufuegen) i am creating action errors and want to show these in action two (called:ZeigePruefungsliste).
If i just use the "redirectAction" from struts it shows the correct action error at the place i wanted to show it. The problem is that the framework doesn't invoke my "execute" method before showing the resultpage with the action errors. Though the table I am filling within my "execute" method is empty and the resulting page is in fact useless.
Can somebody tell me how I can tell Struts to invoke the method while redirecting to action two?
My struts.xml looks like that:
<action name="ZeigePruefungsliste"
class="de.nak.multiplechoice.action.ZeigePruefungslisteAction">
<interceptor-ref name="store">
<param name="operationMode">RETRIEVE</param>
</interceptor-ref>
<interceptor-ref name="defaultLoginStack" />
<result type="tiles" name="*">pruefungsListe</result>
</action>
<action name="StudentZuPruefungHinzufuegen"
class="de.nak.multiplechoice.action.EditiereTeilnehmerAction">
<result type="tiles">studentZuPruefungHinzufuegen</result>
<interceptor-ref name="store">
<param name="operationMode">STORE</param>
</interceptor-ref>
<interceptor-ref name="defaultLoginStack" />
<result name="input" type="redirectAction">
<param name="actionName">
ZeigePruefungsliste
</param>
</result>
</action>
EDIT:
Code of my action classes.
public class EditiereTeilnehmerAction extends AbstractAction {
private static final long serialVersionUID = 882657701678551299L;
private Long ausgewaehltePruefungId;
private List<Nutzer> studenten;
private List<Long> ausgewaehlteStudenten;
#Override
public String execute() {
if (ausgewaehltePruefungId == null) {
addActionError("Es muss eine Prüfung ausgewählt werden.");
return INPUT;
}
studenten = getNutzerService().ladeAlleStudenten();
return SUCCESS;
}
public String zuPruefungHinzufuegen() {
getPruefungService().registriereStudentenFuerPruefung(ausgewaehltePruefungId, ausgewaehlteStudenten);
return SUCCESS;
}
public List<Nutzer> getStudenten() {
return studenten;
}
public void setStudenten(List<Nutzer> studenten) {
this.studenten = studenten;
}
public Long getAusgewaehltePruefungId() {
return ausgewaehltePruefungId;
}
public void setAusgewaehltePruefungId(Long ausgewaehltePruefungId) {
this.ausgewaehltePruefungId = ausgewaehltePruefungId;
}
public List<Long> getAusgewaehlteStudenten() {
return ausgewaehlteStudenten;
}
public void setAusgewaehlteStudenten(List<Long> ausgewaehlteStudenten) {
this.ausgewaehlteStudenten = ausgewaehlteStudenten;
}
}
public class ZeigePruefungslisteAction extends AbstractAction {
private static final long serialVersionUID = -7559234907568287686L;
private List<Pruefung> pruefungen;
#Override
public String execute() {
pruefungen = getPruefungService().getAllePruefungen(getAktuellenNutzer());
return SUCCESS;
}
public List<Pruefung> getPruefungen() {
return pruefungen;
}
}
public abstract class AbstractAction extends ActionSupport {
private static final long serialVersionUID = -6905222101893534102L;
private INutzerService nutzerService;
private IPruefungService pruefungService;
public HttpSession getHttpSession() {
HttpServletRequest request = (HttpServletRequest) ActionContext
.getContext().get(StrutsStatics.HTTP_REQUEST);
return request.getSession(true);
}
public Nutzer getAktuellenNutzer() {
return nutzerService.get(((Nutzer) getHttpSession().getAttribute(
StrutsKonstanten.NUTZER)).getId());
}
protected INutzerService getNutzerService() {
return nutzerService;
}
public void setNutzerService(INutzerService nutzerService) {
this.nutzerService = nutzerService;
}
protected IPruefungService getPruefungService() {
return pruefungService;
}
public void setPruefungService(IPruefungService pruefungService) {
this.pruefungService = pruefungService;
}
}
Greetings,
Marcus

Return String result type from Struts2

I want to send String as a response to the AJAX xhrPOST method. I am using Struts2 to implement the server side processing. But, I am not getting how to send the result "type" as string and the mapping which should be done to send the string from the struts2 action class to the AJAX response.
You can have your action method return not a String result, but a result of type StreamResult.
In other words:
class MyAction {
public StreamResult method() {
return new StreamResult(new ByteArrayInputStream("mystring".getBytes()));
}
}
You don't necessarily have to return a String from a Struts2 action method. You can always return an implementation of the Result interface from xwork.
copy this in action class
private InputStream inputStream;
public InputStream getInputStream() {
return inputStream;
}
public String execute(){
inputStream = new StringBufferInputStream("some data to send for ajax response");
return SUCCESS;
}
Struts.xml
<action name=....>
<result type="stream">
<param name="contentType">text/html</param>
<param name="inputName">inputStream</param>
</result>
This works when we want to send a single data in response
You could create a simple StringResult pretty easily by extending StrutsResultSupport, but nothing exists built-in to the framework as far as I know.
Here's an implementation that I've used in the past of a simple StringResult:
public class StringResult extends StrutsResultSupport {
private static final Log log = LogFactory.getLog(StringResult.class);
private String charset = "utf-8";
private String property;
private String value;
private String contentType = "text/plain";
#Override
protected void doExecute(String finalLocation, ActionInvocation invocation)
throws Exception {
if (value == null) {
value = (String)invocation.getStack().findValue(conditionalParse(property, invocation));
}
if (value == null) {
throw new IllegalArgumentException("No string available in value stack named '" + property + "'");
}
if (log.isTraceEnabled()) {
log.trace("string property '" + property + "'=" + value);
}
byte[] b = value.getBytes(charset);
HttpServletResponse res = (HttpServletResponse) invocation.getInvocationContext().get(HTTP_RESPONSE);
res.setContentType(contentType + "; charset=" + charset);
res.setContentLength(b.length);
OutputStream out = res.getOutputStream();
try {
out.write(b);
out.flush();
} finally {
out.close();
}
}
public String getCharset() {
return charset;
}
public void setCharset(String charset) {
this.charset = charset;
}
public String getProperty() {
return property;
}
public void setProperty(String property) {
this.property = property;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getContentType() {
return contentType;
}
public void setContentType(String contentType) {
this.contentType = contentType;
}
}
I've used the json plugin to do similar things. If you use that, you can use the following to expose a single String property in your action:
<result name="success" type="json">
<param name="root">propertyToExpose</param>
</result>

Resources