This question already has answers here:
doGet and doPost in Servlets
(5 answers)
Closed 6 years ago.
I want to know that in servlets why we use doGet and doPost methods together in the same program. What is the use of it??
What does the following code means?
Why to call the doGet method from doPost? I am not at all clear about this code.
public class Info extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
doGet(request, response);
}
}
Thanks
doGet() handles incoming HTTP GET requests while doPost() handles... POST requests. There are also equivalent methods to handle PUT, DELTE, etc.
If you submit your form using GET (default), the doGet() will be called. If you submit using POST, doPost() will be invoked this time. If you only implement doPost() but the form will use GET, servlet container will throw an exception.
In many programs the server doesn't care whether the request uses GET or POST, that's why one method simply delegates to another. This is actually a bad practice since these methods are inherently different, but many tutorials write it this way (for better or worse).
Simply, it is to make the servlet generalized so that even if we change the request method in future, it is not required to edit the servlet, which will reduce the efforts to modify the application in future.
This is to handle both requests type eg. GET and POST of http. depending upon app's requirement people may chose to keep request type as GET or POST so incase you are handling both of them you will get error. and in case you want to handle both of them in similar fashion then you can create another method doSomething and call it from your doGet and doPost methods for more info see this answer
Isn't it to do with a get request allows the parameters to be seen in the URL in the browser window and the post request incorporation the parameters into the structure of the request and hence hidden from view. How will your request be made from the client as a get or a post. I think it is something to do with security and avoiding sql injections, but it is not my area really. Hopefully, some expert with correct my view/comment as I need to know this myself.
As you noted here you can indeed call a third method but you also can override the service() method from the HttpServlet motherclass so that it calls alawys one unique method.
Related
For legacy reasons I need to do a url redirection from an old website to the new one.
For example, this is the old URL:
https://my_old_site/a_section_of_the_website
So when a user types this URL because they think it is still the actual URL, I want to redirect the user to:
https://my_new_site/a_section_of_the_website
I mean, I don't want to redirect to another action, I want to intercept the URL and redirect it to another url. But after searching here, on Google and other sites, I can't figure out how to do it.
I would like to know if there is a way in Struts or Spring to manage the URLs of the application and handle redirects. I don't know if it can be done in the struts.xml or there is another file in Spring in which it performs this task.
Best regards.
Finally, the only thing I have found to achieve this was:
In the Action class of the old URL, as it received HttpServletResponse response as a parameter, I made the redirection there directly and forced a null return since the signature of the method expects an ActionForward.
protected ActionForward doExecute(..., HttpServletResponse response) throws Exception {
...
response.sendRedirect("https://my_new_site/a_section_of_the_website");
return null;
}
I hope this may be of help to someone in the future.
I have java application which has httpservlet class. This class has doPost(HttpServletRequest request, HttpServletResponse response) method as common servlet class. Nothing special.
This servlet waits for requests from other applications which I can't change and see.
This applications put token param as paramName to request. Token could contain different symbols and numbers.
And I have a problem: sometimes tokens comes in this format token=cc%7C342084%7C7957 but when I use it in my servlet it already cc|342084|7957
I suppose, it's because my servlet see %7c and thinks that it |. How could I prevent this? I need token to be the same as it comes.
Can anyone help?
How tomcat works online book from gitbook
Chapter 2 mentions a way to compromise security:
There is a serious problem in the first application. In the ServletProcessor1 class's process method, you upcast the instance of ex02.pyrmont.Request to javax.servlet.ServletRequest and pass it as the first argument to the servlet's service method. You also upcast the instance of ex02.pyrmont.Response to javax.servlet.ServletResponse and pass it as the second argument to the servlet's service method.
try {
servlet = (Servlet) myClass.newInstance();
servlet.service((ServletRequest) request,
(ServletResponse) response);
}
This compromises security. Servlet programmers who know the internal workings of this servlet container can downcast the ServletRequest and ServletResponse instances back to ex02.pyrmont.Request and ex02.pyrmont.Response respectively and call their public methods. Having a Request instance, they can call its parse method. Having a Response instance, they can call its sendStaticResource method.
can anyone give me an example, how this will compromises security. Let's say i have a Servlet Application on this HttpServer1, How can another programmer do any harm to my servlet application?
Got a Java Filter which is responsible to intercept some endpoints.
In doFilter method, as follows:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException;
How do I get the accessed method name?
For instance:
Given 2 Servlets followed by operation name:
LifeCycle
create
delete
SearchService
findByName
findById
When LifeCycle.create operation is called by a front end perspective, the filter intercepts it, however I couldn't know if the operation called was create or delete?
Are there some way to get the "create" operation name in Java Filter?
Thanks in advance.
Filters are invoked by the web container when a request is made to the server (servlet or jsp). They are not called by Servlets or jsps.
You can see Filter's life-cycle in the image below:
For more see DOCUMENTATION
If you want to know which action is called from the front-end, then you can use a request parameter and then capture it from ServletRequest
I could get the operation name using:
((HttpServletRequest) request).getHeader("SOAPAction");
If you are searching for method names then you can try this piece of code:
StackTraceElement[] st = Thread.currentThread().getStackTrace();
String methodName = st[2].getMethodName();
You can further modify the index of st to get the chained caller methods. It is just a simple array of stack trace objects containing class and method names. Good Luck!
Im currently making a Java Servlet that can respond to jquery calls and send back data for my web page to use. But this is only a response using the doGet method.
Is there a way to have multiple methods in a Servlet and call them each with JQuery?
i.e. have a method called Hello and it returns a String "Hello" and another method called Bye and it returns a String "Bye". Is there a way using Jquery or some other technology to do this kind of thing?
Im quite new to servlets so Im still not sure what they are fully capable of. So is the doGet the only method to 'get in' and I just branch responses from there?
With Servlet you can either call the service method, so may be for your scenario you could pass the parameter to decide which method to invoke from doGet()
also you could identify if request is coming from AJAX using header check
There are other technologies available which will allow you directly invoke method See JSF, DWR
See
How to invoke a method with Openfaces/JSF without rendering page?
How to call a java method from jsp by clicking a menu in html page?
Personally I use reflection in my controllers(servlets) which basically let me achieve this.
If I have a servlet called UserController
The main url to call the servlet will be /user.
Knowing this, I always pass my first parameter as ?action=add
Then in my servlet I have a method called add or actionAdd. Whichever you prefer.
Then I use the following code;
String str = String str = request.getParameter("action").toLowerCase();
Method method = getClass().getMethod(str, HttpServletRequest.class, HttpServletResponse.class);
method.invoke(this, request, response);
Explanation:
str will have the action parameters value, add in this case.
Method method will be a reference to a method with the given name(str) and its expected parameter types.
I then invoke the method, passing the context, request and response.
The add method would look something like this;
public void add(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
//do add stuff
String url = "/user/index.jsp";
RequestDispatcher dispatcher = context.getRequestDispatcher(url);
request.setAttribute("User", user);
dispatcher.forward(request, response);
}
I don't know about only passing back a string. But this should get you a basic idea.
Do note that reflection can cost you, altohugh it shouldnt really affect you much like this. And it is error prone as method names/signatures need to match perfectly.
So from jquery you would do an ajax request to the url:
localhost/projectname/user/add (if you use urlrewrite)
or
localhost/projectname/user?action=add (if you dont)
Servlet Container supports Custom Http methods since Servlet 3.0. For Ex,
public void doHello(HttpServletRequest req, HttpServletResponse res) {
//implement your custom method
}
The above method in Servlet can be invoked using hello http method.
But i am not sure if jquery has the support to invoke custom HTTP methods.
If it does not have, then the only option you have.
Invoke Servlet using GET and action parameter.
Read the action parameter and invoke the method using reflection.