angular send post request but servlet keep showing nul value - java

i have angular controller which triggered with ng-click:
app.controller('showAllWorkersContoller', function($scope, $http){
$http.get("/SafetyManager/workers").success(function(response){
$scope.workers = response;
$scope.workerInfo = function(id){
$http({
url: '/SafetyManager/workers',
method: "POST",
data: { 'ID' : id },
}).success(function(response){
$scope.info = response;
});
};
});
});
and when i check on chrome debug it sends in form data: {'ID':"1"} (or any other id num according to the worker i click on)
but when the Servlet get the request:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("post request to Workers (get worker by id )");
String id = request.getParameter("ID");
System.out.println("this id is: " + id);
}
its print :
post request to Workers (get worker by id )
this id is: null
how can i get the ID value in the servlet?

The data that you post will not be available as a request parameter, it is in the request body.
You can use a reader to read content from body.
Refer: Getting request payload from POST request in Java servlet

You have to use req.getAttribute(name) to get body content.
Refer this blog:
Difference between getAttribute() and getParameter()

Related

Get OkHttp PUT request parameters in Servlets

I'm making a PUT request using OkHttp 4.9.1 from my Android app as below,
RequestBody reqBody = new FormBody.Builder()
.add("name", name)
.add("phone", phone)
.build();
Request request = new Request.Builder()
.url(API_URL)
.put(reqBody)
.build();
new OkHttpClient().newCall(request).enqueue(new Callback() {
...
});
The request comes to the server but the problem is I cannot access the parameters from the Servlet,
#Override
protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("NAME: " + req.getParameter("name"));
System.out.println("PARAMS: " + new HashMap(req.getParameterMap()).toString());
System.out.println("CT: " + req.getContentType());
}
below is the output log from the server,
NAME: null
PARAMS: {}
CT: application/x-www-form-urlencoded
As you can see the parameter map is empty. What am I missing?
request.getParameter() is not working in Servlets when it comes to PUT requests. So this was not a problem with OkHttp. As to why request.getParameter() is not working in doPut(...) refer the post below,
Servlet request.getParameter() returns null in PUT but not in POST

java spring boot HTTP POST request not working

For my application I am writing a POST request to send array of parameters from a checkbox list. Its working for get request but not working for post request. What is the error in my code.
My code on the client side for sending ajax request to the server.
$(".add").click(function(){
monitoring.length=0;
nonMonitoring.length=0;
$('.modal-body input:checked').each(function() {
monitoring.push($(this).val());
});
$('.addkeywords input:checked').each(function() {
nonMonitoring.push($(this).val());
});
// alert(monitoring[2]+ " " + nonMonitoring[2]);
var monitoringLength=monitoring.length;
var nonMonitoringLength=nonMonitoring.length;
$.ajax({
type : "POST",
url : '/rest/channelstats/my/rest/controller',
data : {
// monitoring : monitoring,
// nonMonitoring: nonMonitoring,
monitoringLength: monitoringLength,
nonMonitoringLength: nonMonitoringLength,
},
success : function(data) {
// var keywordsList=data
//console.log(keywordsList);
// htm = "" ;
}
});
})
My java code on the server side.
#RequestMapping(value="/rest/channelstats/my/rest/controller",method = RequestMethod.POST)
public void monitorKeywords(#RequestParam(value="monitoringLength",required=true)int monitoringLength,#RequestParam(value="nonMonitoringLength",required=true)int nonMonitoringLength){
System.out.println("MonitoringLength =>" +monitoringLength);
System.out.println("NonMonitoringLength=>" +nonMonitoringLength);
}
}
Its working for HTTP GET requests but not working for POST requests.How should I solve this problem?
According to your jquery post request, you should use DAO(Data Access Object) to parse the request data. So you should add class Request
public class Request {
private int monitoringLength;
private int nonMonitoringLength;
//getters and setters
}
And change controller to
#RequestMapping(value="/rest/channelstats/my/rest/controller",method = RequestMethod.POST)
public void monitorKeywords(#RequestBody Request request){
System.out.println("MonitoringLength =>"+request.getMonitoringLength());
System.out.println("NonMonitoringLength=>"+request.getNonMonitoringLength());
}

My Titanium Post Works, how do I display in Java Servlet?

