Thymeleaf and Static Resources with fingerprint - java

I have tried to add fingerprint suffix to some of my static files (Ex. app.min.js / style.min.css) using ResourceResolvers and ResourceTransformers
http://spring.io/blog/2014/07/24/spring-framework-4-1-handling-static-web-resources
I have config the ResourceHandler like this
#Configuration
#EnableWebMvc
public class ResourceResolverConfiguration extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("bower_components/**/*.js", "/assets/**", "/build/**")
.addResourceLocations("/bower_components/", "/assets/", "/build/","classpath:/META-INF/webapp/build/")
.resourceChain(true)
.addResolver(
new VersionResourceResolver()
.addContentVersionStrategy("/**")
);
}
}
and in my main controller I have add some debug log.
logger.debug("js = '{}'" + this.resourceUrlProvider.getForLookupPath("/build/app.js"));
logger.debug("css = '{}'" + this.resourceUrlProvider.getForLookupPath("/build/styles/style.css"));
After run the web application, from the debug log, there is fingerprint in each file like
app-5d2c76ad6517f26d252d5cc93a4fc7d2.js
and I can access this file directly, (ie. via localhost:8080/build/app-5d2c76ad6517f26d252d5cc93a4fc7d2.js)
However, when I click view source at the web browser, it is still an original file without any fingerprint.
which in my layout.html I load the script/link like this.
<script th:src="#{/build/app.js}"></script>
<link th:href="#{/build/styles/style.css}" rel="stylesheet"></link>
I use Thymeleaf for template engine.
What should the configuration or code be to make Thymeleaf include the fingerprint files or did I miss something ?
Thank you very much.

Make sure you're including the appropriate encoding filter, which is what the #{} syntax uses to rewrite URLs:
#Bean
public ResourceUrlEncodingFilter resourceUrlEncodingFilter() {
return new ResourceUrlEncodingFilter();
}

Try this to render the fingerprint along with the filename
<script th:src="${#mvcResourceUrlProvider.getForLookupPath('/build/app.js')}" />
The above results in:
<script src="/build/app-16e85c31092c68733df3c729b831dcfd.js"></script>
I know this is late, but I was looking for the same answer for how to render urls to work with addContentVersionStrategy and this came up, so hopefully it helps someone else.

Related

Customize contents in swagger-ui.html

I am using spring boot 2.1.6.RELEASE and swagger 2.9.2, everything is fine except that I want to simplify the content.
First, I want to remove the base URL under title:
[ Base URL: localhost:7777/ ]
http://localhost:7777/v2/api-docs
And, I want the API blocks and Models block to be opened on visiting, not until I click the name.
And, I want the select a spec list on the top banner to be removed or hidden.
I don't know if there is a way to do these with java API, I can't find any solution other place.
The picture I tried to upload:
Seems that I am not allowed uploading picture yet, don't blame me if the picture above is unavailable.
here i find a class helping to configure swagger UI:
springfox.documentation.swagger.web.UiConfiguration
and here is my usage:
#Bean
public UiConfiguration uiConfig() {
return UiConfigurationBuilder.builder()
.deepLinking(false)
.displayOperationId(false)
.defaultModelsExpandDepth(1)
.defaultModelExpandDepth(1)
.defaultModelRendering(ModelRendering.MODEL)
.displayRequestDuration(true)
.docExpansion(DocExpansion.LIST)
.filter(false)
.maxDisplayedTags(null)
.operationsSorter(OperationsSorter.METHOD)
.showExtensions(false)
.tagsSorter(TagsSorter.ALPHA)
.validatorUrl(null)
.build();
}

Spring Boot/MVC: How to serve static files outside JAR with special characters?

