appending special character with URL - java

I need help on the issue where we are appending special character like % with URL.
Suppose my application URL is "http://www.google.com/".
we have our custom error page which will come when server will not find URL address.
scenario 1: hitting "http://www.google.com/sdfkdjkfj :---redirecting on custom error page which is correct.
Scenario 2: hitting "http://www.google.com/% :--Instead of redirecting on my own custom page it is showing message "this page is not working HTTP ERROR 400".
we are using below code in web.xml to handle the page not found exception.
<error-page>
<error-code>404</error-code>
<location>/ErrorPage.jsp</location>
.
Please help on scenario 2 .

If you want to include a % character in a URL, it needs to be percent-encoded; e.g. http://www.google.com/%25. (That URL still may not be recognized, but at it is syntactically well-formed.)

Error code 400 means "Bad request", the server cannot understand this request. Generally you should avoid passing special character "%" in your URL like in your example.
However if you want to pass this character and preserve its meaning, try to encode it: https://www.w3schools.com/tags/ref_urlencode.asp. When you try http://www.google.com/%25 - you will have 404 error.

Related

fix for spot bug - HRS_REQUEST_PARAMETER_TO_HTTP_HEADER

I am executing below code inside servlet and getting this spot bugs - HRS_REQUEST_PARAMETER_TO_HTTP_HEADER
Bug: HTTP parameter directly written to HTTP header output in SSOIdpLogoutRedirect.doPost(HttpServletRequest, HttpServletResponse)
String relayState = request.getParameter("RELAY_STATE");
if(relayState != null)
{
response.sendRedirect(relayState);
}
To fix this bugs i added below code.
relayState = URLEncoder.encode(relayState,StandardCharsets.UTF_8);
But URL does not redirect in correct way as i can see the relaystate url has been changed after encoding
original relaystate = https://sad.ezhdj.net/system/web/apps/dfgh/
and after encoded it is
relaystate =https%3A%2F%2Fsad.ezdev.net%2Fsystem%2Fweb%2Fapps%2Fdfgh%2F`
you should use HttpServletResponse.encodeRedirectURL() to encode redirect urls:
String encodeRedirectURL(String url)
Encodes the specified URL for use in the sendRedirect method or, if
encoding is not needed, returns the URL unchanged. The implementation
of this method includes the logic to determine whether the session ID
needs to be encoded in the URL.
...
All URLs sent to the HttpServletResponse.sendRedirect method should be
run through this method...
this should work:
response.sendRedirect(response.encodeRedirectURL(relayState));
since your url doesn't actually need encoding, output from encodeRedirectURL() will be:
https://sad.ezhdj.net/system/web/apps/dfgh/
and the redirect will work just fine.
edit:
apparently proposed solution still triggers HRS_REQUEST_PARAMETER_TO_HTTP_HEADER spotbug error.
after doing little more research I found out that the error is meant to prevent HTTP response splitting vulnerability (i.e. when unwanted \r\n are written in the header section of http response).
we should then better sanitize relayState against this type of vulnerability.
a simple relayState.replace("\r\n", "") is enough to make the error go away:
response.sendRedirect(response.encodeRedirectURL(relayState.replace("\r\n", "")));

How to disable curly braces evaluation in URL passed to HttpServletResponse.sendRedirect

I have a URL shortner that should sendRedirect(URL) to URLs specified by users.
Sometimes URL contain curly braces like this: http://example.com?someparam={something}.
Instead of sending response 302 to client browser, my Spring MVC app at Tomcat server gives error 404 with no text.
Apparently it's some sort of URL variable evaluation taking place, can I disable it? I could not find docs regarding this feature.
I know this is an old question but I think the OP was looking for a way to prevent Spring from doing variable replacement in redirect URL
I faced the exact same issue and the fix was using RedirectView
and in RedirectView you can set setExpandUriTemplateVariables(false)
that made it redirect to the url given exactly without Spring trying to replace anything in it
here is how the code looks like
RedirectView redirect = new RedirectView(redirectUrl);
redirect.setExpandUriTemplateVariables(false);
return new ModelAndView(redirect);
Hope that helps
This is not valid Google search URL http://google.com/{something}. It should have been https://www.google.ca/search?q=http{302}
Emphasis is on search?q. After domain name you have specify your service name and then query string if you want to pass some inputs.
When you do http://google.com/{something} then you really do not have any resource or service as {something} so 404 is the expected output.
HTTP 302 is for redirection, I am not sure why you were expecting redirection.
URL encoding will also not help because issue is related to resource/service, if it is not present then you will get 404. URL encoding is not meant to solve problem related to 404.

JSP error page appended to previous output

I have a Spring MVC project where I am using controller advice to handle errors thrown in controllers. However, I also want to display a nice error page if an error occurs within JSP files (even though this really shouldn't happen!). Therefore I have added the following to my project's web.xml file:
<error-page>
<error-code>500</error-code>
<location>/WEB-INF/views/application/error/view-error.jsp</location>
</error-page>
<error-page>
<exception-type>java.lang.Exception</exception-type>
<location>/WEB-INF/views/application/error/view-error.jsp</location>
</error-page>
If I trigger an error in JSTL on purpose, the contents of view-error.jsp is rendered fine. However, the content is appended to the output of the JSP file in which the error occurred. For instance, if an error occurs within display-users.jsp at line 50, the result is that the output that was generated before the error occurred (line 1-50) is prepended the contents in view-error.jsp.
This is very undesirable as it generates a funky looking error page. And since I cannot tell where an exception will be thrown (if I could, I would fix the error), then what the user sees is very likely to look bad.
I guess it's because the output is already in the buffer, and may already have been sent to the client? Is there any way I can fix this, or perhaps an alternative approach? Thanks!
This is a problem with large JSP generating big HTML, with scriptlet java code intermixed everywhere. As soon as enough data have been writen, the server commits the headers (sends them to client) and send the beginning of the page. At that moment, you can no longer rollback anything to get back the data that has already been received (and possibly displayed) by the browser.
That's one of the reasons why scriplet are not recommended, and if you really need to put some intelligence it the JSP, it should be at the beginning of the page before anything is actually sent to browser. But ideally, everything should have been computed in advance in a servlet and prepared data put in request attributes. That way the JSP should only contain simple conditionnal or loop tags in addition to HTML output and request attributes rendition. All that with little risk to generate an exception.
Looks like the OutputStream of the HttpServletResponse is being written to before the enitre JSP finishes rendering.
This ideally should be controllable by "autoflush" property. https://tomcat.apache.org/tomcat-5.5-doc/jspapi/javax/servlet/jsp/JspWriter.html
But just in case it isn't solvable by that:
You could intercept anything that written to HttpServletResponse by using the HttpServletResponseWrapper approach.
The general idea there is that you create a Filter and that Filter will pass a "Response Wrapper" to the layers below. This Response Wrapper holds a reference to real Response instance. Anything that gets written to the Response, can be then manipulated by the Response Wrapper and then sent to the real Response instance.
So, for your case, you could append all the data in a StringBuilder, and when then controls returns back to the Filter, the Filter can print the entire StringBuilder to the real Response's OutputStream.
Here is an example that intercepts anything the Servlets, etc. write and then sends the GZipped version of that to the Browser:
http://tutorials.jenkov.com/java-servlets/gzip-servlet-filter.html
Been there, done that. Here's a quick and dirty workaround until you can redesign.
1) Place the all the JSTL code that generates output in a new JSP -- let's call it display-users-view.jsp (call it whatever you want).
2) Import display-users-view.jsp from your display-users.jsp page via a <c:import>, but make sure you dump the contents to a var(!). e.g.:
<c:import url="display-users-view.jsp" var="output"/>
3) As a final step in display-users.jsp, dump the output to the screen with a simple:
${output}
Now, if the error is thrown before the ${output} .. no harm, no foul because you haven't output anything to the browser yet. If there is no error, the ${output} will dump the HTML that was generated in the display-users-view.jsp.
Note, by using c:import you don't have to pass any querystring or form params that were submitted to display-users.jsp because you will still have them available in your display-users-view.jsp.

how to get URL from address bar in JSP

Lets say I hit
http://localhost/webapp/wcs/stores/servlet/en/marksandspencer/l/women/dresses/party-and-cocktail-dresses
and this internally redirects me to custom 404.jsp page, But URL remain same in address bar.
I tried this code - <%= request.getAttribute("javax.servlet.forward.request_uri") %>; and it's returning me the path of 404.jsp
How can I get the entered URL which is there in address bar?
Use request.getAttribute("javax.servlet.error.request_uri") to get URI of requested page that not found (404 error). Check this: https://tomcat.apache.org/tomcat-7.0-doc/servletapi/constant-values.html
When error raised (because of some reason such as page not found (404), Internal Server Error (500), ...), the servlet engine will FORWARD the request to corresponding error page (configured in web.xml) using ERROR dispatcher type, NOT FORWARD dispatcher type so that is the reason we must use javax.servlet.error.request_uri, NOT use javax.servlet.forward.request_uri
I think you were close. javax.servlet.forward.request_uri is for normal forwarding, but for 404, you need javax.servlet.error.request_uri.
You can use :
String url = request.getRequestURL().toString();
but this doesn't hold Query String. So, to get query string, you may call
request.getQueryString()
You can do this to get the whole URL including parameters.
request.getRequestURL()+""+request.getQueryString();
use request.getHeader("Referer").
referer gives a url from where you redirected.

URL submit with "get" mode, response"400" error

when I raise request with follow url:
myip/searchapp/genericSearch/genericSearchInit.html?securityName=&identifierType=3&identifierCode=test&vendor=4&startDate=10%252F1%252F2013&priceType=&currency=&endDate=&exchange=
I got 400 error:
Failed to load resource: the server responded with a status of 400 (Bad Request)
But when I give some values such as
myip/searchapp/genericSearch/genericSearchInit.html?securityName=&identifierType=3&identifierCode=test&vendor=4&startDate=10%252F1%252F2013&priceType=1&currency=1&endDate=1&exchange=1
and it become legal url.
can any guy tell me why? and how can I deal with it?
Try leaving out those last parts completely if you don't need them:
myip/searchapp/genericSearch/genericSearchInit.html?securityName=&identifierType=3&identifierCode=test&vendor=4&startDate=10%252F1%252F2013
it must be that whatever page you are calling is using those variables to redirect to different pages. It seems that the page breaks when an empty string is sent in.
That page is probably using key_exists() checks, which would return false if the query didn't have it at all but true if you sent an empty string, and not an additional empty() checks, which would return false either way.
If that page is yours, then you could probably adjust it so that the it is valid to send empty data. If it isn't yours then it is just the way that specific page is working, there really isn't anything else to understand.
It is a bug, report it to whoever is in charge of the page.
The only difference that I can tell in those two urls is
priceType=&currency=&endDate=&exchange=
versus
priceType=1&currency=1&endDate=1&exchange=1
It seems the server doesn't like missing data and therefore sends 400 Bad Request. You need to figure out what your service expects and send that.

Categories