solve the path to css in jsp - java

I'm using Spring MVC 3.0 to construct a rest-style url.
Here is part of my code:
#RequestMapping(value = {"/", "/posts"}, method = RequestMethod.GET)
public String getNewestPosts(Model model, HttpServletRequest request)
throws DataAccessException {
return getPostsByPage(1, model, request);
}
#RequestMapping(value = "/posts/page/{page}", method = RequestMethod.GET)
public String getPostsByPage(#PathVariable long page, Model model,
HttpServletRequest request) throws DataAccessException {
// ... get the posts by page number
}
I wrote two methods. One handles the request from url "/posts" which means retrieving the first page of the posts , and the other one handles the request from url "/posts/page/{page}" which means retrieving the posts according to the path variable {page}.
And the problem is that all the two methods above point to the same view which is a jsp file, but they're in different paths("/posts, "/posts/page/xxx"). The css path (../style.css) can not adapt both of them.
I try to solve it by using absolute css path(/style.css), which means the web application works only if the application is deployed on a root path("/").
I would appreciate it if you could help me.

Use the <c:url> tag, which prepends the context path to an absolute URL.
<link rel="stylesheet" type="text/css" href="<c:url value="/style.css" />" />
or
<c:url var="cssUrl" value="/style.css" />
<link rel="stylesheet" type="text/css" href="${cssUrl}" />

Related

Thymeleaf 3 URL resolving not working with Spring Boot 4 + Spring Security

