AngularJS http POST to Servlet - java

I went through a lot of StackOverflow answers and googled a lot but still could not find why my post request is not working.
This is my jsp:
<div class="container">
<form class="form-signin" ng-controller="MyController">
<h2 class="form-signin-heading">Please sign in</h2>
<label for="username" class="sr-only">Username</label>
<input type="text" id="username" ng-model="user.name" class="form-control" placeholder="Username" required autofocus>
<label for="password" class="sr-only">Password</label>
<input type="password" ng-model="user.password" id="password" class="form-control" placeholder="Password" required>
<button class="btn btn-lg btn-primary btn-block" ng-click="login()" type="submit">Sign in</button>
</form>
</div>
This is my controller:
app.controller('MyController', function($scope, $http) {
$scope.login = function() {
console.log($scope.user);
$http({
method : 'POST',
url : 'login',
data : $scope.user,
headers: {
'Content-Type': 'application/json'
}
}).success(function(data) {
console.log(data);
}).error(function(data) {
console.log(data);
});
console.log("POST done");
};
});
And my servlet:
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
System.out.println("inside do POST");
Gson gson = new Gson();
JsonParser parser = new JsonParser();
JsonObject obj = (JsonObject) parser
.parse(request.getParameter("data"));
Iterator it = (Iterator) obj.entrySet();
while (it.hasNext()) {
System.out.println(it.next());
}
System.out.println("over");
}
I keep getting this Null pointer exception
java.lang.NullPointerException
at java.io.StringReader.<init>(StringReader.java:50)
at com.google.gson.JsonParser.parse(JsonParser.java:45)
at com.zookeeperUI.controller.Login.doPost(Login.java:40)
Please tell me what am I doing wrong here .

Your request does not contain a URL parameter named "data", therefore request.getParameter("data") returns null and you get the NullPointerException.
You try to send a Javascript object via URL parameters which does not go well with non-shallow objects.
I would recommend to send the data as request payload:
JsonObject obj = (JsonObject) parser.parse(request.getReader());
On the client you need to make sure that your data is sent as proper JSON:
$http({
method : 'POST',
url : 'login',
contentType: 'application/json',
data : JSON.stringify($scope.user),
})...

i think you should be sending data as
$http({
method : 'POST',
url : 'login',
data : {data: $scope.user},
headers: {
'Content-Type': 'application/json'
}
}).success(function(data) {
console.log(data);
});
pay attention to data : {data: $scope.user}

You are using a POST request and your data is sent in the request body - not as parameter. You need to read the content using request.getReader().
// example using the javax.json.stream package
JsonParser parser = Json.createParserFactory().createParser(request.getReader());

Related

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

in spring framework how to get response from controller to jsp page by ajax call passing an id value to controller

