Spring MVC with Thymeleaf + Bootstrap using webjars - java

I have a Spring project where I included the following webjars into pom.xml:
<dependency>
<groupId>org.webjars</groupId>
<artifactId>bootstrap</artifactId>
<version>3.3.7-1</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>3.1.1</version>
</dependency>
Then I included in my HTML view the following link and scripts:
<link rel="stylesheet" href="#{/webjars/bootstrap/3.3.7-1/css/bootstrap.min.css}" />
<script src="#{/webjars/jquery/3.1.1/jquery.min.js}"></script>
<script src="#{/webjars/bootstrap/3.3.7-1/js/bootstrap.min.js}"></script>
But it didn't work, no mapping found:
[org.springframework.web.servlet.PageNotFound] (default task-15) No mapping found for HTTP request with URI [/TestPublicWeb-0.0.1-SNAPSHOT/webjars/bootstrap/3.3.7-1/css/bootstrap.min.css] in DispatcherServlet with name 'testapp'
...so I tried to include the following mapping into servlet.xml:
<mvc:resources mapping="/webjars/**" location="classpath:/META-INF/resources/webjars/"/>
But with this, mapping for my /TestApplication is not found:
[org.springframework.web.servlet.PageNotFound] (default task-13) No mapping found for HTTP request with URI [/TestApplication/] in DispatcherServlet with name 'testapp'
How should webjars be included in a Spring project in a correct way?

The problem is that you are mixing the standard HTML href tag with Thymeleaf's syntax #{}. Change it as follows:
<link rel="stylesheet" th:href="#{/webjars/bootstrap/3.3.7-1/css/bootstrap.min.css}" />
<script th:src="#{/webjars/jquery/3.1.1/jquery.min.js}"></script>
<script th:src="#{/webjars/bootstrap/3.3.7-1/js/bootstrap.min.js}"></script>
And if you are using Spring Security you need also specify the authorization to your webjars in the configure(HttpSecurity http) method like:
http.authorizeRequests().antMatchers("/webjars/**").permitAll();

A couple things I could think of as to why the above is not working for you. Make sure you are using spring mvc namespace inside of your servlet.xml file. Looks something like:
<bean xmlns:mvc="http://www.springframework.org/schema/mvc"....
Also not sure why you are trying to access assets using #{..} when you have specified the classpath. Try removing the #{..} like so:
<link rel="stylesheet" href="/webjars/bootstrap/3.3.7-1/css/bootstrap.min.css" />
<script src="/webjars/jquery/3.1.1/jquery.min.js"></script>
<script src="/webjars/bootstrap/3.3.7-1/js/bootstrap.min.js"></script>

Related

Spring MVC CSS, fonts, images wont show in index.html page

