I have the URL: http://demo.lendingclub.com/account/summary.action.
When visit this url, it will first go to the authenticate interceptor, in the interceptor class, If I use:
String uri = req.getRequestURI();
it will return /account/summary.action
But if I use it in jsp:
<%
HttpServletRequest req = ServletActionContext.getRequest();
String uri = req.getRequestURI();
%>
it will return : /mainapp/pages/account/summary.jsp
Why they're different, and how can I get action URL in JSP?
The easiest way to get the current actions url is: <s:url/> if you supply namespace and action parameters you can make it point at other actions but without these parameters it defaults to the current url.
You could get the action URL or any other value if you set property to the action, and then retrieve that property from the value stack via OGNL.
private String actionURL;
public String getActionURL(){
return actionURL;
}
the code to calculate the action URL is similar you posted to the comments
public String getPath(){
ActionProxy proxy = ActionContext.getContext().getActionInvocation().getProxy();
String namespace = proxy.getNamespace();
String name = proxy.getActionName();
return namespace+(name == null || name.equals("/") ?"":("/"+name));
}
this code is not supported .action extension, if you need to add the extension to the path then you need to modify this code correspondingly.
then write your action method
public String excute() {
actionURL = getPath();
...
return SUCCESS;
}
in the JSP
<s:property value="%{actionURL}"/>
you have been used dispatcher result to forward request to the JSP as a result you get the URI pointed to the JSP location.
Related
I have the controller method like below:
#RequestMapping(value = "/login/do", method = RequestMethod.POST)
public String loginProcess(#RequestParam("email") String email, #RequestParam("password") String password,
HttpSession session) {
session.setAttribute("email", email);
Optional<User> userDetail = userRepository.findById(email);
if (userDetail.isPresent()) {
String userType = userDetail.get().getUserType();
String passwordDb = userDetail.get().getPassword();
if (password.equals(passwordDb) && userType.equals("admin")) {
return "adminPage";
} else if (password.equals(passwordDb) && userType.equals("candidate")) {
return "candidatePage";
} else {
return "passwordError";
}
} else {
return "invalid";
}
I have URL localhost:8080/login/do as URL
for my login process method inside the method, some business logic is written upon execution of that it will take me to some page candidate.html,passworderror.html, etc however on moving to the any of the pages the URL is showing as localhost:8080/login/candidate.jsp here I don't want /login to be present in URL.
strong text
since here onwards moving on to any page if i move forward the localhost:8080**/
**login****
/candidate.jsp is present by default.
expected Url should not include login further.
remove from properties file if exists:
server.servlet.context-path=
and also specify where your jsp pages are created and also mention your properties file configuration and #Controller annotation code as well.
I am trying to access the contents of an API and I need to send a URL using RestTemplate.
String url1 = "http://api.example.com/Search?key=52ddafbe3ee659bad97fcce7c53592916a6bfd73&term=&limit=100&sort={\"price\":\"desc\"}";
OutputPage page = restTemplate.getForObject(url1, OutputPage .class);
But, I am getting the following error.
Exception in thread "main" java.lang.IllegalArgumentException: Not enough variable values available to expand '"price"'
at org.springframework.web.util.UriComponents$VarArgsTemplateVariables.getValue(UriComponents.java:284)
at org.springframework.web.util.UriComponents.expandUriComponent(UriComponents.java:220)
at org.springframework.web.util.HierarchicalUriComponents.expandInternal(HierarchicalUriComponents.java:317)
at org.springframework.web.util.HierarchicalUriComponents.expandInternal(HierarchicalUriComponents.java:46)
at org.springframework.web.util.UriComponents.expand(UriComponents.java:162)
at org.springframework.web.util.UriTemplate.expand(UriTemplate.java:119)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:501)
at org.springframework.web.client.RestTemplate.getForObject(RestTemplate.java:239)
at hello.Application.main(Application.java:26)
If I remove the sort criteria, it is working properly.
I need to parse the JSON using sort criteria.
Any help will be much appreciated.
Thanks
The root cause is that RestTemplate considers curly braces {...} in the given URL as a placeholder for URI variables and tries to replace them based on their name. For example
{pageSize}
would try to get a URI variable called pageSize. These URI variables are specified with some of the other overloaded getForObject methods. You haven't provided any, but your URL expects one, so the method throws an exception.
One solution is to make a String object containing the value
String sort = "{\"price\":\"desc\"}";
and provide a real URI variable in your URL
String url1 = "http://api.example.com/Search?key=52ddafbe3ee659bad97fcce7c53592916a6bfd73&term=&limit=100&sort={sort}";
You would call your getForObject() like so
OutputPage page = restTemplate.getForObject(url1, OutputPage.class, sort);
I strongly suggest you do not send any JSON in a request parameter of a GET request but rather send it in the body of a POST request.
If the solution suggested by sotirios-delimanolis is a little difficult to implement in a scenario, and if the URI string containing curly braces and other characters is guaranteed to be correct, it might be simpler to pass the encoded URI string to a method of RestTemplate that hits the ReST server.
The URI string can be built using UriComponentsBuilder.build(), encoded using UriComponents.encode(), and sent using RestTemplate.exchange() like this:
public ResponseEntity<Object> requestRestServer()
{
HttpEntity<?> entity = new HttpEntity<>(requestHeaders);
UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(rawValidUrl)
.queryParams(
(LinkedMultiValueMap<String, String>) allRequestParams);
UriComponents uriComponents = builder.build().encode();
ResponseEntity<Object> responseEntity = restTemplate.exchange(uriComponents.toUri(), HttpMethod.GET,
entity, String.class);
return responseEntity;
}
Building, encoding, and extracting URI have been seperated out for clarity in the above code snippet.
You can URL encode the parameter values:
String url1 = "http://api.example.com/Search?key=52ddafbe3ee659bad97fcce7c53592916a6bfd73&term=&limit=100&sort=";
org.apache.commons.codec.net.URLCodec codec = new org.apache.commons.codec.net.URLCodec();
url1 = url1 + codec.encode("{\"price\":\"desc\"}");
OutputPage page = restTemplate.getForObject(url1, OutputPage.class);
You can set a specific UriTemplateHandler in your restTemplate. This handler would just ignore uriVariables :
UriTemplateHandler skipVariablePlaceHolderUriTemplateHandler = new UriTemplateHandler() {
#Override
public URI expand(String uriTemplate, Object... uriVariables) {
return retrieveURI(uriTemplate);
}
#Override
public URI expand(String uriTemplate, Map<String, ?> uriVariables) {
return retrieveURI(uriTemplate);
}
private URI retrieveURI(String uriTemplate) {
return UriComponentsBuilder.fromUriString(uriTemplate).build().toUri();
}
};
restTemplate.setUriTemplateHandler(skipVariablePlaceHolderUriTemplateHandler);
You can encode url before using RestTemplate
URLEncoder.encode(data, StandardCharsets.UTF_8.toString());
You can simply append a variable key to the URL and give the value using the restTemplate.getForObject() method.
Example:
String url = "http://example.com/api?key=12345&sort={data}";
String data="{\"price\":\"desc\"}";
OutputPage page = restTemplate.getForObject(url, OutputPage.class, data);
Using below struts.xml setting, changing action extension from .action to .html was a success.
<constant name="struts.action.extension" value="html"/>
However, the old links from Google search results or other external links are still pointed to .action url, it always redirect to no page found error when clicked.
Is there anyway I can redirect those .action url to latest .html links?
Here is the code for the interceptor that replaces .action url to .html.
Don't forget to declare the added interceptor in struts.xml.
I hope it will be helpful to others looking for it. ;)
#Override
public String intercept(ActionInvocation actioninvocation) throws Exception {
HttpServletRequest request = ServletActionContext.getRequest();
HttpServletResponse response = ServletActionContext.getResponse();
StringBuffer url = request.getRequestURL();
if(url != null && url.indexOf(".action") > 0) {
String fullUrl = url.toString().replace(".action", ".html");
String queryString = request.getQueryString();
fullUrl += (queryString == null ? "" : ("?" + queryString));
// return new url with .html
response.sendRedirect(fullUrl);
}
return actioninvocation.invoke();
}
I need to retrieve URL from current Web page opened in Firefox by using Wicket. Can somebody tell me how to do that?
To get the current page's url use the webrequest and UrlRenderer:
Url url = ((WebRequest)RequestCycle.get().getRequest()).getUrl();
String fullUrl = RequestCycle.get().getUrlRenderer().renderFullUrl(url);
You need to query the underlying HTTPServletRequest:
public class DummyPage extends WebPage{
private String getRequestUrl(){
// this is a wicket-specific request interface
final Request request = getRequest();
if(request instanceof WebRequest){
final WebRequest wr = (WebRequest) request;
// but this is the real thing
final HttpServletRequest hsr = wr.getHttpServletRequest();
String reqUrl = hsr.getRequestURL().toString();
final String queryString = hsr.getQueryString();
if(queryString != null){
reqUrl += "?" + queryString;
}
return reqUrl;
}
return null;
}
}
Reference:
(Wicket) Component.getRequest()
(Wicket) Request
(Wicket) WebRequest
(Servlet API) HTTPServletRequest
The solution from Sean Patrick Floyd seems to be obsolete for wicket 1.5
If using wicket 1.5 (or above I guess) here is the solution:
RequestCycle.get().getUrlRenderer().renderFullUrl(
Url.parse(urlFor(MyPage.class,null).toString()));
Reference:
Getting a url for display
Depending on what exactly you want, this may not be possible. There is a short guide here in the Wicket wiki, but it has some caveats, notably that it only returns a relative URL in versions of Wicket after 1.3. That said, the method used is
String url = urlFor("pageMapName", MyPage.class, new PageParameters("foo=bar"));
If you go with the wiki's alternate method — the one involving the form — be warned: getPage() is not part of Wicket's public API.
This works. I'm using wicket 1.5;
new URL(RequestCycle.get().getUrlRenderer().renderFullUrl(
Url.parse(urlFor(HomePage.class,null).toString()))).getAuthority();
Example: http://example.com:80/a_long_path/
getAuthproty() will return example.com:80
getHost() will return example.com.
<li><a href="<%=
UTIL.getServletPath("/SetupPage?PG=setupusersettings") %>">
<span>Settings</span></a>
public String getServletPath(String fileName)
{
if(!fileName.startsWith("/"))
fileName = "/" + fileName;
return getContextPath() + fileName;
}
public String getContextPath()
{
try
{
return request != null ? request.getContextPath() : "";
}
catch(Exception ex)
{
DBGlobals.Error(ex);
return "";
}
}
public interface HttpServletRequest extends javax.servlet.ServletRequest {
java.lang.String getContextPath();
I have a few questions..
What does getServletPath do?
What does getContextPath do?
Canyone explain me the flow?
original derived from Oracle's specs:
http://download.oracle.com/javaee/1.2.1/api/javax/servlet/http/HttpServletRequest.html
getServletPath
public java.lang.String getServletPath()
Returns the part of this request's URL that calls the servlet. This includes either the servlet name or a path to the servlet, but does not include any extra path information or a query string. Same as the value of the CGI variable SCRIPT_NAME.
getContextPath
public java.lang.String getContextPath()
Returns the portion of the request URI that indicates the context of the request. The context path always comes first in a request URI. The path starts with a "/" character but does not end with a "/" character. For servlets in the default (root) context, this method returns "".
Returns:
a String specifying the portion of the request URI that indicates the context of the request
I think that the spec is descriptive enough.
Regards.