Hi im trying to send data from my titanium app to my Apache Web Service. The snippet of titanium code works as the output to the console is success. Now what im trying to do is when the post is sent, display the contents of the post on the web service page. Is my doPost correct?
Titanium Snippet
button.addEventListener('click', function(e) {
var params = {
"places" : {
Country : textCountry.getValue(),
Capital : textCapital.getValue()
}
};
var xhr = Ti.Network.createHTTPClient({});
// function to deal with errors
xhr.onerror = function() {
Ti.API.info('error, HTTP status = ' + this.status);
alert('Error Sending Data');
};
// function to deal with response
xhr.onload = function() {
console.log('success, HTTP status = ' + this.status);
};
xhr.open("POST", 'http://130.206.127.43:8080/Test');
//set enconding
xhr.setRequestHeader("Content-Type", "application/json; charset=utf-8");
xhr.send(JSON.stringify(params));
});
Java Servlet/Apache Tomcat Snippet
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
String jsonData = request.getParameter("json");
response.setContentType("applicaiton/json");
PrintWriter out= response.getWriter();
out.println(jsonData);
out.close();
}
18/02/205
// function to deal with response
xhr.onload = function() {
console.log('success, HTTP status = ' + this.status);
Ti.API.info('json' + this.responseText);
};
[INFO] : success, HTTP status = 200
[INFO] : json = null
Set a breakpoint in the xhr.onload and look at the variables that are present before your write your log.
You are looking for the this.responseText, which will have the response from your call to the Java servlet. I mainly use WCF and C# and if I don't setup the WCF service specifically to clean-up the output, it will add the function name to the response.
Generally, my onload looks like this.
xhr.onload = function(){
var result = JSON.parse(this.responseText);
Ti.API.log(result);
}
* Look closer at your Java Servlet return type. It is a VOID return type so no data will be returned to the http call. *
http://docs.appcelerator.com/titanium/3.0/#!/api/Titanium.Network.HTTPClient

jquery ajax call returns error on successful call to a servlet

I have a servlet that adds a user to a file on the server side.
I invoke it with a jqueries ajax call.
I can see on the server that the method is being called correctly and my user is added, but the error callback is being invoked on the jquery call. All the status text says is error.
Using firebug the response seems to be empty. Why can I not get a success jquery callback?
//Servlet Code
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String action = request.getParameter("action");
String responseStr = "";
if(action.equals("addUser"))
{
responseStr = addUser(request);
}
System.out.println("Reponse:" + responseStr);
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
response.getWriter().println(responseStr);
}
private String addUser(HttpServletRequest request) throws IOException
{
Storage s;
s = Storage.load();
String name = request.getParameter("name");
String imageUrl = request.getParameter("imageUrl");
User u = new User();
u.setName(name);
u.setImageUrl(imageUrl);
s.addUser(u);
s.save();
return "success";
}
.
//javascript code
function addUser() {
var name = $('#name').val();
var imageUrl = $('#imageUrl').val();
var url = "http://ws06525:8080/QCHounds/QCHoundServlet?action=addUser&name=${name}&imageUrl=${imageUrl}";
url = url.replace("${name}", name);
url = url.replace("${imageUrl}", imageUrl);
$('#result').html(url);
$.ajax({
url: url,
success: function( data ) {
$('#result').html(data);
},
error: function(jqXHR, textStatus, errorThrown)
{
alert("error: " + textStatus);
alert("error: " + errorThrown);
}
});
}
Aaargh! Feel like an idiot. It's a cross site scripting issue.
I was testing the call to the server from the html file on disk so my browser address was
file://projects/myproject/content/Users.html <<< Fail
instead of:
http://myboxname:8080/appname/Users.html <<< Works
The actual code is fine...
use this for learn what is the problem, it will be better for get solution i think
error: function(e){
alert(JSON.stringify(e))
}
For one thing the string "success" isn't valid json. If your ajax query is expecting json, that would fail it.
What if you returned "{ \"success\": true }" ?
EDIT
It looks like from your ajax call that the response shouldn't be json, why is your return content type json?
If it is true that firebug shows no response, your problem must be in the java code that writes the response.

Making AJAX POST request to Servlet fails

From my client side code, I am making an AJAX call to my servlet. If I use GET as request method. Everything works and I get response back. But when I send request as POST, servlet fails to send the response. From log I found out that in servlet "request" object is null when made ajax call with POST. According to this post:
Servlet response to AJAX request is empty , I'm setting headers for same-origin policy.
Below is my code for reference:
function aimslc_ajaxCall(url,callback, postParams){
var xmlhttp = null
if (window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
eval( callback+"("+xmlhttp.responseText+")" );
}
}
if(postParams!=null && typeof postParams!="undefined" ){
xmlhttp.open("POST",url,true);
xmlhttp.send(postParams);
}else{
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
}
Servlet Code:
public void doProcess (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
logger.info("doProcess::start..."+request.getQueryString());
response.setHeader("P3P","CP='NOI ADM DEV PSAi COM NAV OUR OTR STP IND DEM'");
response.setHeader("Access-Control-Allow-Origin","*");
response.setHeader("Access-Control-Allow-Credentials","true");
response.setHeader("Access-Control-Allow-Methods","POST, GET");
}
Throws a null exception on request.getQueryString()
if you do a post all the data is in the request body, not on the url. From here you see that getQueryString only gets the stuff on the url.
See here for how to get the request body.
Also, if your data is name/value pairs, you might want to use getParameter and associated methods.
If the request is null, I ask do you implement doPost on your servlet?

Categories

Resources