http get from jsp and resolve status code - java

I need to send http request to certain URL via jsp (by clicking on a link / button). Depending on the http response status code I need to generate corresponding output in the jsp (200 - action OK, 404 - unknown action etc, the content of the URL is irrelevant). Is there any way to achieve this behaviour?
I am using Spring.

First send your request to a servlet using AJAX and call the url that you want from the servlet.From that url response you can use int status = response.getStatus(); on the HttpServletResponse object in your servlet and based on the int value that you get you can write your if else statements and use PrintWriter's println method to send response/text to the ajax call on your jsp and use it wherever you want in that jsp page.

you can use jquery and make an ajax call using its ajax method and use it success/error callback methods to get textStatus

Related

Unable to redirect to another page in AEM using request dispatcher in sling servlet via POST

I have a scenario where from one page in AEM, I need to call another AEM page in the same application and I need to pass some hidden parameters. I choose to do it via POST and below are the steps which I followed:
From page "A", I did a form submission via POST to the sling servlet and passed some parameters.
2. In the servlet, using request dispatcher I redirected the same request and response to a different page in doPost method using the following code snippet:
request.getRequestDispatcher("/content/company/en/apps/welcomepage.html").forward(request, response);
When I run the code, I am able to call the servlet through form submission but I am not able to redirect to a new page. I see the below error in logs:
18.10.2017 14:41:00.802 ERROR [127.0.0.1 [1508352060795] POST /bin/rap/welcomepage HTTP/1.1] org.apache.sling.servlets.post.impl.operations.ModifyOperation Exception during response processing.
javax.jcr.nodetype.ConstraintViolationException: No matching property definition: appointmentTypeId = platform001d
at org.apache.jackrabbit.oak.jcr.delegate.NodeDelegate.setProperty(NodeDelegate.java:522)
at org.apache.jackrabbit.oak.jcr.session.NodeImpl$35.perform(NodeImpl.java:1375)
at org.apache.jackrabbit.oak.jcr.session.NodeImpl$35.perform(NodeImpl.java:1363)
at org.apache.jackrabbit.oak.jcr.delegate.SessionDelegate.perform(SessionDelegate.java:208)
at org.apache.jackrabbit.oak.jcr.session.ItemImpl.perform(ItemImpl.java:112)
at org.apache.jackrabbit.oak.jcr.session.NodeImpl.internalSetProperty(NodeImpl.java:1363)
If I try the same code in doGet method it works fine. Also if I use response.sendRedirect("/content/company/en/apps/welcomepage.html") it works fine too. But the problem with this is it initiates it as a new request to the page and it looses all the parameters which I get from the form submission. Could someone please let me know like how can I redirect a request to a page in AEM via POST since I need to pass some hidden parameters whic should not be visible in the url ?
Here is the way I understand your question
User visits page "A"
User fills a form, then submits.
Your custom servlet handles the submitted POST request and calls:
request.getRequestDispatcher("/content/company/en/apps/welcomepage.html").forward(request, response);
You get the ConstraintViolationException
Why do you get this exception?
Since you are using forward the POST request is forwarded to /content/company/en/apps/welcomepage.html that node is most likely of type cq:Page, which has constraints on which properties can be added. Think of it as a simple post request trying to store parameters on the cq:Page node.
What can you do?
Since I don't understand your use-case and particularly why you need to preserve the submit params, I cannot recommend a specific solution. However, since you don't want the parameters in the URL, here is a potential solution you can try:
In your servlet handler, see those hidden params to cookies on the response.
use response.sendRedirect("/content/company/en/apps/welcomepage.html")
On any of the components in /content/company/en/apps/welcomepage.html, you can get the request cookies and process them however you like. same way you wanted to process those hidden params.
Now the flow becomes:
User visits page "A"
User fills a form, then submits.
Your custom servlet handles the submitted POST request, adds your special params to cookies on the response, then calls response.sendRedirect("/content/company/en/apps/welcomepage.html")
User's browser receives a 301 response with the cookies, sets the cookies in the browser then requests "/content/company/en/apps/welcomepage.html"
Your components handle the request and get the params from the cookies, then retuns the appropriate response.

Hiding Parameters in url while sending url through response.sendRedirect method

I am sending url to another server through response.sendRedirect() method and it is generating pdf for me. I am passing all the parameters but one of the parameter data is exceeding length due to which browser is not able to handle it and request is getting blocked.
I know through Post method we can hide url Parameters and response.sendRedirect() uses GET method. Is there any POST method like sendRedirect through which we can access another server url directly through servlet? Thanks in advance.
With response.sendRedirect(newUrl) you send back a HTTP status 302 with a new Location=newUrl in response header. Thus, you cannot force browser to make POST instead of GET method.
What you could do is to consume a pdf file from within your server code and return it to the client, hiding thus from client the actual target location. You can then build any request with method and parameters you want to the new location if it accept it.
See, for example, this tutorial how to make a request to another server from your servlet http://www.mkyong.com/java/how-to-send-http-request-getpost-in-java/

what is in background of html submit form?

