Servlet being called twice! - java

sorry but I do not have the actual code with me, but I will try to explain:
I have a servlet mapped to the following:
/admin/*
So, this goes to a servlet:
public class AdminController extends MainController {
public void doPost(HttpServletRequest request, HttpServletResponse response) {
// Do stuf here
}
}
Here is MainController:
public class MainController extends HttpServlet {
#Override
public void service(ServletRequest request, ServletResponse response) {
String requesturi = ((HttpServletRequest)request).getRequestURI();
reqlist = Arrays.asList(requesturi.substring(requesturi.indexOf(Util.rootPath) + Util.rootPath.length()).split("/"));
reqlist = reqlist.subList(1, reqlist.size());
doPost((HttpServletRequest)request, (HttpServletResponse)response);
}
So, the request is passed to AdminController, no problem, but then I reallized something:
The servlet is being called twice!. And this is causing me many errors..
Does anybody have a clue on this? It is because I used some kind of heritance?
Thank you for all!

Though it is old thread but my answer may help someone.
Today I faced the same issue. My particular servlet is working fine earlier and suddenly it has started calling doGet method twice. On investigation, I found that my chrome browser has html validator extension which is calling the servlet again with same request to do html validation.
After I disabling the extension, the problem got resolved.

The HttpServlet.service method gets called for all request types and what you are seeing is a HEAD request and then a GET or POST request. Instead of implementing service just implement doGet or doPost. What is commonly done is to just implement one of doPost or doGet and then call the other from the one you don't have an implementation for.

I solved same problem with simple way.
If you are developing local and access to your app with address http://127.0.0.1 which is loopback network, change address to http://localhost which is direct.
This problem won't happen if you actually run it on webhosting or server and access to it from outer network.

Had the same issue, and I tried anything mentioned above and on other posts, but the issue was only on local.
If nothing works for you too, try a deploy :)

I had the same issue. I had a servlet to handle a post request.
But after calling doPost it suddenly started to call doGet method.
So the doGet was called by a chrome plugin that I installed (FireBug Lite).
Problem solved after I deactivated that plugin.

Related

Why someone calls post() method inside get() method in Servlets?

why we call post() method inside get() method in servlets?
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
Simply only because someone wants to have the same behavior disregarding the HTTP method whether it was POST or GET. So requesting resource with POST does the same as GET.
BUT: doing this - doing the same action - is quite propably wrong. Someone who does this might do it for convenience - for example wants to provide more means to access resource but does not fully understand the difference of GET vs. POST.
It is a matter of idempotency. Good explanation here.
In a nutshell GET should be used when GETting stuff and POSTing when you need to change stuff on the server side.
But what I have experienced some people use GET as long as there too much data for GET and then switch to POST without further thinking about the real difference.

I can't use HttpServlet T-T

I can use Servlet, it is nothing wrong:
this is my Servlet code:
Configuration of web.xml:
But when I use HttpServlet, the mistake happened:
this is My HttpServlet code:
and this is Configuration of it:
I already inspect the things all i imagine.
I have found a lot of places that have no results,
I am a senior high school student in grade two,
If the text is in a mess, I'm sorry, I don't know why the pictures in here will be links. Whether you can help me or not, I still want to thank you for see it.
The problem is this line:
super.doGet(req, resp);
This is delegating to the default implementation of doGet provided by the HttpServlet class. The problem is that that version of doGet is version that is used when you don't implement your own doGet, and its behavior is to tell the remote client that GET is not supported by the servlet.
Solution: remove that call.

Using session to send params to a Liferay Portlet

I need to make a Servlet which will manage some information and, after that, will go to a Liferay 6.2 Portlet. Both in the same server.
I need the Servlet to send a parameter, but I don't want to send it GET, but POST method. So, I try to put it in the session to retrieve it from the Portlet.
At the Servlet, I have:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
request.getSession().setAttribute("param1", "TEST 1");
url = "http://myServer/";
response.sendRedirect(response.encodeRedirectURL(url));
} catch (Exception e) {
e.printStackTrace();
}
}
And at the Portlet I manage the information at render method, as I want to get param1 before I render the page:
public void render (RenderRequest renderRequest, RenderResponse renderResponse)
throws PortletException, IOException {
super.render(renderRequest, renderResponse);
//Try to retrieve from getOriginalServletRequest
HttpServletRequest servletReq = PortalUtil.getOriginalServletRequest(PortalUtil.getHttpServletRequest(renderRequest));
String param1 = servletReq.getSession().getAttribute("param1").toString();
//Try to retrieve from getHttpServletRequest
HttpServletRequest servletReq_ = PortalUtil.getHttpServletRequest(renderRequest);
String param1_ = servletReq_.getSession().getAttribute("param1").toString();
}
As you can see, I tried to retrieve from getHttpServletRequest and from getOriginalServletRequest, but I always get the param1 null.
Any suggestion?
Thank you in advance!
Update question:
I'm being called from a third part, and I'm receiving a GET parameter I want to evaluate.
After that, and not rendering a page in the middle, I want to redirect to one or another Portlet, depending of that evaluation.
I need to send some personal information to those Portlets, so I want to send some parameters in POST method.
A Servlet doesn't fit as doesn't share session with Portlets.
I've tried to implement a landing Portlet, but the redirect can only be done in action phase, so I'd need to render a (empty) page before the redirect, don't like that part. Render phase doesn't allow redirect (even getting PortalUtil.getHttpServletResponse(), doesn't work)
Any suggestion? Thanks!
A servlet and a portlet will not share the same session. The portlet is living within the portal server, e.g. Liferay. The servlet is typically in its own web application, thus completely separated by design.
If you need to communicate between the two, here are two possible solutions/workarounds:
reimplement your servlet as a portlet, potentially utilizing the resource-phase of a portlet
use a request parameter instead of a session attribute
Edit after all of the comments:
It seems best to take a step back and look at the underlying problem - what is the problem that you're actually trying to solve? The content of your question is how you're trying to solve it, and obviously there are challenges. It looks like the problem needs a different solution in the first place.
My answer describes why your solution can't work, but that obviously doesn't help solving the underlying problem.

RestEasy resets all headers when resource throws an exception

I've uncovered something strange while using resteasy-jaxrs in a Cors enabled jBoss server. Here's the setup:
Our server has thetransactioncompany.com's CorsFilter (v1.3.2) enabled as a servlet filter to enable CORS and add the appropriate CORS headers to the HttpServletResponse object.
The server itself is using resteasy-jaxrs (v2.3.2.Final) to serve JSON endpoints to power our app, obviously running on a separate domain.
The issue is that if one of my endpoint methods generates any type of exception (NPE, UnauthorizedException, InternalServerErrorException), as a part of preparing the response, RestEasy makes the call
(HttpServletResponse)response.reset()
which clears out my CORS headers. This causes Chrome to rightly act as if the request should be canceled. This is really inconvenient for my front end dev who needs those error codes.
Two questions:
Why would RestEasy want to clear those headers?
Has anyone else run across this and have any workarounds?
I am actually surprised to see that you have encountered this behavior since I've never seen it, and I certainly have generated plenty of exceptions in my day.
Regardless, consider writing a custom ExceptionMapper as described here. You can populate the response with your CORS headers and return it from toResponse along with the appropriate error information.
I ran into this issue too, and I had a workaround by using a response wrapper
class CorsHeaderResponseWrapper extends HttpServletResponseWrapper{
public CorsHeaderResponseWrapper(HttpServletResponse resp) {
super(resp);
setCorsHeader();
}
void setCorsHeader(){
HttpServletResponse resp = (HttpServletResponse)getResponse();
//set cors header here
}
public void reset(){
super.reset();
//set again if anyone reset it
setCorsHeader();
}
}
when calling doFilter
chain.doFilter(req, new CorsHeaderResponseWrapper(resp));

Java Servlet POST action not receiving parameters from request

Yesterday I tried using Tomcat and Servlets for the first time (I come from IIS/C#/MVC).
I'm also using AngularJS and Guice.
I've made a Servlet that has a single method:
#Singleton
#SuppressWarnings("serial")
public class CommandServlet extends HttpServlet {
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
System.out.println(req.getParameterMap());
}
}
I've made a service in Angular that looks like the following:
app.factory('console', [ '$http', function($http) {
var console = {};
console.execute = function(gameId, command) {
$http.post("Command/", {
gameId : gameId,
command : command
}).success(function(data, status, headers, config) {
}).error(function(data, status, headers, config) {
});
};
return console;
} ]);
In my controller I inject the service and expose it to the view via an "execute" function on the scope:
app.controller('PlayController', function($scope, console) {
$scope.consoleIn = "";
$scope.gameId = 1;
$scope.execute = function(command) {
$scope.consoleOut = console.execute($scope.gameId, command);
};
});
And in my view I have a button which calls the function and passes in text from an input element:
<input ng-model="consoleIn" type="text">
<button class="btn" type="button" ng-click="execute(consoleIn)">Go!</button>
For some reason the console on my Tomcat server is printing an empty Map ({}) without the parameters being passed with the POST request. When I look at the network tab in Chrome's Console thingy and see that the parameters are being sent ({"gameId":1,"command":"a"}), so my question is 1) Am I doing the right thing to get the values out of the POST request (getParameterMap() ?) and 2) if I am doing the right thing, what am I doing wrong so that the request my browser makes isn't getting to my servlet properly?
EDIT:
I ended up using Jersey as my container (I think it's called) instead of Java's default Servlets. I did this after seeing Jersey popping up with Guice often on Google, thinking there would be sufficient documentation to get the two of them working together. There are several examples and I sort of drew on several, especially this one.
The snag I ran into getting it to work was this, but now everything's good to go.
Overall I'd say that if you like Guice for your DI and want to make a Java website, Jersey is good. It appears to be for a different more specialized functionality of RESTful services than regular servlets - but that's what I needed, anyway. From my un-scientific Googling observations besides Tomcat there's Grizzly and Jetty that are popular as well - you may want to look into them if you're having trouble with Tomcat.
I hope this edit saves someone the hours I spent yesterday and today getting it to work.
What does it actually print? Some of the Tomcat Map implementations don't print their contents in their toString() method. Try another way of seeing what's in it. You'll find its all there.

Categories