Java Play2 with CDN - java

I am using a CDN (amazon cloudfront) and I am trying to configure play to work with a CDN
GET xxxxxxxxx.cloudfront.net/*file controllers.Assets.at(path="",file)
The problem with this approach is that my image url looks like this
http://localhost:9000/xxxxxxxxxxxxxxx.cloudfront.net/images/Ascalon_Wall_Ruins.jpg
I would need to remove the http://localhost:9000/
Any ideas how I can do this?

You don't need to use Play's router for building external links, instead you can just prefix it with domain, ie. if you're storing paths in your model as images/Ascalon_Wall_Ruins.jpg in its file field, you can just put it directly in template:
#for(item <- itemsList){
<img src="http://domain.tld/#item.file" />
}
Of course you can also create additional method in your model's class to deliver ready-to-use path.

I solved my problem like this:
package Config;
public class CDN {
private final static String url = "http://yourcdnurl.net/;
public static String createUrl(String s) {
return url + s;
}
}
usage:
<link rel="stylesheet" media="screen" href= "#Config.CDN.createUrl("stylesheets/bootstrap.css")">

Related

How can you build an absolute URL in thymeleaf?

I would like to display an absolute url generated at run-time with a parameter. Not create a href to a page but display the URL using th:text. Any simple way to do this with Tymeleaf (without having to concatenate the URL pieces from #request object and without using some MVC utility class)?
Attempt 1
<p th:text="#{/myServlet(myParam=${dynamicParameter})}" /> - only displays part of the URL leaving out the protocol, port and host name. I am getting /myServlet?myParam=123. The same behavior as for th:href, if you inspect the <a> you will see the same href - in that case the browser helps by inferring the protocol, port and so on
Attempt 2
th:text="#{__${#httpServletRequest.requestURI}__}" - produces a relative URI of the current page that doesn't include the protocol and so on
Attempt 3
th:text="#{__${#httpServletRequest.requestURL}__}" - produces this time an absolute URL of the current page containing the protocol, host and servlet context. The problem now is when I display this text from a different page, my URL is ...myApp/myOtherServlet so I need to edit this string to replace myOtherServlet with the URI I want.
Non Tymeleaf Attempt 1
#Service("urlUtils")
public class UrlUtilsServiceImpl implements UrlUtilsService {
#Override
public String getAbsoluteUrlTo(final String aPath, final String param, final String value){
return ServletUriComponentsBuilder
.fromCurrentContextPath()
.path(aPath)
.queryParam(param, value)
.build().toString();
}
}
page.html:
th:text="${#urlUtils.getAbsoluteUrlTo('/myServlet', 'myParam', ${dynamicParameter})}"
The problem is the host name that can be aliased before it reaches my server (see this).
Thymeleaf+JS Sollution
Using some java script plus thymeleaf
<p id="myUrl" th:text="#{/myServlet(myParam=${dynamicParameter})}" />
<script type="text/javascript">
$(document).ready(function () {
var myUrl= $("#myUrl");
myUrl.text(window.location.origin + myUrl.text());
});
</script>
You can concatenate servlet request on the fly:
th:text="${#httpServletRequest.scheme}+'://'+${#httpServletRequest.serverName}+':'+${#httpServletRequest.serverPort}+#{/myServlet(myParam=${dynamicParameter})}"
Or for JavaScript:
<script type="text/javascript">
GLOBAL.serverURI = '[[${#httpServletRequest.scheme}+'://'+${#httpServletRequest.serverName}+':'+${#httpServletRequest.serverPort}+#{/myServlet(myParam=${dynamicParameter})}]]';
</script>

Play Framework - value login is not a member of controllers.Application

I'm running the latest Play Framework 2.5.1 and I'm getting an error from my log on page:
Error:
value login is not a member of controllers.Application
I have tried adding the # symbol i.e:
#controllers.Application.login()
And removing the injector from the build.sbt, clean up/ clean-files and updates in "CMD". I'm using the sample from https://www.playframework.com/documentation/2.1.0/JavaGuide.
HTML CODE
#(form: Form[Application.Login])
<html>
<head>
<title>Zentasks</title>
<link rel="shortcut icon" type="image/png" href="#routes.Assets.versioned("images/favicon.png")">
<link rel="stylesheet" type="text/css" media="screen" href="#routes.Assets.versioned("stylesheets/login.css")">
</head>
<body>
<header>
<span>Zen</span>tasks
</header>
</body>
</html>
CONTROLLERS
package controllers;
import play.*;
import play.mvc.*;
import views.html.*;
public class Application extends Controller {
public Result index() {
return ok(index.render("Your new application is ready."));
}
public static Result login() {
return ok(
login.render(form(Login.class))
);
}
public static class Login {
public String email;
public String password;
}
}
ROUTES
# Routes
# This file defines all application routes (Higher priority routes first)
# ~~~~
# Home page
GET / controllers.Application.index()
GET /login controllers.Application.login()
# Map static resources from the /public folder to the /assets URL path
GET /assets/*file #controllers.Assets.versioned(path="/public", file: Asset)
Remove the static keyword from your controller's actions. Play 2.5.1 uses dependency injection by default and if you want to use static actions, you need to explicitly configure it. So, your login action must be like:
// no static keyword here
public Result login() {
return ok(login.render(form(Login.class)));
}
Update:
By the way, you are mixing a lot of things here. I recommend you to not follow 2.1.0 guide while developing for version 2.5.x since there is a lot of differences between these two versions. In fact, Play 2.1.0 is from Feb 06 2013.
Here are some references that explain why your code was failing:
Java Routing: Dependency Injection
Dependency injecting controllers
Replaced static controllers with dependency injection

two different URI mapping same view, one works well, however css can not be loaded for the other one

There are two methods with different URI which mapping to the same view in spring boot, the first one works well, however, the second one can only display html and css can not be loaded, the code is as below:
#Controller
public class ExamController {
#RequestMapping("/quiz0")
public ModelAndView quizingA() {
System.out.println("run into quiz0");
ModelAndView modelAndView = new ModelAndView("examination");
return modelAndView;
}
#RequestMapping("/quiz1/{course}")
public ModelAndView quizingB(#PathVariable("course") String course) {
System.out.println("run into quiz1, couse choosed: " + course);
ModelAndView modelAndView = new ModelAndView("examination");
return modelAndView;
}
}
From the log, both of them are reached successfully, as I known, there shouldn't be error existed, right?
For the first one which works well the url I used is;
http://localhost:8080/quiz0
For the second one which failed the url I used is:
http://localhost:8080/quiz1/Java
One more information, I have disabled spring security with override WebSecurityConfigurerAdapter. I can paste it out if required.
Could anyone help to explain it?
Thanks in advance.
You're probably including your css with a relative path instead of an absolute one.
e.g.
if you include like this
<link type="text/css" href="css/bootstrap.css" rel="stylesheet"/>
The paths will be converted to
/quiz0/css/bootstrap.css
and
/quiz1/{course}/bootstrap.css
I recommend using it with absolute path
<link type="text/css" href="/css/bootstrap.css" rel="stylesheet"/>

Spring 4 - MVC - URL param and static resource path

I have a spring mvc application, in a page I list the "Group" details in a table, fetched from database. The url of every group is set to "/viewgroup/410", where 410 is the groupid which will be loaded from the database and displayed in the viewgroup.jsp page.
<td>${group.name}</td>
So, the controller method has the
#RequestMapping("/viewgroup/{groupid}")
public String viewGroup() {
...
}
like this. The jsp pages could not load the static resources which I have in the directory structure
+webapp
+resources
+css
+js
+images
+views
+login.jsp
The jsp pages has the below path for image/js/css.
<link href="resources/css/bootstrap.css" rel="stylesheet" media="screen">
I tried adding
#Controller
#RequestMapping("/viewgroup/**")
public class ViewGroupController {
...
}
and this in jsp
<link href="viewgroup/resources/css/bootstrap.css" rel="stylesheet" media="screen">
Still the jsp page loads could not load the static resources. How do I provide the resource path of the static resources in jsp pages when I pass params in the url?
The fact that you pass query parameters through any URL of your project does not affect the way it addresses static resources. You need just to include a link to your static resources (as a relative path for example) as follow :
<link href="/resources/css/bootstrap.css" rel="stylesheet" media="screen">
The resolution of such static resources is completely independent of the page you're currently looking at, be it /viewgroup/410 or /foo/bar. That's the reason why you don't need the "viewgroup" at the beginning of your link's href.
But you do need to tell Spring MVC how it should address such static resources. Usually, this is done in the Spring configuration. For example, if you use Spring MVC java config through an WebMvcConfigurer instance, you should override the addResourceHandlers method in such way :
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
EDIT : My bad, I thought Spring MVC + any view technology (JSP, Thymeleaf, etc etc) would automatically resolve link's href against the root path of the web-app but this is obviously not true to raw HTML which relative link's href are resolved against current path.
So in the end, as found by OP, links are only to be resolved against root path if they are processed with the view technology in use (in the example with JSP : <c:url value="/resources/css/bootstrap.css"/>)

Struts2 - how to generate internationalized url's?

I have an application that needs to redirect to several internationalized urls, ie
www.mydomain.com/us/myapp/xxx.action
www.mydomain.com/fi/myapp/xxx.action
dwww.mydomain.com/de/myapp/xxx.action
We have a proxy server where the url is mapped to myapp/xxx.action?country=us and redirected to the application server. The problem is how to redirect to the next action with the format above?
Now the url for the next action is generated by using country from url and adding context path and action name and opened by javascript in jsp.
Example:
<body onload="javascript:top.location='${generatedPath}';return true;"></body>
Example form submit:
<s:form id="form" action="%{generatedPath}" theme="simple" method="post" includeContext="false">
Would like to do this in a less hackish way, and have tested a bit with struts.xml and type redirectAction, but cannot seem to be able to generate the url above, with the country before context path.
I have not found any struts2 documentation describing this, but are unsure if im looking at the right place as well? Should this be handled elsewhere?
I think the following discussion can help you:
How to do dynamic URL redirects in Struts 2?
Here, your result will look like:
<result name="redirect" type="redirect">${url}</result>
And, the action would be:
private String url;
private String country;
public void setCountry(String country) {
this.country = country;
}
public String getUrl()
{
return url;
}
public String execute()
{
url = "www.mydomain.com/" + country + "/myapp/xxx.action";
return "redirect";
}

Categories

Resources