After having configured Thymeleaf 3 in Spring Boot 4 using the Gradle configuration
compile('org.springframework.boot:spring-boot-starter-thymeleaf')
compile('org.thymeleaf:thymeleaf:3.0.3.RELEASE')
and
ext['thymeleaf.version'] = '3.0.3.RELEASE'
ext['thymeleaf-layout-dialect.version'] = '2.1.2'
URL resolvers do not properly resolve the URLs in Thymeleaf views:
<link rel="stylesheet" href="/css/login.css" data-th-href="#{~/css/login.css}">
simply becomes
<link rel="stylesheet" href="/css/login.css">
I have done some debugging and first of all, during a request I noticed that SaveToSessionResponseWrapper (sub of SaveContextOnUpdateOrErrorWrapper) gets initialized like this:
public SaveContextOnUpdateOrErrorResponseWrapper(HttpServletResponse response,
boolean disableUrlRewriting) {
super(response);
this.disableUrlRewriting = disableUrlRewriting;
}
The arguments passed are a FireWalledResponse and false. The latter results in the following method completely disabling the forwarding of URLs:
#Override
public final String encodeURL(String url) {
if (this.disableUrlRewriting) {
return url;
}
return super.encodeURL(url);
}
Now, if I put a breakpoint in the constructor and force disableUrlRewriting to be true, it eventually executes HttpServletResponseImpl.isEncodeable which then fails here:
} else if(hreq.isRequestedSessionIdFromCookie()) {
return false;
At this point I'm not sure what is wrong. I'm unable to find anyone with this error and it works with neither starter-tomcat nor starter-undertow but I haven't done as thorough debugging in Tomcat yet.
#{~/css/login.css} is a server-relative URL in Thymeleaf.
If you want a context-relative URL, omit the tilde (~) character:
<link rel="stylesheet" href="/css/login.css" data-th-href="#{/css/login.css}">
See Standard URL Syntax article for details.
You should use
<link rel="stylesheet" href="/css/login.css" th:href="#{/css/login.css}">
Without data-th-href

Spring dynamic url access to css/js files

I have a simple Spring boot application. There URL that would be used here is going to be like:
sub.domain.com/variable1/variable2
and variable1 and variable2 can be anything for example:
sub.domain.com/kfc/foo
sub.domain.com/subway/boo
and I capture those in my controller as below:
#Controller
public class IndexController {
#RequestMapping(value="/{var1}/{var2}", method = RequestMethod.GET)
public String Index(#PathVariable(value="var1") String variable1, #PathVariable(value="var2") String variable2) {
return "/index.html";
}
}
which will redirect to my html page which is located at src/main/webapp/index.html
so the index page is loaded under the dynamic url but then none of the scrips or stylesheets are found because it's trying to find them under variable1 path.
for example if I have
sub.domain.com/kfc/foo
and my link to css in the index.html is
<link rel="stylesheet" href="styles/index.css" />
it will try to find the index.css under
sub.domain.com/kfc/styles/index.css
how can I tell the app to look into the right place for the styles or js files?
index.html is trying to load styles from a relative path.
In order for index.html to load styles under sub.domain.com/styles/index.css, add a / in link tag **/**styles/index.css <link rel="stylesheet" href="/styles/index.css" />

Spring MVC - Double Slash in RequestMapping causes bugs in CSS link

I have a controller, and i put double slash on it.
#RequestMapping(value="/vehicles/add", method = RequestMethod.GET)
public String addVehicle(Model model) {
model.addAttribute("vehicle", new Vehicle());
return "newvehicle";
}
And the CSS link:
<link rel="stylesheet" type="text/css" href="css/main.css"/>
What happened is when I have double slash, the css link of the html was not working. So I tried to just use single slash
RequestMapping(value="/add", method = RequestMethod.GET)
and it worked. But I want to have a double slash. What do you think is the problem. I think the directory is not the problem because it worked with single slash.

How I load css and js of Bootstrap in a web java application (jsp)?

If I use the controller (Servlet) don't see the Boostrap styles.
The events are:
[1] Load login.jsp
[2] Send login information to SessionController (Servlet) throught POST.
[3] SessionController save the information in the Session, create an attribute in the session for indicate to FormsController his work:
request.getSession().setAttribute("user", request.getParameter("usuario"));
request.getSession().setAttribute("pass", request.getParameter("clave"));
request.getSession().setAttribute("pg", "showAll");
request.getRequestDispatcher("FormsController").forward(request, response);`
In this moment pg = "showAll" and SessionController call to FormsController.
[4] FormsController search information in the DataBase and redirect to formularios/datos.jsp
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
switch (request.getParameter("p")) {
case "new":
request.getRequestDispatcher("formularios/nuevoformulario.jsp").forward(request, response);
break;
case "showAll":
DBFormulario f = new DBFormulario(request.getSession().getAttribute("user").toString(), request.getSession().getAttribute("pass").toString());
try {
request.getSession().setAttribute("formularios", f.consultarFormularios());
request.getRequestDispatcher("formularios/datos.jsp").forward(request, response);
} catch (DBExceptionsManager ex) {
Logger.getLogger(FormsController.class.getName()).log(Level.SEVERE, null, ex);
}
break;
}
}
More information:
index.jsp:
<meta http-equiv="refresh" content="0;URL=login/login.jsp" />
login.jsp:
http://s2.subirimagenes.com/imagen/9582471login.png
datos.jsp:
http://s2.subirimagenes.com/imagen/9582472datos.png
Views:
http://s2.subirimagenes.com/imagen/previo/thump_9582470sin-ttulo.png
The better way to load the resource files I think is to use the tag jstl core library which provides the tag url to proper URL encoding, for using this library you have to import the jstl/core tag library in your jsp and you will get great benefits of the library which contains if-else, for and many more conditions statements.
To import the library, <%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> write this in your jsp,
and re-write your link tag like below,
<link rel="stylesheet" type="text/css" href="<c:url value='/css/bootstrap.min.css'">

Access data in external javascript file working with Spring MVC?

I am using spring 3 MVC and i have below classes.
External system would call my application using below URL:
http://somehost/root/param1/param2/param3
I have a spring MVC controller method as below:
public ModelAndView showPage(#PathVariable("param1") String paramOne, #PathVariable("param2") String paramTwo, #PathVariable("param3") String paramThree, HttpServletResponse response) {
SomeModel model = new SomeModel(paramOne, paramTwo, paramThree);
return new ModelAndView("SomeJsp", "model", model);
}
SomeModel.java
public class SomeModel{
private String paramOne;
private String paramTwo;
private String paramThree;
//constructor
//setters and getters
}
SomeJsp.jsp
//In this Jsp i have a div with few elements. Div is not visible by default.
//This jsp has externalJavascript included.
//I enable div and set the data into div elements using jquery.
externalJs.js
$(document).ready(function() {
//Here i need the model returned using ModelAndView
//I can get data from model and set into div elements.
});
In external java script file, is it possible to get the model content?
Thanks!
In the jsp page you may define global js variable and access those variables from the external js like:
jsp file
<script>
myModel=[];
myModel.paramOne='${model.paramOne}';
myModel.paramTwo='${model.paramTwo}';
myModel.paramThree='${model.paramThree}';
</script>
All server side scripts been rendered at server side and those value will be hardcoded once rendered. Once page loaded in the browser, global variables will be created with the rendered hardcoded value.
And my myModel can be access in the external file also.
EDIT:
Here is the someJsp.jsp file
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE>
<html>
<head>
<script>
myModel=[];
myModel.paramOne='${model.paramOne}';
myModel.paramTwo='${model.paramTwo}';
myModel.paramThree='${model.paramThree}';
</script>
<script src="externalJs.js"></script>
</head>
<body>
<!--content-->
</body>
and externalJs.js
$(document).ready(function() {
// myModel will be accessible from here because it's globally declared
alert(myModel);
});

Categories