I am currently working on a project where I need to serve static files residing on file system (outside the JAR-File).
What I currently have:
#Configuration
#ComponentScan({"some.package"})
public class MaboConfiguration extends WebMvcConfigurerAdapter {
/* Irrelevant configs omitted */
#Value("${application.pdfpath}")
public String pdfPath;
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/files/**")
.addResourceLocations("file:" + this.pdfPath);
super.addResourceHandlers(registry);
}
}
This works for most files in the configured "pdfPath" directory. Now the problem is, that files containing special characters (like: "ä", "ö", "ü",...) cannot be found and the servers returns 404.
Example for working file (given pdfPath is /opt/tst/):
"/opt/tst/tstdir/with some space/01 - my tst pdf.pdf" -> is served under
"http://localhost:8100/contextRoot/files/tstdir/with some space/01 - my tst pdf.pdf"
Example for not working file:
"/opt/tst/tstdir/with some space/01 - my ätst pdf.pdf" -> should be served under
"http://localhost:8100/contextRoot/files/tstdir/with some space/01 - my ätst pdf.pdf"
I think this might be an encoding issue. The logs show that the incoming request is correctly URL-Encoded (UTF-8, e.g: "ä" becomes "%C3%A4"). Though, using trace, the logs also show that spring resolves "%C3%A4" to "?" when looking for the corresponding file.
Is there any way to tell the Resolver to resolve the File URL using a specific charset?

JHipster - Removing # HASH from URL permanently

I can see all the urls in jhipster are having #, how to remove it properly, I don't want to show # in my application's urls, I created application in angular 4
We do have this tip in our docs although I have never tried it myself :
https://jhipster.github.io/tips/010_tip_configuring_html_5_mode.html
The tip is only for angularjs 1. You can try to combine it's advice with the official angular docs on routing : https://angular.io/guide/router
If you manage to make it work please do a PR on our website : https://github.com/jhipster/jhipster.github.io
I spent many hours to achieve this and finally has paid off. You can follow these steps:
Remove on angular app avery use of hash location strategy in every RouterModule.forRoot...:
{useHash: false}
Go to java app to the config folder and create a new java class to manage the error pages to redirect to index.html:
#Configuration
public class ErrorPageConfig implements ErrorPageRegistrar {
#Override
public void registerErrorPages(ErrorPageRegistry registry) {
registry.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/index.html"));
}
}
This page was very helpful
https://www.baeldung.com/spring-cloud-angular

How to use processing sketch in a web app

Good day, i have a Processing sketch that i want to use in a web application
i am using jsp and servlets in my web app with tomcat as a server. I am using netbeans and i tried using < applet > tag but i can't get it to work, please help.
CODE:
import processing.core.*;
public class MyProcessingSketch extends PApplet {
public static void main(String args[]) {
PApplet.main(new String[] { "MyProcessingSketch" });
}
public void setup() {
}
#Override
public void draw() {
background (200,0,0);
}
public void settings(){
size(600,240);
}
public void mousePressed(){
exit();
}
}
Applets are not really supported anymore... But you might try p5js. Your HTML page would look like this:
<html>
<script src="http://cdnjs.cloudflare.com/ajax/libs/p5.js/0.4.6/p5.js"></script>
<script>
function setup() {
createCanvas(600, 240);
background(200,0,0);
}
function draw() {
// ...
}
</script>
Like the other answer says, applets are pretty much dead. They currently require you to have a paid signed certificate or for your users to change their security settings. And even then they show a bunch of scary warning dialogs, and it's just a pain in the neck for everybody. Chrome has dropped support for applets, and they'll be deprecated in the next version of Java.
If you're using eclipse, you've got three options:
Deploy as a runnable jar.
Deploy as a packaged executable.
Deploy using webstart.
None of these are embedding an applet in a webpage.
However, if you're using the Processing editor, you can use Processing.js to write the same Processing code but have it deployed as JavaScript, which you can embed in a webpage. Processing.js does the translation for you, so you don't have to change your code into JavaScript code.
You can also use p5.js, but that will require you to completely rewrite your syntax into JavaScript syntax.
In either case, you'll no longer be able to use Java libraries in your code. You'll have to find a JavaScript library that does the same things and use that instead. If you really need to use the Java libraries, then you have to go with deploying using one of the first three options.

Play-Rest API with Java - basic response

I'm new in the server-side , and I'm trying to learn how to use play in rest api with java and restangular. I made a project for java in the intellij. I want the GET request to return an html page and not html.scala page.
how do I change this function that it will return the app/views/index.html instead the app/views/index.html.scala
also if someone have a good website to learn from, it will help a lot
the function in java :
package controllers;
import play.*;
import play.mvc.*;
import views.html.*;
public class Application extends Controller {
public static Result index() {
return ok(index.render("Your new application is ready."));
}
}
the routes page :
# Routes
# This file defines all application routes (Higher priority routes first)
# ~~~~
# Home page
GET / controllers.Application.index
# Map static resources from the /public folder to the /assets URL path
GET /assets/*file controllers.Assets.at(path="/public", file)
Play use twirl as a template engine. I am not sure if you can easely change it to some other template engine but I think you can. Any way, as I see you are looking for a way just output simple HTML file. You can do this with default Assets controller:
this string in your route
GET /assets/*file controllers.Assets.at(path="/public", file)
would handle any files in the public. So if you will add to the public directory the simple /html/hello.html file then Play will render it by the url /assets/html/hello.html. You can change URL as you like in the rote file
I found a similar question with good answer with a lot of examples.
you can find it here.
The easiest way is to make a GET request for the / and to send the destination also, like this:
# Home page
GET / controllers.Assets.at(path="/public",file="index.html")

Categories