AngularJS posting data to servlet not working - java

I'm trying to post data from Angular to my servlet. But, it throws me the error
"Failed to load resource: the server responded with a status of 405 (Method Not Allowed)"
Here is my code. Am I missing anything?
$scope.pushDataToServer = function() {
$scope.data = {user_id:"123",key_name:"key2",value:"value2"};
$http({
method: 'POST',
url: 'pushData',
headers: {'Content-Type': 'application/json'},
data: $scope.data
}).success(function (data){
$scope.status=data;
}).error(function(data, status, headers, config) {
alert("error")
});
};
My servlet config
<servlet>
<servlet-name>pushData</servlet-name>
<servlet-class>com.data.pushData</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>pushData</servlet-name>
<url-pattern>/pushData</url-pattern>
</servlet-mapping>

write a do post method in your servlet.
/**
* handles HTTP POST request
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException {
//TODO: handle POST here
}

Simple, the servlet you are calling doesn't support the POST method.
You haven't implemented it or has done so erroneously.

Related

Java Servlet - response.sendRedirect() returning file source

I have a log in page and if the user goes to login.jsp, I call
$http.post("AutoLogin?uuid=" + uuid).then(
function(response) {
console.log(response);
}, function(error) {
console.log(error);
}
);
Then in my servlet I have:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//Check user is logged in
//if user is logged in
response.sendRedirect("portal.jsp#/dashboard.jsp");
return;
}
But the redirect does not happen and in the response I see it console.log the html of dashboard.jsp. Why wont it redirect?
Thanks
The request you are sending through AJAX. Here what happens the request and response calls works fine, but the response you are getting that is limited to that AJAX call, hence you will get that particular response through the AJAX response only.
Please make the call either by not using AJAX or after getting the response make it redirect from function(response) method in jquery/javascript.

ajax call to java servlet results in 404 [duplicate]

This question already has answers here:
HTTP Status 404 - Servlet [ServletName] is not available
(4 answers)
Closed last year.
I'm trying to get a web page to send JSON data to a java servlet via a jQuery ajax POST.
I've already checked everything I could think of, but I still can't figure out why I keep getting a 404.
Even more confusing is that other calls to the same context path work correctly.
My web.xml
<web-app>
<servlet>
<servlet-name>Controller</servlet-name>
<servlet-class>com.vibridi.klyr.servlet.Controller</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet>
<servlet-name>CustomerServlet</servlet-name>
<servlet-class>com.vibridi.klyr.servlet.CustomerServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Controller</servlet-name>
<url-pattern>/klyr</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Controller</servlet-name>
<url-pattern>/home</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>CustomerServlet</servlet-name>
<url-pattern>/klyr/customer/*</url-pattern>
</servlet-mapping>
My ajax call:
$.ajax({
url: "customer/save",
type: "POST",
data: JSON.stringify(o),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(obj) {
alert('Customer saved');
},
error: function(obj) {
alert('Error!');
}
});
My servlet:
public class CustomerServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static Logger logger = Logger.getLogger("KLYR_LOGGER");
private CustomerManager manager;
public void init(ServletConfig sconfig) throws ServletException {
super.init(sconfig);
manager = new CustomerManager();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//stuff
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
response.setContentType("application/json;charset=utf-8");
try {
StringBuffer sb = new StringBuffer();
String line = null;
BufferedReader reader = request.getReader();
while((line = reader.readLine()) != null) {
sb.append(line);
}
manager.saveCustomer(sb.toString());
} catch(Exception e) {
logger.log(Level.SEVERE, "Data processing failure: " + e.getMessage());
out.write(Convertor.createBaseJSON(JSONType.E).toString());
out.close();
}
out.write(Convertor.createBaseJSON(JSONType.S).toString());
out.close();
}}
}
I can see from the Chrome's debugger tools that the call is properly directed to http://localhost:8080/klyr/customer/save but it 404's, whereas http://localhost:8080/klyr does not.
Thanks a lot!
EDIT:
I've tried to switch the servlet mappings over, i.e. /klyr (the working one) on CustomerServlet and /customer/save on Controller, but nothing happens, in fact when I call /klyr from the browser bar instead of seeing the response from CustomerServlet.doGet I still see the welcome page as if Controller.doGet fired. It looks like tomcat isn't reloading the web.xml file even if I restart it. Any ideas?
This is obvious because your CustomerServlet does not bind to $.ajax({url: "customer/save", ... so it won't work, your should change the below code :
<servlet-mapping>
<servlet-name>CustomerServlet</servlet-name>
<url-pattern>/klyr/customer/*</url-pattern>
</servlet-mapping>
to something like:
<servlet-mapping>
<servlet-name>CustomerServlet</servlet-name>
<url-pattern>/customer/save</url-pattern>
</servlet-mapping>
in order to solve the problem ~
I've eventually found the culprit, gonna post it here as a reference for other people.
Both servlets mapped in my web.xml are loaded on startup.
The first servlet attempted to read a config file from an incorrect path inside its init() method, but couldn't find it and threw an exception. The Catalina startup routine exited before it could load the second servlet, hence the 404 error.

Restlet 1.1 Access Control Header Issue

I'm working on a restlet built on restlet 1.1.1
The issue I'm facing is setting the 'Access-Control-Allow-Origin' header to allow for cross domain requests. I've attempted a few things that didn't work.
Method one, put the header in the acceptRepresentation function:
#Override
public void acceptRepresentation( Representation resetEntity ) {
Form headers = (Form)getResponse().getAttributes().get("org.restlet.http.headers");
if (headers == null) {
headers = new Form();
getResponse().getAttributes().put("org.restlet.http.headers", headers);
}
headers.add("Access-Control-Allow-Origin","https://origin.server.edu");
//other code here for actual resource logic...
}
This didn't work. I still received errors when attempting to send a request using JQuery as such:
jQuery.ajax({
type: "POST",
contentType: "application/json",
url: "https://test.servername.edu/cas/cas-rest-api/reset/",
data: JSON.stringify("{\"uname\" : \"someone\", \"attr\":\"dataElement\" }"),
dataType: "json",
crossDomain: true
})
.done(function(data){
console.log("Success");
alert(data);
})
.fail(function(data){
console.log("failure");
console.log(data);
alert(data);
});
This didn't work. So I noticed an init function in the resource class. I figured I'd attempt putting my code there to see if this would change the situation.
#Override
public void init(Context context, Request request, Response response ){
Form headers = (Form)response.getAttributes().get("org.restlet.http.headers");
if (headers == null) {
headers = new Form();
response.getAttributes().put("org.restlet.http.headers", headers);
}
headers.add("Access-Control-Allow-Origin","https://origin.server.edu");
super.init(context, request, response);
}
Nope. Didn't work either. What am I missing here? Where do I set this header?
Thanks for your replies. After some analysis of the problem it turned out that I needed to configure Spring to allow option requests for my restlet in the web.xml file as shown below:
<servlet>
<servlet-name>ccrest</servlet-name>
<servlet-class>com.noelios.restlet.ext.spring.RestletFrameworkServlet</servlet-class>
<init-param>
<param-name>dispatchOptionsRequest</param-name>
<param-value>true</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>

how to return data to ajax from java Servlet [duplicate]

This question already has answers here:
How should I use servlets and Ajax?
(7 answers)
Closed 4 years ago.
i have my ajax function as follows:
$.ajax({
type: 'GET',
url: "/myservlet",
data: {
objects: '2',
dimension: '2',
},
success: function( data ) {
console.log(data);
alert(data);
},
error:function(data,status,er) {
alert("error: "+data+" status: "+status+" er:"+er);
}
});
and i have my servlet to process the data sent to /myservlet. I read from the ajax tutorial which said the data in the success function is the data that ajax got from the server side. But i don't know how to set this data or return this data from doGet method in a Java servlet to the frontend. It seems doGet is a void method and cannot return any values, isn't it? I am a freshman in web development, thanks in advance!
You can get the data from servlet by writing on response.getWriter().write("");.
Here is a simple servlet example.
#WebServlet(name = "MyServlet", urlPatterns = {"/myservlet"})
public class MyServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
response.getWriter().write("Success Data");
}
}
You might notice that the doGet() method has two parameters: HttpServletRequest and HttpServletResponse.
You use HttpServletRequest to get information about the request - any parameters, the calling client IP, the URL etc.
http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html
You use HttpServletResponse to populate the response. HttpServletResponse has a number of methods allowing you to set response headers and data.
http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletResponse.html
You no need to return any thing from the doGet method , infact you can not as it's void.
So what you need to do is get the PrintWriter object from the response and write data to it and that will available in the success function .

Jquery ajax call is not hitting servlet

I am trying to make a simple ajax call. No matter what I do, it always executes the error block. I have a sysout in the doPost that is never hit. Someone please tell me what I am doing wrong. Here is my code.
javascript----
$.ajax({
url: "GetBulletAjax",
dataType: 'json',
success: function(data) {
alert("success");
},
error: function(jqXHR, textStatus, errorThrown) {
alert(jqXHR+" - "+textStatus+" - "+errorThrown);
}
});
Java----
public class GetBulletAjax extends HttpServlet {
private static final long serialVersionUID = 1L;
public GetBulletAjax() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("made it to servlet");
PrintWriter out = response.getWriter();
User user = (User) request.getSession().getAttribute("user");
int userId = user.getId();
List<Bullet> bullets;
BulletDAO bulletdao = new BulletDAOImpl();
try {
bullets = bulletdao.findBulletsByUser(userId);
Gson gson = new Gson();
String json = gson.toJson(bullets);
System.out.println(json);
out.println(json);
out.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
web.xml----
<servlet>
<servlet-name>GetBulletAjax</servlet-name>
<servlet-class>bulletAjax.GetBulletAjax</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>GetBulletAjax</servlet-name>
<url-pattern>/GetBulletAjax</url-pattern>
</servlet-mapping>
What's the URL for your client? Your URL is going to be relative -- so if your page's URL is <server>/foo/bar.html, your ajax request is going to go to <server>/foo/GetBulletAjax. But your servlet definition is <server>/GetBulletAjax.
Change your url in your ajax request to /GetBulletAjax. You need the leading forward slash to tell the browser the resource is located off the root of the site.
in Jquery documentation
http://api.jquery.com/jQuery.ajax/
type (default: 'GET')
Type: String
The type of request to make ("POST" or "GET"), default is "GET". Note: Other HTTP request methods, such as PUT and DELETE, can also be used here, but they are not supported by all browsers.
seems that you miss the type attribute which needs to be POST. default is GET as mentioned by documentation. You dont have a doGet in your servlet to support that.
$.ajax({
url: "GetBulletAjax",
dataType: 'json',
type:POST,
success: function(data) {
alert("success");
},
error: function(jqXHR, textStatus, errorThrown) {
alert(jqXHR+" - "+textStatus+" - "+errorThrown);
}
});

Categories