unable to change URL by using getRequestDispatcher - java

The code i use for this is
request.getRequestDispatcher("jsp/caseconference.jsp").forward(request, response);
The code above works fine when i use send Redirect but in that part, I can't use request and response which gives an error.

Based on your comment above, I don't think you're getting an error, but rather, you want the last part of your url to go from LoginServlet to caseconference. You would have to create a url pattern for caseconference like this:
#WebServlet(
name = "LoginServlet",
description = "This is optional but helpful",
urlPatterns = "/caseconference"
)
public class LoginServlet extends HttpServlet {
....
}
Then create a variable in your doPost method to keep track of every path the user is on, for example:
String path = request.getServletPath();
Whenever the time comes for the user to redirect to roswellpark/caseconference set the path to caseconference:
path = "/caseconference";
Then, build your url like this, provided you have a folder in your directory named roswellpark or you make a url pattern for it:
String url = "roswellpark/" + path + ".jsp";
And lastly, forward the url using try/catch statements for best practice:
try{
request.getRequestDispatcher(url).forward(request,response);
}catch(Exception ex){
....
}

Related

Need to get value after Domain name in url using java

We are getting url from JSON Response and which we open in in Chrome.The page loads , there is submit button which we click then it redirect to url as :-
https://www.google.com/AB1234
We need the need to retrieve only "AB1234" value from url.
tried following code to get value ="AB1234"
String url = driver.getCurrentUrl();
int index=url.lastIndexOf("/");
String result = url.substring(0,index);
but here getting initial part of url:https://www.google.com/
You need to call substring function with index +1 .
Try below code :
String url = driver.getCurrentUrl();
int index = url.lastIndexOf("/");
String result = url.substring(index + 1);
To parse a URI, it's likely a good idea to use a URI parser.
Given http://example.com/bar
String path = URI.create(driver.getCurrentUrl()).getPath();
will get you '/bar'.
Given http://example.com/bar/mumble the same code gets '/bar/mumble'. It's unclear from your question whether this is what you want. Nevertheless, you should at least start the parse as above.

Spring request mapping with regex like in javax.ws.rs

I'm trying rewrite this Google App Engine maven server repository to Spring.
I have problem with URL mapping.
Maven repo server standard looks like this:
URL with slash at the end, points to a folder, example:
http://127.0.0.1/testDir/
http://127.0.0.1/testDir/testDir2/
all others (without slash at the end) point to files, example:
http://127.0.0.1/testFile.jar
http://127.0.0.1/testFile.jar.sha1
http://127.0.0.1/testDir/testFile2.pom
http://127.0.0.1/testDir/testFile2.pom.md5
Original app mapping for directories and for files.
There were used annotations #javax.ws.rs.Path which supports regexy differently than Spring.
I tried bunch of combinations, for example something like this:
#ResponseBody
#GetMapping("/{file: .*}")
public String test1(#PathVariable String file) {
return "test1 " + file;
}
#ResponseBody
#GetMapping("{dir: .*[/]{1}$}")
public String test2(#PathVariable String dir) {
return "test2 " + dir;
}
But I can't figure out how to do this in right way in Spring application.
I'd like to avoid writing a custom servlet dispatcher.
I had a similar problem once, also regarding a Spring implementation of a maven endpoint.
For the file endpoints, you could do something like this
/**
* An example Maven endpoint for Jar files
*/
#GetMapping("/**/{artifactId}/{version}/{artifactId}-{version}.jar")
public ResponseEntity<String> getJar(#PathVariable("artifactId") String artifactId, #PathVariable("version") String version) {
...
}
This gives you the artifactId and the version, but for the groupId you would need to do some string parsing. You can get the current requestUri with the help of the ServletUriComponentsBuilder
String requestUri = ServletUriComponentsBuilder.fromCurrentRequestUri().build().toUri().toString();
// requestUri = /api/v1/com/my/groupId/an/artifact/v1/an-artifact-v1.jar
For the folder endpoints, I'm not sure if this will work, but you can give it a try
#GetMapping("/**/{artifactId}/{version}")
public ResponseEntity<String> getJar(#PathVariable("artifactId") String artifactId, #PathVariable("version") String version) {
// groupId extracted as before from the requestUri
...
}
Don't know about your java code, but if you are verifying one path at a time, you can just check if the string ends in "/" for a folder and the ones that don't are files
\/{1}$
this regular expression just checks that the string ends with "/" if there is a match, you have a folder, if there is not, you have a file
Well there is no other specific standard in Spring then the way you have used it. However if you can customize URL then I have a special way to differentiate directory and files. That will increase the scalibility and readability of application and will reduce lot of code for you.
Your Code as of now
#ResponseBody
#GetMapping("/{file: .*}")
public String test1(#PathVariable String file) {
return "test1 " + file;
}
#ResponseBody
#GetMapping("{dir: .*[/]{1}$}")
public String test2(#PathVariable String dir) {
return "test2 " + dir;
}
Change above code to as below in your controller class
private final Map<String, String> managedEntities=ImmutableMap.of(
"file","Type_Of_Operation_You_want_For_File",
"directory","Type_Of_Operation_You_want_For_Directory"
);
#GetMapping(path = "/{type:file|directory}")
public String myFileOperationControl(#PathVariable String type){
return "Test"+managedEntities.get(type));
}
And proceed further the way you want to per your business logic. Let me know if you have any questions.
Note: Please simply enhance endpoint per your need.
Spring doesn't allow matching to span multiple path segments. Path segments are delimited values of path on path separator (/). So no regex combination will get you there. Spring 5 although allows the span multiple path segments only at the end of path using ** or {*foobar} to capture in foobar uri template variable for reactive stack but I don't think that will be useful for you.
Your options are limited. I think the best option if possible is to use different delimiter than / and you can use regex.
Other option ( which is messy ) to have catch all (**) endpoint and read the path from the request and determine if it is file or directory path and perform actions.
Try this solution:
#GetMapping("**/{file:.+?\\..+}")
public String processFile(#PathVariable String file, HttpServletRequest request) {
return "test1 " + file;
}
#GetMapping("**/{dirName:\\w+}")
public String processDirectory(#PathVariable String dirName, HttpServletRequest request) {
String dirPath = request.getRequestURI();
return "test2 " + dirPath;
}
Results for URIs from the question:
test2 /testDir/
test2 /testDir/testDir2/
test1 testFile.jar
test1 testFile.jar.sha1
test1 testFile2.pom
test1 testFile2.pom.md5

