I have the servlet name ExampleServlet.java which have only init method with HttpServletRequest and HttpServletResponse parameters. I will forward the request to another servlet named ForwardedServlet.java which will display some text on the web page. But when i am trying to execute the ExampleServlet http://localhost:8080/Sample/ExampleServlet
the following error occurs.
The request sent by the client was syntactically incorrect (HTTP method GET is not supported by this URL).
Please give the solution and why it this error occured...
Thanks in advance
You haven't implemented the 'doGet' method, so it's falling back to the default implementation, which is a 503 server error (or some variant).
The init is only called once, when the servlet is instantiated - it's not called once per request, which you'll need to do.
Also, make sure the capitalisation and arguments are correct; if you use something else, it won't be the right method that the Servlet API calls.
Related
I am studying for the Spring Core certification and I have some doubts about how Spring handles REST requests.
I know that with REST the resources are exposed as name and that the actions on these resources are the HTTP methods, such as GET, PUT, POST, and DELETE.
And I know that requests are handled by the use of #RequestMapping annotations over the method that handles the operation on the resource.
From what I have understood, both standard web applications and RESTful applications use some codes to communicate with their clients (the RESTful application have an expanded set of codes) that I think represent the status of the request (for example 200 is the request is a successful GET returning content, etc.).
Now the documentation shows the use of the #ResponseStatus annotation as in this example:
#RequestMapping(value="/orders", method=RequestMethod.POST)
#ResponseStatus(HttpStatus.CREATED) // 201
public void createOrder(HttpServletRequest request, HttpServletResponse response) {
Order order = createOrder(request);
// determine full URI for newly created Order based on request
response.addHeader("Location",
getLocationForChildResource(request, order.getId()));
}
So looking at the previous method I know that it handles HttpRequest POST requests towards the resource named /orders (using REST the resource is seen as an URL, is that correct?).
But what exactly does the annotation below do:
#ResponseStatus(HttpStatus.CREATED) // 201
I know that the 201 status code means that a new resource was created on POST.
And looking at the official documentation I can read:
Marks a method or exception class with the status code and reason that
should be returned. The status code is applied to the HTTP response
when the handler method is invoked, or whenever said exception is
thrown.
So what exactly it means? I think that as is done in the previous example it sets the 201 status that says that the resource is correctly created by the POST request. If this is correct I have 2 questions:
The resource is the /orders URI. So what is created? a file named orders (I think that this assertion is false) or what?
Where the 201 status is put?
201 is an HTTP status code. It indicates that the
request has been fulfilled and resulted in a new resource being created.
So if your server is returning such a status code, then the client understands that some (conceptual) resource was created. What that resource is is your responsibility, you're the server.
A status code is part of the HTTP response status line.
Actually, the JavaDocs for the ResponseStatus annotation warn us not to use this annotation for REST APIs. This annotation will cause Spring to call the HttpServletResponse.sendError() method, which will result in an HTML Error page. You don't want that in a RESTful service. Here's what it says:
Warning: when using this annotation on an exception class, or when setting the reason attribute of this annotation, the HttpServletResponse.sendError method will be used.
With HttpServletResponse.sendError, the response is considered complete and should not be written to any further. Furthermore, the Servlet container will typically write an HTML error page therefore making the use of a reason unsuitable for REST APIs. For such cases it is preferable to use a ResponseEntity as a return type and avoid the use of #ResponseStatus altogether.
I am working on a Java Portlet (extending GenericPortlet), using JBoss 7.02 and LifeRay Portal 6.1.0 GA1. This is one of the bundles that can be downloaded from LifeRay's release archive.
During deployment, when the init() method is called, getRequestDispatcher() returns null. Below is the exact error message:
09:22:15,972 ERROR [org.apache.catalina.core.ContainerBase.[jboss.web].[default-host].[/my-portlet-name]] (MSC service thread 1-15) Error during mapping: java.lang.NullPointerException
Below is a snippet from my init() method:
PortletConfig config = getPortletConfig();
PortletContext context = getPortletContext();
PortletRequestDispatcher normalView = context.getRequestDispatcher("/portlet.jsp");
As a temporary workaround, I have moved all getRequestDispatcher() calls to doView() where it executes without problem. I do not understand why getRequestDispatcher() can locate portlet.jsp when called during doView, but not when its called during init()
Am I missing a preceding call of some other method that would resolve this? Is this a known issue?
Thanks for any help.
Getting the request dispatcher in the doView is the only place I've seen it done. I would imagine that it returns null during init because there is no actual request to dispatch.
Typically the init method is used for time-expensive operations that you don't want to incur for each request. This might be something like reading data from a file, or creating a reusable SQL connection.
You should also keep in mind that you should keep any portlet state thread safe. Don't create class or object variables that can only be used for one request at a time. The portlet methods are not inhererently thread safe, so you need to make sure that whatever variables a request is interacting with won't be manipulated by another request that is executing concurrently.
I'm not familiar with Portlets, but the answer should be the same as for Servlets.
The init() method is called exactly once, when your application is initially deployed. There is no active request (no one is asking for anything) or response (no one is going to read what the output is). Therefore, it is very reasonable forgetRequestDispatcher() to return null. In doView(), when you're handling a request and response, it makes sense to ask another resource to generate part (or all) of the response.
To address your question directly, getRequestDispatcher() has no problem locating portlet.jsp from init(); it's the request that's missing. (Where do you expect to see the result of portlet.jsp, anyway?)
If you do want to print some output during initialization, you can try logging it to a file, if your application is set up for that. Or, you can display data on System.out, if you know where the container's console is. (I use this second option quite often with servlets.)
Sorry friends if this question is very easy but i am confuse i unable to find out solution.
As we all know in spring MVC framework we create controller which will handle multiple request from same page using #requestmapping annotation.
but same thing i want to do in servlet how can i do ?
Suppose i have a jsp which which will contain a jqgrid,and two forms i want to use only one servlet to load the data into jqgrid and that servlet only will handle request from both the form . Since we have only doGet and doPost in servlet how one servlet fulfill all three request. Hope you understand my question if you have and link where i get sample or and tutorial link plz reply me
Well, the only easy way to do this would be to use a request parameter to control how the processing happens.
In a very basic example, you may have something like a requestType value that gets passed as either part of the query string or the request body. You would assign values of 1-3 (or 0-2) with each value indicating a different type of request. Your servlet would then parse the request accordingly.
This actually is how the DispatcherServlet in SpringMVC works. There's only one servlet class instance and when a request comes in, it examines the query string along with other parts of the request to determine which controller should handle the request.
I'was debugging a client-side AJAX problem that is making request to servlet. But the bug turned out to be at server side. You can refer to my original question here. From the discussion with more experienced people, I found out that servlet is using request.getAttribute() method to retrieve parameters from the request instead of getParameter(). So I thought to open a new question to clear my doubt.
Now my question is: If I use GET method to pass parameters from client to server, getAttribute() in Servlet works fine and I can get param values. But when I use POST method, getAttribute() returns null. Why does it work for GET and not for POST?
You should always use getParameter, when attribute come from GET or POST method. And use getAttribute when request is forwarded from another servlet/jsp. Such as :
ServletA:
request.setAttribute("test","value")
request.getRequestDispatcher("/ServletB").forward(request, response)
ServletB:
request.getAttribute("test") <-- you can get test attribute by using getAttribute
Now my question is: If I use GET method to pass parameters from client to server, getAttribute() in Servlet works fine and I can get param values. But when I use POST method, getAttribute() returns null. Why does it work for GET and not for POST?
Complete nonsense. You're apparently working on an existing project which has a lot of other existing servlets and filters. My cents that there's another filter in the request-response chain which maps request parameters to request attribtues for some unobvious reason.
Please create a blank playground project and create a playground servlet to familarize yourself better with servlets without all that noise in existing projects.
See also:
Our Servlets wiki page
I have a servlet that does a request dispatcher include of another servlet.
The included servlet sets headers that I would like to read in the including servlet. So I pass in a custom HTTPResponse object in the include() method which captures all feedback activity from the servlet.
The problem is that the headers are not being set in my custom response. I've run in debug and examined what looks like Tomcat wrapping my custom response object with its own response object. The setHeader calls go to this wrapping class and never propagate to my custom response object.
I imagine Tomcat does this to protect the client from headers being set in the wrong place. The funny thing is that the same approach works the way I'd expect in Jetty.
It's been a while since I've done Servlets seriously so I'm struggling a bit here. I'm trying to figure out how to read the response headers from a servlet that's invoked via dispatcher.include().
From the Servlet specifications section SRV.8.3:
The include method of the RequestDispatcher interface may be called at any time.
The target servlet of the include method has access to all aspects of the request
object, but its use of the response object is more limited.
It can only write information to the ServletOutputStream or Writer of the
response object and commit a response by writing content past the end of the
response buffer, or by explicitly calling the flushBuffer method of the
ServletResponse interface.
It cannot set headers or call any method that affects
the headers of the response. Any attempt to do so must be ignored.
How about setting your values for the calling servlet in request scope, with request.setAttribute(...) and then reading it from there once you return? Could that work?