Send Form Data to Struts2 Action Class using Ajax - java

I am new to Jquery and Struts.
I need to send the form data to Struts2 action class using Ajax function.
My HTML form element is set as :
<div class="input-append date" id="from_date">
<input type="text" id="processDate" name="processDate" />
<span class="add-on"><i class="icon-th"></i></span>
</div>
<div>
<input id="submit-date" type="button" class="btn btn-primary" value="Search" />
</div>
I am using the JQuery Script as :
$('#submit-date').click(function() {
var processDate = $('#processDate').val();
alert(processDate);
$.ajax({
type : "POST",
url : "launchapptest",
data : processDate,
dataType : "json",
success : function(result) {
alert("Success");
}
});
}
Struts.XML file is written as :
<action name="launchapptest" class="com.ge.wd.action.LaunchAppTestAction">
<result type="json">
</result>
</action>
I have given execute method in Action Class :
String processDate;
public String getProcessDate() {
return processDate;
}
public void setProcessDate(String processDate) {
this.processDate = processDate;
}
public String execute() throws Exception {
processDate=getProcessDate();
System.out.println("Process Date : "+processDate);
}
Please help me as how can I receive this for data in the action class.

Thanks for the help. But issue is resolved, I changed the code to :
HTML:
<div class="input-append date" id="from_date">
<input type="text" id="processDateForm" name="processDate"/>
<span class="add-on"><i class="icon-th"></i></span>
</div>
<div>
<input id="submit-date" type="button" class="btn btn-primary" value="Search" />
</div>
Jquery :
$('#submit-date').click(function() {
var processDate = $('#processDateForm').val();
alert(processDate);
$.ajax({
/* type : "POST", */
url : "launchapptest",
/* contentType: "application/json; charset=utf-8", */
data : "processDateInput="+processDate,
dataType : "json",
async: true,
success : function(result) {
alert("Success");
}
});
and JAVA code :
public class LaunchAppTestAction extends ActionSupport {
private static final long serialVersionUID = -367986889632883043L;
//private ProcessDate pd = new ProcessDate();
private String processDateInput=null;
public String getProcessDateInput() {
return processDateInput;
}
public void setProcessDateInput(String processDateInput) {
this.processDateInput = processDateInput;
}
public String execute() throws Exception {
System.out.println("Process Date : "+processDateInput);
return SUCCESS;
}}
Struts.xml
<action name="launchapptest" class="com.ge.wd.action.LaunchAppTestAction">
<result name= "success" type="json">
</result>
</action>
I hope this works for anyone facing the same issue :)
Thanks again

Related

How to upload form with image file in it, AngularJS spring

I have this form
<div class="row">
<h1 class="page-header">
Create
</h1>
<form ng-submit="create()", enctype="multipart/form-data">
<div class="form-group">
<label>Name:</label>
<input type="text" ng-model="subforum.name" class="form-control" />
</div>
<div class="form-group">
<label>Desc:</label>
<input type="text" ng-model="subforum.desc" class="form-control" />
</div>
<input type="file" ngf-select ng-model="subforum.icon" name="subforum.icon"
accept="image/*" ngf-max-size="2MB" required
ngf-model-invalid="errorFile">
<img ng-show="myForm.file.$valid" ngf-thumbnail="subforum.icon" class="thumb"> <button ng-click="subforum.icon= null" ng-show="subforum.icon">Remove</button>
<button class="btn btn-success" type="submit">Create</button>
</form>
``
In my JS
.config(function($stateProvider) {
$stateProvider.state('create', {
url:'/subforum/create',
views: {
'main': {
templateUrl:'subforum/create.tpl.html',
controller: 'CreateCtrl'
}
},
data : { pageTitle : "Create Subforum" }
})
and
.factory('subforumService', function($resource) {
var service = {};
service.create = function (subforum, success, failure) {
var SubForum= $resource ("/web-prog/rest/subforums");
SubForum.save({}, subforum, success, failure) ;
};
.controller("CreateCtrl", function($scope, $state, subforumService) {
$scope.create = function() {
$scope.subforum.author = JSON.parse(localStorage.getItem ("logedUser"));
subforumService.create($scope.subforum,
function(returnedData) {
$state.go("home");
},
function() {
alert("Error creating");
});
};
I know thats not best practice to save user in LocalStorage but for now its like that.
On backend i have controller and in that controller i have methode:
#RequestMapping(method = RequestMethod.POST)
public ResponseEntity<SubForumResource> createPodforum(#RequestBody SubForumResource sentPodforum) {
}
and SubForumResource is
public class PodforumResource extends ResourceSupport {
private String name;
private String desc;
private byte[] icon;}
with geters and seters and everything i need.
So when i have form without image it works without problems. But i need icon too. Im new to angularjs but need it for this project. When i try to use FormData() i dont know how to use $resource. So if someone can help me i would be thankful. This is my first prject i need to work front end so im lost.
You can refer below code for angularjs :
this.addEmployee = function (requestData, file) {
var data = new FormData();
data.append('file', file[0]);
data.append('requestData', new Blob([JSON.stringify(requestData)], {
type: "application/json"
}));
var config = {
transformRequest: angular.identity,
transformResponse: angular.identity,
headers: {
'Content-Type': undefined
}
}
var url = "http://localhost:8080/addEmployee";
var promise1 = $http.post(url, data, config);
var promise2 = promise1.then(function (response) {
return response.data;
},
function errorCallback(response) {
alert(response.data.errorMessage);
});
return promise2;
}
And for controller :
#RequestMapping(value = "/addEmployee", method = RequestMethod.POST, consumes = {"multipart/form-data" })
#CrossOrigin
public CustomResponse addEmployee(#RequestPart("file") MultipartFile file, #RequestPart("requestData") Employee emp) {
}

How to pass String Array from html input to Angular http Post?

I want to pass some text input as array string to angular controller. I'm able to send single input as POST param and get it in Serlvet by using String key = request.getParameter("key");
This is my form
<form ng-controller="FormController" ng-submit="submitForm()" class="ng-valid ng-scope ng-dirty ng-valid-parse">
<p>Text1: <input type="text" name="ancestor" ng-model="blob.ancestor" class="ng-valid ng-dirty ng-touched ng-empty"></p>
<p>Text2: <input type="text" name="ancestor" ng-model="blob.ancestor" class="ng-valid ng-dirty ng-valid-parse ng-empty ng-touched"></p>
<p><input type="submit" class="btn btn-primary" value="Confirm"></p>
</form>
and this is my js script:
var app = angular.module('myApp', []);
app.controller('FormController', FormController);
FormController.$inject = ['$scope', '$http', '$httpParamSerializerJQLike'];
function FormController($scope, $http, $httpParamSerializerJQLike) {
$scope.blob = {};
$scope.submitForm = function() {
alert(JSON.stringify($scope.blob));
$http({
method : 'POST',
url : '/javaAngularJS',
data: $httpParamSerializerJQLike($scope.blob),
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8;'
}
});
};
}
Again, i'm able to send single param but i want to send "ancestor" with multiple values and get it using String ancestors[] = reuest.getParameterValues("ancestor"); in my Post method on servlet.
Let us assume that from your backend you are getting value of ancestor as [1,2,3,4] as array . you can bind this value to input field with ng-repeat like this
In Controller:
$scope.blob = {};
$scope.blob.ancestor = [1, 2, 3, 4];
In HTML:
<form ng-submit="submitForm()" class="ng-valid ng-scope ng-dirty ng-valid-parse">
<p ng-repeat="ancestor in blob.ancestor">Text {{$index +1}}: <input type="text" name="ancestor" ng-model="ancestor" class="ng-valid ng-dirty ng-touched ng-empty"></p>
<p><input type="submit" class="btn btn-primary" value="Confirm"></p>
</form>
Now in submitForm() click we will perform this to send data to backend in array
$scope.submitForm = function() {
console.log($scope.blob); // result:{"ancestor":[1,2,3,4]}
$http({
url: 'http://localhost:8080',
method: "POST",
params: {
ancestor: $scope.blob.ancestor
}
}).success(function(data) {
console.log(data);
}).error(function(data) {
console.log(data);
});
}
The data will go in paramter and the url will look like this:
http://localhost:8080?ancestor=1&ancestor=2&ancestor=3&ancestor=4

Displaying database valuees obtained through a RESTful webservice in a JSP pag

I am implementing a messanger using Jax-Rs. I have a client application which use the implemented API. within the database message_id,message,date, sender fields are stored. I need to display these values within a div of jsp page of the client application.
client.jsp
<form action="ClientServlet" method ="post" onclick="onTechIdChange();"></form>
<div id="uploadSuggest" class="center-block">
<div id="suggestHeading" class="row">
<h4 class="textTitle center-block"> Messages </h4>
</div>
<div class="row">
<div class="col-md-8">
<a id="btn_padding" href="#download" class="btn btn-image pull-left" onclick="onTechIdChange();">Create Profile</a>
<p> </p>
</div>
</div>
</div>
</div>
</section>
<script>
function onTechIdChange() {
var urlPath = "http://localhost:8081/messanger/webapi/messages" ;
$.ajax({
url : urlPath,
dataType : "json",
cache: false,
type : 'GET',
success : function(result) {
var details = result[0];
var name;
for(name in details)
{
dispatchEvent(event)
}
alert(details.sender);
},
error : function(jqXHR, exception) {
alert('An error occurred at the server');
}
});
function display(msg) {
var p = document.createElement('p');
p.innerHTML = msg;
document.body.appendChild(p);
}
}
</script>
Through this code nothing is displayed in the div. But values are printed in the tomcat console which ensures that all the methods within API are working properly. Do you have any idea? Thank you in advance
UPDATE
I Updated the javascript code snippet. But nothing is displayed inside the <p> tag
var urlPath = "http://localhost:8081/messanger/webapi/messages" ;
$.ajax({
url : urlPath,
dataType : "json",
cache: false,
type : 'GET',
success : function(result) {
var details = result[0];
var name;
for(name in details.sender)
{
display(name);
}
alert(details.sender);
},
error : function(jqXHR, exception) {
alert('An error occurred at the server');
}
});
function display(msg) {
var p = document.createElement('p');
p.innerHTML = msg;
document.body.appendChild(p);
}
}
This is the section with the <p>
<form action="ClientServlet" method ="post" onclick="onTechIdChange();"></form>
<div id="uploadSuggest" class="center-block">
<div id="suggestHeading" class="row">
<h4 class="textTitle center-block"> Messages </h4>
</div>
<div class="row">
<div class="col-md-8">
<a id="btn_padding" href="#download" class="btn btn-image pull-left" onclick="onTechIdChange();">Create Profile</a>
<p> </p>
</div>
</div>
</div>
</div>
</section>
If somebody knows a tutorial regarding this can you upload a link?
I think you are not calling the display function that add the values to the DOM.
for(name in details){
display(name)
}
Also I am not sure that your parser is correct
success : function(result) {
var details = result[0]; -- Extract the first value of response
var name;
for(name in details) --- should be an array as well
{
dispatchEvent(event) -- I think here you need to call print function
}
alert(details.sender); -- If details.sender have the details probably the
iteration should be for(name in details.sender)
},
Also I reconsider the use of $.ajax, probably use $.get is better and also, use jsp I dont think is needed use a simple html with a javascript.

how to send json data to server using ajax

refer.jvmhost.net/refer247/registration, this is my url,i have to fetch request to this url like user details and should get the appropriate response in json format with status n error if it contains ..dont give me android code..
this is html page.
<head>
<script type="text/javascript" src="json2.js"></script>
</head>
<body>
<div data-role="page" data-theme="c">
<div data-role="header" data-position="fixed" data-inset="true" class="paddingRitLft" data-theme="c">
<div data-role="content" data-inset="true"> <img src="images/logo_hdpi.png"/>
</div>
</div>
<div data-role="content" data-theme="c">
<form name="form" method="post" onsubmit="return validate()">
<div class="logInner">
<div class="logM">Already have an account?</div>
<div class="grouped insert refb">
<div class="ref first">
<div class="input inputWrapper">
<input type="text" data-corners="false" class="inputrefer" placeholder="Userid" name="userid" id="userid" />
</div>
<div class="input inputWrapper">
<input type="password" data-corners="false" class="inputrefer" placeholder="Password" name="password" id="password" />
</div> <input type="submit" data-inline="true" value="Submit" onclick="json2()">
<p>Forgot Password
</p>
</div>
</div>
<div class="logM">New user? Create refer Account</div>
<input type="button" class="btnsgreen" value="Sign Up! its FREE" class="inputrefer" data-corners="false" data-theme="c" />
</form>
</div>
</div>
<p style="text-align: center;">© refer247 2013</p>
</div>
</body>
this is json2.js
function json2()
{
var json1={"username":document.getElementById('userid').value,
"password":document.getElementById('password').value,
};
//var parsed = jsonString.evalJSON( true );
alert(json1["username"]);
alert(json1["password"]);
};
so tell me how to send the json data to that url n obtain some response like if email
id is already exist if u registering with that id ..then give some error
like email id already exist n if registerd succesfully then give respone like registerd successfully and status msg..200 okk...
You can use ajax to post json data to specified url/controller method. In the below sample I am posting an json object. You can also pass each parameter separately.
var objectData =
{
Username: document.getElementById('userid').value,
Password: document.getElementById('password').value
};
var objectDataString = JSON.stringify(objectData);
$.ajax({
type: "POST",
url: "your url with method that accpects the data",
dataType: "json",
data: {
o: objectDataString
},
success: function (data) {
alert('Success');
},
error: function () {
alert('Error');
}
});
And your method can have only one parameter of string type.
[HttpPost]
public JsonResult YourMethod(string o)
{
var saveObject = Newtonsoft.Json.JsonConvert.DeserializeObject<DestinationClass>(o);
}
$.ajax({
url: urlToProcess,
type: httpMethod,
dataType: 'json',
data:json1,
success: function (data, status) {
var fn = window[successCallback];
fn(data, callbackArgs);
},
error: function (xhr, desc, err) {
alert("error");
},
});
function addProductById(pId,pMqty){
$.getJSON("addtocart?pid=" + pId + "&minqty="+ pMqty +"&rand=" + Math.floor((Math.random()*100)+1), function(json) {
alert(json.msg);
});
}
Here is a simple example, which will call on button click or onclick event and call addtocart servlet and passes 2 argument with it i.e. pId and pMqty.
and after successful completion it return message in alert which is set in that servlet in json.
var json1={"username":document.getElementById('userid').value,
"password":document.getElementById('password').value,
};
$.ajax({
url: '/path/to/file.php',
type: 'POST',
dataType: 'text',//no need for setting this to JSON if you don't receive a json response.
data: {param1: json1},
})
.done(function(response) {
console.log("success");
alert(response);
})
.fail(function() {
console.log("error");
})
.always(function() {
console.log("complete");
});
on the server you can receive you json and decode it like so:
$myjson=json_decode($_POST['param1']);

Json serialize to java pojo with nested List<pojo> property

Below is my code attempt to post an Json serialize object (java pojo having list of other pojos) with JQuery Ajax call to Spring MVC controller.
Getting Bad request error from server.
When the modalForm data is removed from the Json object the MainPojo data received correctly at server side.
Html Code
Fisrt form
-------------
<form id="mainForm">
.....
</form>
Form in the modal
-----------------
<form id="modelform" ..>
<div id="row">
<input type="text" id="subject" />
<input type="text" id="max" />
<input type="text" id="min" />
</div>
<div id="row">
<input type="text" id="subject" />
<input type="text" id="max" />
<input type="text" id="min" />
</div>
.............
</form>}
Jquery
var mainObject = $('#mainForm').serializeObject();
var modelObject = $('#modelform').serializeObject();
mainObject.marks = modelObject;
Json ( Expected)
{
"name": "Some Name",
"age": "10",
"marks": [
{
"subject": "maths",
"max": "20",
"min":"12"
},
{
"subject": "english",
"max": "20",
"min":"12",
}
]
}
Json (actual output with the above code)
{
"name": "Some Name",
"age": "10",
"marks": [
{
"subject": "maths",
"subject": "english"
},
{
"max": "20",
"max":"20",
},
{
"min": "12",
"min":"12"
}
]
}
//Ajax call
$.ajax({
url: '/save',
type: 'POST',
contentType: 'application/json',
mimeType: 'application/json',
data : JSON.stringify(mainObject),
dataType: 'json',
success: function(data) {
alert(data.msg);
},
error:function (xhr, ajaxOptions, thrownError) {
alert('Technical error occured');
}
});
Java Pojo's
public class MainPojo {
private String name;
private String age;
private Lists<marks>
..................
}
public class ModelPojo {
private String subject;
private String maxMarks;
private String minMarks;
.....................
}
Controller Method
#RequestMapping(value = "save", headers = "Accept=application/json",
method = RequestMethod.POST)
public #ResponseBody String save(#RequestBody final MainPojo mainPojo) {
}
Please help me to identify the problem.
Thank You.
Modify html text like this
<form id="mainForm">
<input name="name" type="text" value="Some Name">
<input name="age" type="text" value="20">
</form>
<form class="modelform">
<input type="text" value="subject" name="subject"/>
<input type="text" value="max" name="max"/>
<input type="text" value="min" name="min"/>
</form>
<form class="modelform">
<input type="text" value="subject" name="subject" />
<input type="text" value="max" name="max"/>
<input type="text" value="min" name="min"/>
</form>
Then write javascript code to assign object value
<script>
var mainObject = $('#mainForm').serializeObject();
var modelObject = [];
$('.modelform').each(function(o){
modelObject.push($(this).serializeObject());
})
mainObject.marks = modelObject;
</script>
i have
#RequestMapping(value = "/save", method = RequestMethod.POST)
public #ResponseBody
MyEvent saveOrganization(#RequestBody Organization organization) {
return new MyEvent('save',organization);
}
y your mvc-servlets.xml
<context:component-scan base-package="com.jrey.project.controllers" />
<context:annotation-config></context:annotation-config>
<mvc:annotation-driven>
<mvc:message-converters>
<bean
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
my jquery post
$.fn.serializeObject = function() {
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [ o[this.name] ];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
<script>
$(document)
.ready(
function() {
$('.submit', '#form')
.click(
function() {
var data = JSON
.stringify($('#form')
.serializeObject());
console.log(data);
$
.ajax({
type : "POST",
url : '${pageContext.request.contextPath}/controller/organization',
data : data,
dataType : 'json',
contentType : 'application/json;charset=UTF-8',
success : function(data) {
$(
'<div>'
+ data.message
+ '</div>')
.dialog(
{
title : 'Organizacion',
modal : true,
buttons : {
'Aceptar' : function() {
document.location.href = data.location;
}
}
}
);
},
});
});
});

Categories