In my program i need to perform an operation by passing id.The id is selected from a dropdown box(ie;changing dynamically).so to pass the id i'am using ajax.but i don't know the code to receive the response back from controller in spring.
<div class="form-group">
<label class="col-sm-4 control-label">Employee</label>
<div class="col-sm-6">
<select id="empId" name="empId" class="form-control" >
<option value="" >--Select--</option>
<c:forEach var="row" items="${employeeList}" >
<option value="${employeeList.Id}">${employeeList.name</option>
</c:forEach>
</select>
</div>
<div class="col-sm-6">
<input type="text" name="empname" id="empname" class="form-control"/>
</div>
</div>
//i need to pass the employee id from the dropdown box to controller and get //the name of the employee as response .and set the response value in the text //box.how can be it done in spring using ajax.
//ajax code i tried
$('#empId').change(function(event) {
var eId= $("select#empId").val();
$.get('getEmpName', {
id: eId
}, function(data) {
$('#empname').val(data);
});
});
//but i am not getting any response ie:nothing in data
Here the ajax side code:
$('#empId').change(function() {
$.ajax({
type: 'POST',
dataType: 'json',
url: 'your_url', // in your controller side (RequestMapping value)
data: 'empId='+$('#empId').val(),
success: function(responseData, textStatus) {
// your stuff here. you found the response in responseData var.
},
complete: function(textStatus) {
},
error: function(responseData)
{
}
});
});
And your controller side code like something below,
#RequestMapping(value = "your_url", method = RequestMethod.POST)
public ResponseEntity<String> postMethod(HttpServletRequest req) {
String jsonString = "";
String empId = req.getParameter("empId");
// your operation done here and
//convert it to json format before sending response.
jsonString = gson.toJson("your response convert here to json format"); // here i used google Gson library to convert your response in json format.
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.add("Content-Type", "text/html; charset=utf-8");
return new ResponseEntity<String>(jsonString, responseHeaders, HttpStatus.CREATED);
}

How to check if form was submitted in Java

I have a form in jsp:
<form id="emailForm" data-role="form">
<input type="text" class="form-control" id="name" name="name" placeholder="Enter full name..">
<input type="submit" id="emailSubmit" name="emailSubmit" class="btn btn-default" value="submit">
</form>
I send the form to controller using AJAX:
$("#emailSubmit").click(function(e){
e.preventDefault(); //STOP default action
var postData = $("#emailForm").serializeArray();
$.ajax(
{
type: "POST",
url : "HomeController",
data : postData,
success: function(data)
{
$("#emailResult").html("<p>Thank your for submitting</p>);
},
error: function(jqXHR, textStatus, errorThrown)
{
$("#emailResult").html("<p>ss"+errorThrown+textStatus+jqXHR+"</p>");
}
});
});
I check if it has been submitted in Controller here:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String emailSubmit = request.getParameter("emailSubmit");
if(emailSubmit != null){
// continue
}}
Can someone please tell me why when it checks if form was submitted in the controller that it is null?
For forms the standard way is to catch the submit event instead of the click event of the button:
$("#emailForm").submit(function(e){
e.preventDefault();
var postData = $(this).serializeArray(); // or: $(this).serialize();
$.ajax({
type: "POST",
url : "HomeController",
data : postData,
success: function(data)
{
$("#emailResult").html("<p>Thank your for submitting</p>);
},
error: function(jqXHR, textStatus, errorThrown)
{
$("#emailResult").html("<p>ss"+errorThrown+textStatus+jqXHR+"</p>");
}
});
});
I have tried several methods to be able to check the submit button isn't null and can't solve that issue. For now I have set a hidden input field in the form like so:
<input type="hidden" name="form" value="contactForm">
In controller I check for the form:
String form = request.getParameter("form");
if(form.equals("contactForm")){
// continue
}
Doing this enables me to know which form has been posted to the controller.

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']);

JSP form values passed to a servlet

I have a form in JSP in the following manner :
<form id="provision-field" method="post" action="${pageContext.request.contextPath}/myServlet">
<fieldset>
<ol class="fields">
<li>
<label for="field1">field1</label>
<input type="text" id="field1" "
value="<%= field1 %>"
/>
<span class="description">
<span class="optional">Optional</span>
</span>
</li>
</ol>
</fieldset>
<div class="actions">
<button type="submit" name="Submit">
Submit form
</button>
Cancel
</div>
</form>
I have a js snippet on click of the submit button does the following
var field = document.getElementById("field1").value;
$.ajax({
url: '${pageContext.request.contextPath}/myServlet'
type: 'POST',
data: field,
dataType: "html",
success: function(html) {
alert("Success");
},
error: function(error){
alert("ERROR");
}
});
When I just use the form element (ie take out the js code) , I can reach my servlet but none of my form parameters are passed . when I try using the js code , the ajax request does not work . could someone point to me how this should be correctly done .
The servlet code is :
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
logger.info("Inside the post function");
logger.info(request.getParameter("data");
}
var field = document.getElementById("field1").value;
$.ajax({
url: '${pageContext.request.contextPath}/myServlet'
type: 'POST',
data: {
data :field
},
dataType: "html",
success: function(html) {
alert("Success");
},
error: function(error){
alert("ERROR");
}
});
Inside servelt following code in doPost method :
Assuming that you have primary knowledge of HttpServlet...
request.getParameter("data");
I am sharing small Ajax with Servlet tutorial , which may help you for further problem... Download Link- AJAX Servlet Tutorial
data: { field1:field1Value } send like this
and then access request.getParameter("field1"); in servlet
As form submission method is post method="post", you need to make sure you are fetching request values in doPost(request, response) method

Categories