Reading whole url from servlet

I would like to read from a servlet the exact URL that was set in the HTTP request. That is together with any URL rewritten parts (;jsessionid=…).
Is it possible?
You can get the request URL (the part before ; and ?) as follows:
StringBuffer requestURL = request.getRequestURL();
You can check as follows if the session ID was attached as URL path fragment:
if (request.isRequestedSessionIdFromURL()) {
requestURL.append(";jsessionid=").append(request.getSession().getId());
}
You can get and append the query string as follows, if any:
if (request.getQueryString() != null) {
requestURL.append('?').append(request.getQueryString());
}
Finally, get the full URL as follows:
String fullURL = requestURL.toString();

Get url parameters after # in java

I am trying to get the access_token from facebook. First I redirect to facebook using an url as the following
https://graph.facebook.com/oauth/authorize?type=user_agent&client_id=7316713919&redirect_uri=http://whomakescoffee.com:8080/app/welcome.jsf&scope=publish_stream
Then I have a listener that gets the url.
FacesContext fc = FacesContext.getCurrentInstance();
HttpServletRequest request =
(HttpServletRequest) fc.getExternalContext().getRequest();
String url = request.getRequestURL().toString();
if (url.contains("access_token")) {
int indexOfEqualsSign = url.indexOf("=");
int indexOfAndSign = url.indexOf("&");
accessToken = url.substring(indexOfEqualsSign + 1, indexOfAndSign);
handleFacebookLogin(accessToken, fc);
}
But it never gets inside the if..
How do I retrieve the parameter when it comes after a # instead of a usual parameter after ?.
The url looks something like
http://benbiddington.wordpress.com/#access_token=
116122545078207|
2.1vGZASUSFMHeMVgQ_9P60Q__.3600.1272535200-500880518|
QXlU1XfJR1mMagHLPtaMjJzFZp4
The URL is incorrectly encoded. It's XML-escaped instead of URL-encoded. The # is a reserved character in URL's which represents the client-side fragment which is never sent back to the server side.
The URL should more look like this:
https://graph.facebook.com/oauth/authorize?type=user_agent&client_id=7316713919&redirect_uri=http%3a%2f%2fwhomakescoffee.com%3a8080%2fapp%2fwelcome.jsf%26scope%3dpublish_stream
You can use java.net.URLEncoder for this.

How can you get the original REQUEST_URI from within a Struts 2 Action reached via an apache ErrorDocument redirection?

How can you access the REQUEST_URI from within a Struts 2 Action? In perl/php/ruby it is readily available via ENV["REQUEST_URI"] and the like. In java it seems that the PageContext.getErrorData().getRequestURI() is what I'm looking for, but sadly, the PageContext does not appear to be defined within the action, either because the ErrorDocument redirection makes the request not look like an error, or because it is defined later.
A particular example
Given an apache fronted (mod_jk/ajp) struts 2 app on tomcat reached via the ErrorDocument 404 configuration in apache. With the following details:
-- Original request url (which triggers the 404) --
http://server/totally/bogus/path
-- http.conf --
ErrorDocument 404 /struts2app/lookup.action
-- struts action --
public String bogusUrlLookup() {
HttpServletRequest request = ServletActionContext.getRequest();
// contains /lookup.action as does request.getRequestURI();
String url = RequestUtils.getServletPath(request);
// PageContext is null, so I cannot reach ErrorData from it.
log.info("pageContext="+ServletActionContext.getPageContext());
// Not in the ENV
// Map env = System.getenv();
// Not in the ATTRIBUTES
// request.getAttributeNames()
// Not in HEADER
// request.getHeaderNames()
return ERROR;
}
Again all I need is the string "/totally/bogus/path", but in the above action the only url string that I can find is "/struts2app/lookup.action". I'm tied to the ErrorDocument because the totally/bogus/path is not likely to be within the namespace of my application because apache serves other non-tomcat resources.
request.getAttribute("javax.servlet.forward.request_uri")
baseUri = (String)request.getAttribute("struts.request_uri");
Use:
JkEnvVar REDIRECT_URL ""
in your httpd.conf file. Then use request.getAttribute("REDIRECT_URL"); to get the variable in your jsp/servlets.
If you don't wanna miss the query string part, this is better:
final String referrer = (String) request.getAttribute(RequestDispatcher.FORWARD_REQUEST_URI);
if(referrer != null) {
final String query = (String) request.getAttribute(RequestDispatcher.FORWARD_QUERY_STRING);
if(query != null && query.length() > 0) {
url = referrer+ "?" + query;
}
else {
url = referrer;
}
// do something
}

Categories