I have found several way to set the context path, but didn't found anyway to get the context path in the spring boot application. There is one way to get it through #Value("server.contextPath"), but I am looking for more elegant way to get hold of it.
You can get the context path in controller as:
#RequestMapping(method = RequestMethod.GET, value = "/getUsers")
public String getUsers(HttpServletRequest request) {
String path = request.getContextPath();
//...
}
You could pass in the Request and use request.getContextPath if you'd like.
Check the Javadoc to see if this would work for you?
You can set the contextPath within the application.properties file.
something like this:
server.contextPath=/yourChosenContextPath
Related
I have a Java/Spring web application.
Controller code that shows the view looks like this:
#RequestMapping(value = { "showmessage/{messageId}" }, method = RequestMethod.GET)
public ModelAndView viewMessage(Model model, #PathVariable("messageId") Integer messageId) throws Exception {
/* do stuff */
return new ModelAndView("show-message","message",message);
}
Which displays the contents of the show-message.jsp file.
The problem is, the show-message.jsp file is trying to load resources that are in the myapp.WAR file ... for example ...
/resources/dist/js/jquery/jquery-validate-1.17.0/jquery.validate.js
The browser reports that it failed to load this from this URL ...
http://localhost:8080/myapp/showmessage/resources/dist/js/jquery/jquery-validate-1.17.0/jquery.validate.js
... because the resource is actually here ...
http://localhost:8080/myapp/resources/dist/js/jquery/jquery-validate-1.17.0/jquery.validate.js
If I change the resource line in the JSP from "resources/dist/..." to SLASH "/resources/dist/..." is still doesn't work because it tries load this ...
http://localhost:8080/resources/dist/js/jquery/jquery-validate-1.17.0/jquery.validate.js
... and fails.
What's wrong with my app and how do I make this work?
In you JSP you are most likely using a relative href values e.g.:
<scripts src="resources/dist/js/jquery/jquery-validate-1.17.0/jquery.validate.js"></script>
The browser will resolve it against the current URL which is showmessage/{messageId} based on your #RequestMapping annotation.
Try specifying an absolute URL to your script. Since you have JSP you can use <c:url>.
<scripts src="<c:url value="/resources/dist/js/jquery/jquery-validate-1.17.0/jquery.validate.js"/>"></script>
i have tried to write an upload option in my web application following mentioned is my code
#RequestMapping( value="/group/import/upload", method=RequestMethod.GET )
public String GroupImportInfo( Model model )
{
System.out.println("in controller");
return "upload-File-import";
}
i have a upload-File-import.jsp file, but when i try to access that page am getting an exception saying..
type Status report
message /corept/WEB-INF/views/upload-File-import.jsp
description The requested resource (/corept/WEB-INF/views/upload-File-import.jsp) is not available.
JBoss Web/7.0.13.Final
Thanks for helping.
It seems the ViewResolver is unable to locate the view. Hence, I suggest you to check configuration of the ViewResolver bean's prefix property(in the spring-servlet-config.xml) if it is matching the path of the requested view.
Apart from that I dont see any issue with your code.
I need application context path in controller, I tried the below code its throwing NULLPOINTER EXCEPTION.
HttpServletRequest request;
String Path = request.getContextPath();
Please help me
Thanks
Variable request is declared, but is not
initialized. No wonder you get a NullPointerException.
Look at documentation to access different request related data.
After you read that, and are sure you want to tie your code to native Servlet API, try this:
#Controller
class MyController {
#RequestMapping
public void handleMe(HttpServletRequest request) {
String path = request.getContextPath();
}
}
What's the difference between localhost/user/user123, localhost/user?user=user123 and localhost/?user=user123?
How to get the parameter user123 from a URL localhost/user/user123 in servlet?
Thanks in advance
You can parse from the getPathInfo() of HttpServletRequest Object.
sample code
String urlPath = request.getPathInfo();
System.out.println("" + urlPath.substring(urlPath.lastIndexOf("/"), urlPath.length()- 1));
localhost/user/user123 looks like a RESTful way to identify a resource.
The two others aren't, I think.
These all are accessible from Servlet API. Check HttpServletRequest, you can access all information from there.
The actual values may differ how your webapp was deployed, but usually
localhost is the Context Path
the String after that is the Servlet PAth
the parameters after the ? is the Query String - you have to parse it, if you want to use
Generally you pass parameters like
/localhost/Servlet?parameter1=one
or for a JSP
/localhost/mypage.jsp?parameter1=one
In a servlet you can access the parameters by using the request object. So generally like this:
String parameter1 = request.getParameter("parameter1");
Here is some detail on getParameter for HttpServletRequest
Hope this helps.
localhost/user/user123 - this url will be handled by pattern /user/user123
localhost/user?user=user123 - this url will be handled by pattern /user, with user parameter set to user123 (for GET request)
localhost/?user=user123 - this url will be handled by pattern / with user parameter set to user123 (again, for GET)
I don't know how to retrieve user123 from url localhost/user/user123 with pure servlets, but it's pretty easy with web MVC frameworks. Spring example:
#Controller
#RequestMapping("/user")
public class Controller {
#RequestMapping(value = "/{user}")
public String getUser((#PathVariable String user) {
//here variable "user" is available and set to "user123" in your case
}
}
I'd like to find the absolute URL of the webapp in Spring, from the Controller. I'm aware of JSTL c:url, but I need this info from inside the Controller.
#Controller
public class AuthorizeController {
#Autowired
private Authorizer auth;
#RequestMapping("/auth")
public String sendToAuthorization() {
String baseUrl = "http://localhost:8080/tasks/";
return "redirect:" + auth.getAuthorizationUrl(baseUrl);
}
}
As you can see the baseUrl is hardcoded, and I could provide it to the Authorizer class via Spring configuration, but I am sure that it's possible to get this information from Spring within the Controller. I tried to google "spring mvc url" and could not find a way to solve this problem.
I think that getting absolute url is only possible while processing the request as your server may have many IP addresses and domain names.
#RequestMapping("/auth")
public String sendToAuthorization(HttpServletRequest request) {
String baseUrl = String.format("%s://%s:%d/tasks/",request.getScheme(), request.getServerName(), request.getServerPort());
return "redirect:" + auth.getAuthorizationUrl(baseUrl);
}
As for the servlet, it may also have several mappings in web.xml.
similar question
P.S. Anyway, url parsing in runtime does not look like a good idea to me.
Very late to this answer, but a variant to Boris's answer, if you don't want to push servlet objects into method signatures, is to use RequestContextHolder from a utility class/method. This would also give the ability to abstract fallback logic (e.g., pulling from a property file). Cheesy example:
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
if(null != requestAttributes && requestAttributes instanceof ServletRequestAttributes) {
HttpServletRequest request = ((ServletRequestAttributes)requestAttributes).getRequest();
// build URL from request
}
else {
// fallback logic if request won't work...
}
This presumes you have org.springframework.web.context.request.RequestContextListener registered as a listener in web.xml