I'm new to spring framework and I was able to run my index.html from my localhost but all resources won't show. Below is my folder structure
- src/main
- webapp
- resources
- css (All css files)
- fonts (All font files)
- images (All image files)
- js (All js files)
- static
- index.html (my index.html)
- WEB-INF
My index.html page:
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta charset="utf-8" />
<title>My First Application</title>
<meta name="description" content="overview & stats" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0" />
<!-- bootstrap & fontawesome -->
<link rel="stylesheet" href="/resources/css/bootstrap.min.css" />
<link rel="stylesheet" href="/resources/font-awesome/4.5.0/css/font-awesome.min.css" />
.........
In the "href" I tried changing the directory path multiple times, the page is loading but just a bunch of texts (No css, image, etc)
Do I also need to update my servlet-context.xml or web.xml?
EDIT:
I checked servlet-context.xml and the mapping already exists for resoucres:
<mvc:resources mapping="/static/**" location="/static/" />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
I even added:
<resources mapping="/resources/css" location="/resources/css" />
<resources mapping="/resources/fonts" location="/resources/fonts" />
<resources mapping="/resources/images" location="/resources/images" />
but still won't work.
EDIT 2:
When I go to chrome - inspect - console. This is the log:
springmvc:13 GET http://localhost:8080/$%7BpageContext.request.contextPath%7D/resources/font-awesome/4.5.0/css/font-awesome.min.css
springmvc:21 GET http://localhost:8080/$%7BpageContext.request.contextPath%7D/resources/css/ace.min.css
springmvc:18 GET http://localhost:8080/$%7BpageContext.request.contextPath%7D/resources/css/fonts.googleapis.com.css
springmvc:26 GET http://localhost:8080/$%7BpageContext.request.contextPath%7D/resources/css/ace-skins.min.css
springmvc:27 GET http://localhost:8080/$%7BpageContext.request.contextPath%7D/resources/css/ace-rtl.min.css
springmvc:36 GET http://localhost:8080/$%7BpageContext.request.contextPath%7D/resources/js/ace-extra.min.js
springmvc:2149 GET http://localhost:8080/$%7BpageContext.request.contextPath%7D/resources/js/jquery-2.1.4.min.js
springmvc:2159 GET http://localhost:8080/$%7BpageContext.request.contextPath%7D/resources/js/bootstrap.min.js
springmvc:2166 GET http://localhost:8080/$%7BpageContext.request.contextPath%7D/resources/js/jquery-ui.custom.min.js
springmvc:2167 GET http://localhost:8080/$%7BpageContext.request.contextPath%7D/resources/js/jquery.ui.touch-punch.min.js
springmvc:2168 GET http://localhost:8080/$%7BpageContext.request.contextPath%7D/resources/js/jquery.easypiechart.min.js
springmvc:2169 GET http://localhost:8080/$%7BpageContext.request.contextPath%7D/resources/js/jquery.sparkline.index.min.js
springmvc:2170 GET http://localhost:8080/$%7BpageContext.request.contextPath%7D/resources/js/jquery.flot.min.js
springmvc:2171 GET http://localhost:8080/$%7BpageContext.request.contextPath%7D/resources/js/jquery.flot.pie.min.js
springmvc:2172 GET http://localhost:8080/$%7BpageContext.request.contextPath%7D/resources/js/jquery.flot.resize.min.js
springmvc:12 GET http://localhost:8080/$%7BpageContext.request.contextPath%7D/resources/css/bootstrap.min.css
springmvc:18 GET http://localhost:8080/$%7BpageContext.request.contextPath%7D/resources/css/fonts.googleapis.com.css
springmvc:13 GET http://localhost:8080/$%7BpageContext.request.contextPath%7D/resources/font-awesome/4.5.0/css/font-awesome.min.css
springmvc:21 GET http://localhost:8080/$%7BpageContext.request.contextPath%7D/resources/css/ace.min.css
springmvc:26 GET http://localhost:8080/$%7BpageContext.request.contextPath%7D/resources/css/ace-skins.min.css
springmvc:27 GET http://localhost:8080/$%7BpageContext.request.contextPath%7D/resources/css/ace-rtl.min.css
springmvc:36 GET http://localhost:8080/$%7BpageContext.request.contextPath%7D/resources/js/ace-extra.min.js
springmvc:2149 GET http://localhost:8080/$%7BpageContext.request.contextPath%7D/resources/js/jquery-2.1.4.min.js
springmvc:2159 GET http://localhost:8080/$%7BpageContext.request.contextPath%7D/resources/js/bootstrap.min.js
springmvc:2166 GET http://localhost:8080/$%7BpageContext.request.contextPath%7D/resources/js/jquery-ui.custom.min.js
springmvc:2167 GET http://localhost:8080/$%7BpageContext.request.contextPath%7D/resources/js/jquery.ui.touch-punch.min.js
springmvc:2180 Uncaught ReferenceError: jQuery is not defined
at springmvc:2180
Basically, all the lines in my html that has the:
<link rel="stylesheet" href=
Throws an error.
I tried to change the "href" to:
<link rel="stylesheet" href="${pageContext.request.contextPath}/resources/css/ace-skins.min.css" />
But still the same, css, images, etc won't load.
You need to register Resource Handler in spring to serve static content you can do it by XML way as
or
<mvc:resources mapping="/resources/**" location="/resources/" />
Java config
#Configuration
#EnableWebMvc
public class MvcConfig extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry
.addResourceHandler("/resources/**")
.addResourceLocations("/resources/");
}
}
you can also add multiple resource location as
.addResourceLocations("/resources/","classpath:/other-resources/");
use commat to delimit the string and you can provide as many resource location as you want!
Enjoy coding!
Try using relative links like below. Also use Thymeleaf's th:href
<link rel="s`tylesheet" type="text/css" media="all"
href="../../../resources/css/styles.css"`
th:href="#{/resources/css/styles.css}" />
See your deployed directory structure and ensure required files are present in said folders (resources)
Remember to change the relative path ../../ to correct level.
If files not being copied to /resources folder then trying putting them in /main/src/webapp/resources

Receiving a 404 running spring boot

Hello i'm new to spring and i'm receiving a 404 error when attempting to use spring boot. When attempting to view the url in the browser i keep getting a 404 error. Please could someone assist and point me to what is wrong. I placed a debugger in the controller to print HH but i observed it never goes into the controller as it fails to print "HH" on the console.
I also noticed this from console:
:50.894 INFO 11249 --- [lication.main()] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2015-11-15 07:11:50.894 INFO 11249 --- [lication.main()] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.
Below is my controller:
#RestController
public class TestController {
#RequestMapping(value="/person")
public String intro(){
System.out.println("HH");
return "index";
}
}
pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.springExample.www</groupId>
<artifactId>Hotel-Management</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.2.7.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies>
<properties>
<java.version>1.8</java.version>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
MainApplication.java:
#SpringBootApplication
public class MainApplication {
public static void main(String[] args) {
SpringApplication.run(MainApplication.class, args);
}
}
index.html is defined in src/main/resources/templates:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initialscale=1">
<title>Bootstrap 101 Template</title>
<!-- Bootstrap -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" integrity="sha512-dTfge/zgoMYpP7QbHy4gWMEGsbsdZeCXz7irItjcC3sPUFtf0kuFbDz/ixG7ArTxmDjLXDmezHubeNikyKGVyQ==" crossorigin="anonymous">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5
elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the
page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/
3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/
1.4.2/respond.min.js"></script>
<![endif]-->
<style>
.box {
background-color:#d3d3d3
}
</style>
</head>
<body>
<h1>Hello, world!</h1>
<div class="container">
<div class="row">
<div class="col-md-6 box">Content</div>
<div class="col-md-6 box">Content</div>
</div>
</div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/
jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js" integrity="sha512-K1qjQ+NcF2TYO/eI3M6v8EiNYZfA95pQumfvcVrTHtwQVDG+aHRqLi/ETn2uB+1JqwYqVG3LIvdm9lj6imS/pQ==" crossorigin="anonymous"></script>
</body>
</html>
There a few things to look at:
Use #Controller rather than #RestController. The first is designed to handle views, the second is designed to return raw data.
Move the views to src/main/java/webapp/WEB-INF/. This is the conventional location for views, rather than /src/main/resources.
Change the return value of the intro() method from index to templates/index. The entire path to the view matters.
Add a class annotated with #Configuration that defines a ViewResolver bean that looks for .html views (see this answer).

resource in spring mvc

I know that there are other topics about adding resources(CSS, Javascript) in Spring MVC, but in my case that doesn't work. I have this error when adding: HTTP Status 404 The requested resource is not available.
mvc:resources mapping="/resources/**" location="/, classpath:/META-INF/web-resources/"
My application works properly until this point.
In my index.jsp I've got:
link type="text/css" rel="stylesheet" href="c:url value="/resources/css/test.css"
script type="text/javascript" src="c:url value="/resources/js/carousel.js"
I had a similar problem and I think I solved it by adding a default mapping in web.xml
<servlet-mapping>
<servlet-name>dispatherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
Problem solved.
In DispatcherServlet I added :
<mvc:default-servlet-handler />
<mvc:annotation-driven />
At this point 'HTTP Status 404 The requested resource is not available.' has disappeared, but my resources were not available at all. So i found another way to solve the problem, configuring the base tag like
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
<head>
<base href="<%=basePath %>">
<title>index</title>
<link href="resources/css/test.css" rel="stylesheet" type="text/css" />
</head>
...
And now it works properly.

Why isn't my GWT web application running properly?

I'm going through the book: GWT in Action. On chapter I'm working through the very first hello world application. It's all in development mode.
My issue is that the label in my .java file is not showing up when I open the URL webpage. There is nothing being displayed versus the Label("Hello World!") appearing.
EDIT: When at the displayed webpage, I pressed F12 in google chrome to see if I could find anything weird. Got the error: Failed to load resource: the server responded with a status of 404 (Not Found)
HelloWorld.gwt.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE module PUBLIC "-//Google Inc.//DTD Google Web Toolkit 2.6.0//EN" "http://google-web-toolkit.googlecode.com/svn/tags/2.6.0/distro-source/core/src/gwt-module.dtd">
<module>
<inherits name="com.google.gwt.user.User" />
<source path="client" />
<entry-point class="com.example.gwt.client.HelloWorld"></entry-point>
</module>
HelloWorld.java
package com.example.gwt.client;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
public class HelloWorld implements EntryPoint {
#Override
public void onModuleLoad() {
RootPanel.get().add(new Label("Hello World!"));
}
}
HelloWorld.html
<!doctype html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>HelloWorld</title>
<script type="text/javascript" language="javascript" src=".nocache.js"></script>
</head>
<body>
<iframe src="javascript:''" id="__gwt_historyFrame" tabIndex='-1' style="position:absolute;width:0;height:0;border:0"></iframe>
</body>
</html>
My console is displaying this after I run it as a web application:
[WARN] Server class 'org.eclipse.jetty.servlet.listener.ELContextCleaner' could not be found in the web app, but was found on the system classpath
[WARN] Adding classpath entry 'file:/C:/Users/Qs/Desktop/eclipse/plugins/com.google.gwt.eclipse.sdkbundle_2.6.0/gwt-2.6.0/gwt-dev.jar' to the web app classpath for this session
For additional info see: file:/C:/Users/Qs/Desktop/eclipse/plugins/com.google.gwt.eclipse.sdkbundle_2.6.0/gwt-2.6.0/doc/helpInfo/webAppClassPath.html
If you don't specify the rename-to in your gwt.xml as shown below then by default GWT places the generated nocache.js under war directory by the name of location of gwt.xml followed by its name as shown in below snapshot.
<module rename-to="xyz">
For more info have a look at gwt-module dtd.
Please have a look Defining a module and Renaming modules
There are two ways to solve this issue:
define rename-to in gwt.xml that is more preferable over second solution
gwt.xml
<module rename-to="hello">
html
<script type="text/javascript" language="javascript" src="hello/hello.nocache.js"></script>
use default way
html
<script type="text/javascript" language="javascript" src="com.example.gwt.HelloWorld/com.example.gwt.HelloWorld.nocache.js"></script>
Here is a snapshot to make it more clear
Change the src attribute of the script tag in HelloWorld.html to
src="com.example.gwt.client.HelloWorld/com.example.gwt.client.HelloWorld.nocache.js"
If that still doesn't work, run the GWT compiler and look at the files it generates to determine the exact name of the *.nocache.js file.

Unobtrusive way to combine and compress javascript/css for java/spring/maven applications?

I'd like to add some kind of library, or maven plugin, or 'something' to combine and compress my javascript and css source files.
However, I think this is pretty difficult to do unobtrusively with Java. The Rails people have pretty much solved this problem... it uses the unjoined/uncompressed files for development and then it compresses everything during production. It does this unobtrusively as you don't have to change your html headers or anything like that - it works for both testing and production. This is more or less what I want. Does it even exist in the Java space?
The last thing I want is to comment and uncomment lines of freemarker/html code for development and production - I want everything to be the same. Ideally, I'd want to be able to leave Tomcat running and code my javascript and css, and see my changes instantly - no delays or hickups. I also don't want to have to manually run a command to generate the new javascript every time I make a change... or even have some daemon constantly update it (because then it might not be instantaneous when I'm testing). At the same time, if I'm going to package up my war for production, I want it to use the joined and compressed files instead.
Is this even possible? If so, what tool should I be looking at? I know there are quite a few that do some of this, but they've fallen short on the "unobtrusive" aspect.
Thanks
A solution that has worked for me is using the maven-minify-plugin (groupId is com.samaxes.maven) but only when building for production. Use a build property to specify if you are in development mode or not. Link to plugin
You can then have something like this (I don't know freemarker so I am just pasting some JSP code but I am sure it can easily be converted):
<c:choose>
<c:when test="${developmentMode}">
<link rel="stylesheet" type="text/css" href="<c:url value="/css/custom1.css"/>"/>
<link rel="stylesheet" type="text/css" href="<c:url value="/css/custom2.css"/>"/>
<link rel="stylesheet" type="text/css" href="<c:url value="/css/another1.css"/>"/>
<link rel="stylesheet" type="text/css" href="<c:url value="/css/another2.css"/>"/>
<script type="text/javascript" src="<c:url value="/js/mylibrary.js"/>"></script>
<script type="text/javascript" src="<c:url value="/js/more.js"/>"></script>
<script type="text/javascript" src="<c:url value="/js/util.js"/>"></script>
<script type="text/javascript" src="<c:url value="/js/whatever.js"/>"></script>
<script type="text/javascript" src="<c:url value="/js/more.js"/>"></script>
</c:when>
<c:otherwise>
<link rel="stylesheet" type="text/css" href="<c:url value="/css/minified.css"/>"/>
<script type="text/javascript" src="<c:url value="/js/minified.js"/>"></script>
</c:otherwise>
</c:choose>
This way non-minified/combined JS/css is used while in development and the minified css only used when building for production.
EDIT: As requested here is the code to expose Spring-defined beans on the ServletContext:
<bean class="org.springframework.web.context.support.ServletContextAttributeExporter">
<property name="attributes">
<map>
<!-- Obviously this can be changed to read from properties file -->
<entry key="developmentMode" value="false" />
</map>
</property>
</bean>
Jawr is a library that provides compression and merge of css/js files. It provides a Tag for the html include statements.
This make it possible to use the same unmodified JSP Page for development (with unmodified css/js) and production (merged and minified).
wro4j seams to similar features.
Using maven-minify-pluginworked for me too.
But I manage to find an even less intrusive way to use it than using conditional tags like c:when, by combining it with the maven-war-plugin.
This code snippet can be used as it is :
First, start by minifying the CSS/JS without using suffix (meaning that the files keep their name)
<plugin>
<groupId>com.samaxes.maven</groupId>
<artifactId>minify-maven-plugin</artifactId>
<version>1.7.2</version>
<executions>
<execution>
<id>default-minify</id>
<phase>prepare-package</phase>
<configuration>
<charset>UTF-8</charset>
<skipMerge>true</skipMerge> <!-- do not create one big file -->
<nosuffix>true</nosuffix> <!-- do not use suffix like 'min' -->
<cssSourceDir>css</cssSourceDir>
<cssSourceIncludes>
<cssSourceInclude>*.css</cssSourceInclude>
</cssSourceIncludes>
<jsSourceDir>js</jsSourceDir>
<jsSourceIncludes>
<jsSourceInclude>*.js</jsSourceInclude>
</jsSourceIncludes>
</configuration>
<goals>
<goal>minify</goal>
</goals>
</execution>
</executions>
Then, when building the war file, do not overide CSS/JS files (which are already generated in the target by the minify goal)
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.4</version>
<configuration>
<!-- in order to use minify filed listed bellow -->
<warSourceExcludes>**/*.css, **/*.js</warSourceExcludes>
</configuration>
</plugin>
The built war will then contains the exact same files but compressed.
(this might not be the best way to perform minifying, but it doesn't change anything in development)
Hope this helps...

Categories

Resources