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.
Related
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!
How is it possible to call doGet() method from RequestDispatcher?
RequestDispatcher rd = sc.getRequestDispatcher("/CartServlet");
rd.forward(request, response);
This code calls doPost() as the default action.
It calls doPost() because your original request used POST method.
Generally servlets cannot "call" each other. They just can forward or redirect request. In both cases the same HTTP method that was used in original request is used.
If you want to call doGet() of other servlet it is the time to refactor your application, i.e. separate the logic implemented in doGet(), put it to other class and call this class from both servlets.
Check out below link, using HttpURLConnection to send request internally by POST or GET methods. I had felt the need for this for a long long time.
Java - sending HTTP parameters via POST method easily
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.
I want to over ride the default getParameter() method of ServletRequestWrapper with getParameter() method of SecurityRequestWrapper.
For example, if I am using a simple jsp form to take the name of a person,
String name = request.getParameter("firstName");
I want the above getParameter() method to be from the SecurityRequestWrapper class. I am not able to understand how the request object is over riden since the getParameter method is mostly called on it by default in any jsp form.
I understand that the SecurityRequestWrapper you're talking about already implements HttpServletRequestWrapper? If so, then just create a Filter which is mapped on an url-pattern of *.jsp (or whatever you'd like to invoke this Filter for) and does basically the following in the doFilter() method.
chain.doFilter(new SecurityRequestWrapper((HttpServletRequest) request, response));
I might be wrong, but I do not think this is possible. Because request and response objects are created by the container and passed onto the servlet's process method. The very reason these objects are created by the container, because they want to flush the output and would like to control that. I will be interested to know however if it is possible to pass our own request / response objects.
If I can do this, how do I call Java code (methods for instance) from within JavaScript code, in Wicket.
erk. The correct answer would be ajax call backs. You can either manually code the js to hook into the wicket js, or you can setup the callbacks from wicket components in java.
For example, from AjaxLazyLoadPanel:
component.add( new AbstractDefaultAjaxBehavior() {
#Override
protected void respond(AjaxRequestTarget target) {
// your code here
}
#Override
public void renderHead(IHeaderResponse response) {
super.renderHead( response );
response.renderOnDomReadyJavascript( getCallbackScript().toString() );
}
}
This example shows how to add call back code to any Component in Wicket. After the OnDomReady event fires in your browser, when loading a page, Wicket will cause it's js enging, to call back into your code, using Ajax, to the 'respond' method shown above, at which point you can execute Java code on the server, and potentially add components to the ajax target to be re-rendered.
To do it manually, from js, you can hook into wicket's system by printing out getCallbackScript().toString() to a attribute on a wicket component, which you'll then be able to access from js. Calling this url from js manually with wicket's wicketAjaxGet from wicket-ajax.js.
Check out the mailing list for lot's of conversation on this topic:
http://www.nabble.com/Wicket-and-javascript-ts24336438.html#a24336438
Excerpt from https://cwiki.apache.org/WICKET/calling-wicket-from-javascript.html
If you add any class that extends AbstractDefaultAjaxBehavior to your page, wicket-ajax.js will be added to the header ofyour web page. wicket-ajax.js provides you with two basic methods to call your component:
function wicketAjaxGet(url, successHandler, failureHandler, precondition, channel)
and
function wicketAjaxPost(url, body, successHandler, failureHandler, precondition, channel)
Here is an example:
JavaScript
function callWicket() {
var wcall = wicketAjaxGet('$url$' + '$args$', function() { }, function() { });
}
$url$ is obtained from the method abstractDefaultAjaxBehavior.getCallbackUrl(). If you paste the String returned from that method into your browser, you'll invoke the respond method, the same applies for the javascript method.
You can optionally add arguments by appending these to the URL string. They take the form &foo=bar.
you get the optional arguments in the Java response method like this:
Map map = ((WebRequestCycle) RequestCycle.get()).getRequest().getParameterMap();
or this:
String paramFoo = RequestCycle.get().getRequest().getParameter("foo");
http://www.wicket-library.com/wicket-examples-6.0.x/index.html/ has plenty of examples to get you going.
Or have a Have a look at DWR
http://directwebremoting.org/
DWR allows Javascript in a browser to interact with Java on a server and helps you manipulate web pages with the results.
As Dorward mentioned this is done via AJAX
Assuming you mean JavaScript running on the client - you cause an HTTP redirect to be made to the server, and have your servlet react to the request for the given URL.
This is known as Ajax, and there are a number of libraries that help you do it..