I'm trying to figure out what really happens when html submit form button is clicked.
I suppose it generates some kind of http request (similar to ajax get or post call) which has data in http body and is sent to address specified in action field.
1) Am I right?
2) I've seen many ways of processing forms with PHP or ASP on server side. Can I process it with Java REST Application using e.g. Jersey? Is submit form capable of hitting REST if I put right URL in action field?
Thank You.
By submitting the form in HTML you basically tell the browser to generate a normal HTTP request, usually POST or GET, for an URL defined in tag with form fields attached according to the specified method either appended to the URL or included in the request data.
There is nothing really special or different from a "normal" HTTP request, in fact you can manually "submit a form" by appending form keys and values to the URL in your browser and navigating to it in case of GET method.
Summarizing:
1) Yes, you are right.
2) From what I've just read (never used REST personally) a REST application is implemented by a servlet mechanism and uses HTTP protocol, so it should be possible to write a REST application for processing HTML forms if the form points to this application's URL.

Multiple Request Response Forward

I am currently passing some ArrayList's from my servlet to my JSP page using the below code.
RequestDispatcher rd = null;
request.setAttribute("date",al);
request.setAttribute("bau",al1);
request.setAttribute("project",al2);
rd = request.getRequestDispatcher("ResourceChart.jsp");
rd.forward(request,response);
The problem is when I click refresh on the page, the same date is passed again and I end up with odd results. Should I be forwarding to the JSP page as well to avoid the servlet regenerating the variables and passing them?
Whats the best way to implement this?
You're apparently refreshing a POST request and ignoring/confirming the browser's builtin warning that the data would be resent. In that case, the doPost() method will indeed be re-executed with the previously submitted data which would only end up in duplicate entries in the DB.
The canonical approach to avoid the double submit on a refresh of a POST request is to send a redirect after POST request. A redirect implicitly creates a new GET request. Refreshing would then result in only the GET request being re-executed which is totally harmless.
To achieve that, replace all in the question shown lines of the doPost() by the following single line
response.sendRedirect(request.getContextPath() + "/ResourceChart");
(assuming that your servlet is mapped on an URL pattern of /ResourceChart)
and create a new doGet() method wherein you put all those removed lines back, along with the necessary logic to prepare the lists. The only change which you need to make is to put the JSP file in /WEB-INF folder to avoid endusers from being able to open it directly by entering/guessing its URL without calling the servlet's doGet() first.
request.getRequestDispatcher("/WEB-INF/ResourceChart.jsp").forward(request, response);
See also:
Our Servlets wiki page

Java Servlet Behaviour Question

I am currently implementing an OpenID Relying Party (RP) and Identity Provider (IdP) with Java HttpServlets using the OpenID4Java library. I have run into trouble getting two servlets to communicate with each other. I believe the problem I am having is to do more with how Servlets behave, however I have included info about my application for a better sense as to what is happening.
The scenario is as follows:
Servlet #1 (my RP) sends a request to Servlet #2 (my IdP) as follows:
httpResp.sendRedirect(authReq.getDestinationUrl(true));
Essentially authReq = a message with various OpenID specific parameters. By invoking getDestinationUrl(true) it encodes the request into a url to send via a GET.
Servlet #2 catches the above GET in its doGet method. It parses the information, and crafts a reply to send back to Servlet #1 in the following fashion:
String responseText = processRequest(httpReq, httpResp);
httpResp.setContentType("text/html");
OutputStream outputStream = httpResp.getOutputStream();
//
outputStream.write(responseText.getBytes());
outputStream.close();
My problem is, this response never makes it back to Servlet #1. I would expect that when Server #1 receives the response from Servlet #2 that its' doGet or doPost method would catch the message. However neither case happens.
Any advice would be greatly appreciated.
Thanks!
The response of 2nd servlet will directly go on client side i think because its is the original client right? Your 1st servlet is just redirecting the request.
So, if you want to communicate between servlets, Use URLConnection or Apache HttpClient to communicate with 2nd servlet.
You can also make JSP instead of 2nd servlet, then pass you data from 1st servlet to that JSP. That JSP's response will be sent to client then. After all you can do all logic in JSP what you can in servlet.
Hope this helps.
parth.
If you want two servlets to communicate with each other within an application, you can use the ServletContext object and share data via ServletContext.setAttribute and ServletContext.getAttribute and RequestDispatcher obtained via HttServletRequest or ServletContext
In your case can the Servlet#2 be invoked directly by the client? If not then you should probably refactor the processRequest(request, response) into a Utility class or a library. Which in turn can be called by both Servlet#1 and Servlete#2.
response.sendRedirect sends a redirect (301 moved permenently, ithink) to the browser. So your servlet actually sends a response to browser with 301 and then browser makes a request to servlet#2 again.
You can use RequestDispatcher to include your second servlet's response. In this way, the control returns to the first servlet after the method completes.
RequestDispatcher dispatcher = request.getRequestDispatcher(authReq.getDestinationUrl(true));
dispatcher.include(request, response);
However, with this, the response generated by the called servlet will be sent to the browser. If you want your calling servlet to capture the message from called servlet without sending to browser, you can either create a response wrapper (A wrapper writing the contents in a string) and pass this wrapper when you include the second servlet or better you can share the data in either of the scopes (Preferably 'request' scope): You can set the data in the request scope in called servlet and you can retrieve it in the calling servlet after include() completes.
When you redirect, you are telling the browser to make a new request for the URL. So there will be new request/response objects created as if you had clicked on a link in your page.
Hope this helps.

Categories