Spring boot ModelAndView value is not displayed - java

I can't get the values added to the model in jsp dispalyed. I have tried with everything and and checked all answers on stackoverflow, but nothing helps.
To save your time, I paste a part of code:
My pom.xml :
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.2.5.RELEASE</version>
<relativePath/>
</parent>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
and my java config code is :
#SpringBootApplication
public class Application extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
and
#EnableWebMvc
#Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
#Bean
public InternalResourceViewResolver getViewResolver(){
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/jsp/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
}
my controller is :
#Controller
#RequestMapping(value = "workorder")
public class WorkOrderController {
#RequestMapping(value = "/toProviewPage", method = RequestMethod.GET)
public ModelAndView toPreview(){
WorkOrderVo workOrderVo = new WorkOrderVo();
workOrderVo.setId(1);
workOrderVo.setName("xxx");
workOrderVo.setPriority(1);
workOrderVo.setDetail("xxxx");
return new ModelAndView("workOrderPreview", "workOrderVo", workOrderVo);
}
}
my jsp file is :
<%# page language="java" contentType="text/html; charset=UTF-8" %>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html lang="en">
<div class="form-group">
<label for="detail" class="col-sm-2 control-label">Detail</label>
<div class="col-sm-10">
<textarea class="form-control" rows="5" id="detail" name="detail" value="${workOrderVo.dreadonly="true"></textarea>
</div>
</div>
but spring boot doesn't resloved is as a jsp file, and display all the html code is the Browser.
Where I write errors?

You can't run the main() method directly for the application when you are using "embedded Tomcat". If you look at your POM it is indicating that the Jasper dependency is provided meaning that it expects your artifact to be put inside a Tomcat container. Running the main() method in your application does not actually load up Jasper which is why you are not seeing the pages processed as JSP. For IntelliJ you need to set up a Maven run configuration (not an application) and use spring-boot:run which apparently sets up Tomcat for you. Here is a picture of how to set it up.
I did it with your application and it appears that the JSPs are being processed. I don't see the exact code you are referencing above in GitHub but I noticed that the preview page had a JSP tag that was processed. There was no value in it but the tag was replaced. Its not clear to me that this is documented so I got a hint from this question. If anyone finds official Spring Boot documentation that makes it clear let me know and I will update this.

I'll summarize the current two feasible solutions:
first :
modify pom dependency, change:
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
to
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
The second:
use spring-boot:run command to start application.

Related

Cannot return an HTML view in Spring MVC

It's my first attempt at using Spring and I ran into a problem. I cannot seem to return a simple HTML file as a view inside a controller. I'm trying to return the index.html file (it just has some text and a button), because it is displayed correctly when going to localhost:8080/.
The project was generated using IntelliJ, I figure I'd mention this since it handled most of the configuration.
Here's the file structure:
app:
| src
| main
| java
| com.my.testapp
| Main.java
| controllers
| TestController.java
| resources
| static
| index.html
Here are my files:
Main.java
#SpringBootApplication
public class Main
{
public static void main(String[] args)
{
SpringApplication.run(Main.class, args);
}
}
TestController.java (the first controller actually works)
#RequestMapping("/test")
#Controller
public class TestController
{
#RequestMapping(method = RequestMethod.GET, value = "/testget")
public #ResponseBody ArrayList<Test> foo()
{
ArrayList<Test> tests = new ArrayList<>();
tests.add(new Test("id1", "pass1"));
tests.add(new Test("id2", "pass2"));
return tests;
}
#RequestMapping(method = RequestMethod.GET, value = "/someview")
public String showView()
{
return "index";
}
}
And finally, the 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>com.my</groupId>
<artifactId>testapp</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>springtest</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.8.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<addResources>true</addResources>
</configuration>
</plugin>
</plugins>
</build>
</project>
I was previously using #RestController annotation and the controller would simply return the string index, but now I get a 404 page (Whitelabel Error Page). I know this is a common issue, but I haven't been able to solve it using other people's solution.
EDIT: Ok, I managed to fix part of it by removing the line #RequestMapping("/test"), but I now need to pass the view as "index.html" instead of simply "index". Is there a way to skip the .html? Currently it doesn't work without it.
EDIT #2: I finally figured out how to make the views work properly, check my answer below.
After a lot of useless Google searches, two kind Indian dudes explaining stuff on YouTube and a few white hairs I finally got the app running properly. Here's everything I found out:
File structure
The structure I posted in my question is correct, no need to change anything. The HTML views can reside under src/main/resources/static.
Returning HTML views using controllers
I removed the annotation from the Controller class and now my simplified controller looks like this:
#Controller
public class TestController
{
#RequestMapping(value = "/someview")
public String showView()
{
return "index";
}
}
You can add/map more URLs to this controller by changing the annotation to
#RequestMapping(value = {"/someview", "/someotherview", "/onelastview"}).
Now I can navigate to localhost:8080/someview and get the index.html view (without actually specifying the file extension in the controller).
Extra configuration
By default, my controller function needed to return "index.html" instead of "index". The solution for this is to add a line to application.properties. This file resides (in my case) under the resources folder.
The line is spring.mvc.view.suffix=.html. This specifies the type of the views. You can also set spring.mvc.view.prefix=/path/to/views, but I didn't know how to set it and it worked anyway (I guess that it defaults to resources/static).
This basically tells the framework to grab the views using the following path:
prefix + viewName + suffix, where viewName in my case is index (whatever String I return in my method).
Main.java required no extra configuration, just the SpringApplication.run() line.
Just try "index.html" instead of "index" in the return statement of your showView() method. Let me know if it works.
You need to define ViewResolver bean to let spring know where are your views
#Bean
public ViewResolver internalResourceViewResolver() {
InternalResourceViewResolver bean = new InternalResourceViewResolver();
bean.setViewClass(JstlView.class);
bean.setPrefix("/WEB-INF/view/");
bean.setSuffix(".html");
return bean;
}

Spring Boot controller is not returning html page

I am having some issues with a controller in spring boot. Which should return an index.html file but what it doing is, returning the string "index".
Here are the things you want to look for,
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>com.earworm</groupId>
<artifactId>earworm</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.3.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-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>
The controller named LoginController.java
package com.earwormproject.earwormcontrollers;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
#Controller
public class LoginController {
#RequestMapping(value = "/index", method = RequestMethod.GET)
#ResponseBody
public String createLoginForm(){
return "index";
}
#RequestMapping(value = "/profile", method = RequestMethod.GET)
#ResponseBody
public String addDataToLoginForm() {
return "profile";
}
}
Here is the main class,
package com.earwormproject;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class Earworm {
public static void main(String[] args){
SpringApplication.run(Earworm.class, args);
}
}
The file structure,
Earworm is the main class.So far I know controller checks for the html templates in the src/main/resources/templates, I have put the index.html in templates, did not work.
When I am going to http://localhost:8080/index it is showing me the string index instead of the index.html page. Like this,
I have gone through almost all the similar questions here in SO, tried all those but did not work in this case. Some clue will be of great help. Thank you.
Remove response body from you controller and try again please.
Set the content type in the header, delete the annotation #ResponseBody and change the "index" to "index.html"
#RequestMapping(value = "/index", method = RequestMethod.GET)
public String createLoginForm(HttpServletResponse response){
response.setHeader("Content-Type","text/html");
return "index";
}
Also the classpath of the static resources(your files from templates) must be in the next locations: /static or /public or /resources or /META-INF/resources
because only this locations the spring know to bind by default
I met the same question,but my problem is JDK9. When I try to use JDK1.8, everything become fine.
There are three steps to solve this
1. Remove #RequestBody annotation as we are returning a HTML file.
2. Add a dependency from maven repository corresponding to the tomcat server you are using.
https://mvnrepository.com/artifact/org.apache.tomcat/tomcat-jasper
3. Close all html tags. Thymleaf expects the html file to be a valid xml file.
I had this same problem. There was no way to return an html just by returning a String with the name of the html file. For me, it only worked using ModelAndView:
#RequestMapping("/")
public ModelAndView index () {
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("index");
return modelAndView;
}
Some people say that problems like this occurs because the jdk version. I use jdk14.

Java EE Web Project with Maven : 404 not found no error message

i have a huge problem when i launch a web app with maven on eclipse Neon.2 4.6.2 (for Java EE IDE).
When i use the main servlet, nothing happen other than a http 404 on my computer, without any error message. In console, eclipse return this error :
GRAVE: Servlet [AccueilServlet] in web application [/GestionTrajet]
threw load() exception java.lang.ClassNotFoundException:
presentation.AccueilServlet at
org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1892)
at
org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1735)
at
org.apache.catalina.core.DefaultInstanceManager.loadClass(DefaultInstanceManager.java:504)
at
org.apache.catalina.core.DefaultInstanceManager.loadClassMaybePrivileged(DefaultInstanceManager.java:486)
at
org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:113)
at
org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1133)
at
org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1072)
at
org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5368)
at
org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5660)
at
org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
at
org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1571)
at
org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1561)
at java.util.concurrent.FutureTask.run(Unknown Source) at
java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at
java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at
java.lang.Thread.run(Unknown Source)
In facts, i've tried several possibilites and the last one was to uninstall everything (eclipse / jdk / jre / library .. etc) and redo everything to have a clean version, but the problem didn't change, same error.
On the computer of my friend, everything is fine, he can launch the servlet (named AccueillServlet.java), and he had no 404 error. We are working with Git so i have the exact same version of the project.
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<welcome-file-list>
<welcome-file>accueil.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>AccueilServlet</servlet-name>
<servlet-class>presentation.AccueilServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>AccueilServlet</servlet-name>
<url-pattern>/accueil</url-pattern>
</servlet-mapping>
<!-- <servlet>
<servlet-name>ListeServlet</servlet-name>
<servlet-class>presentation.ListeServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ListeServlet</servlet-name>
<url-pattern>/liste</url-pattern>
</servlet-mapping> -->
</web-app>
Accueil.jsp
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Default title</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="styles/template.css" />
</head>
<style></style>
<body>
<nav class="navbar navbar-default" id="DivNavBar">
<div class="col-sm-3">
<div class="navbar-header">
<img src="http://www.sodifrance.fr/sites/default/files/images/logos/logo-sodifrance-menu-business.png" alt="Sodifrance logo" />
</div>
</div>
<div class="col-sm-6" id="DivFooter">
</div>
<div class="col-sm-3"></div>
</nav>
<div class="col-sm-3"></div>
<div class="col-sm-6">
<h2 align="center">Programme collaboratif</h2>
<h3>Merci de vous identifier</h3>
<form method="post">
Identifiant
<input id="login" type="text" name="login" /><br />
Mot-de-Passe
<input id="pwd" type="text" name="pwd" /><br /><br />
<input type="submit" value="Se Connecter" />
<br /><br />
</form>
</div>
<div class="col-sm-3"></div>
<footer class="col-sm-12"> </footer>
</body>
</html>
AccueilServlet.java
package presentation;
import java.io.IOException;
import java.net.UnknownHostException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import entite.Connexion;
import metier.ConnexionApplicationImpl;
/**
* Servlet implementation class Accueil
*/
//#WebServlet("/accueil")
public class AccueilServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public AccueilServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doWork(request, response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doWork(request, response);
}
private void doWork(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ModelBean bean = new ModelBean("", "");
String page ="/accueil.jsp";
System.out.println("passage servlet accueil");
// traitement des entrées
if (request.getParameter("login") != null && request.getParameter("pwd") != null) {
System.out.println("passage if login pwd différent null");
Connexion connex = ConnexionApplicationImpl.getInstance().returnConnexion(request.getParameter("login"), request.getParameter("pwd"));
if (connex.getLogin().equals("erreur") && connex.getNom().equals("erreur") && connex.getPwd().equals("erreur") && connex.getPrenom().equals("erreur")) {
System.out.println("passage if erreur");
request.getRequestDispatcher(page);
} else {
System.out.println("passage else login pwd OK");
bean = new ModelBean(request.getParameter("login"),request.getParameter("pwd"));
page = "liste";
System.out.println(page);
response.sendRedirect("http://localhost:8080/GestionTrajet/liste");
request.getRequestDispatcher(page);
}
// a = Integer.parseInt(request.getParameter("A"));
// b = Integer.parseInt(request.getParameter("B"));
// c = a + b;
// bean = new ModelBean(a.toString(), b.toString(), c.toString());
}
// passage à la vue
System.out.println(page);
request.setAttribute("bean", bean);
request.getRequestDispatcher(page).forward(request, response);
}
}
pom.xml
UPDATE : 23/12/2016
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>sodifrance</groupId>
<artifactId>GestionTrajet</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>GestionTrajet Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!-- Dependendance MongoDB -->
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver</artifactId>
<version>3.0.4</version>
</dependency>
<!-- Dependendance JEE -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
</dependency>
<!-- standard.jar -->
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<!-- JSTL -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- Dependendance JSF -->
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-api</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-impl</artifactId>
<version>2.2.2</version>
</dependency>
<!-- Bug JSF -->
<dependency>
<groupId>javax.enterprise</groupId>
<artifactId>cdi-api</artifactId>
<version>1.2</version>
</dependency>
<!-- Dependendance Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.3.4.RELEASE</version>
</dependency>
<!-- Dependendance fonctionnement tomcat -->
<dependency>
<groupId>commons-digester</groupId>
<artifactId>commons-digester</artifactId>
<version>2.1</version>
</dependency>
</dependencies>
<build>
<finalName>GestionTrajet</finalName>
</build>
</project>
Directory
My project Directory
I am new in Java EE techno, but from my pov, it's look like Maven is doing something wrong. I've tried with the exact same version of eclipse from my friend and it didn't work at all, doing the same error over again.
If it's a problem inside the source code, if you could just give me few indications that can help me to find the main problem. I am not sur, but i think that the problem come from eclipse, may be library or maven, but not from the code.
(Thanks in advance for help, and sorry for english mistakes)
EDIT 23/12/2016
First of all, thanks for your answer, i corrected the dependencies problems, i did not know that could be a problems :)
I found an other error when i used "Debug As : Maven Test" on my project and it's look like it can't compile because he can't find the compiler (see the error below)
Message error
I tried to edit eclipse.ini and give him the jdk location (and i might do something wrong, i just tried something), but it return the same error.

Spring boot webjars: unable to load javascript library through webjar

I have a spring boot (I use Thymeleaf for templating) project where I want to use some jQuery libraries.
Unfortunately, the webjars aren't loading at all. I have tried many configuration but all of them failed.
Here is the code snippet of my HTML page:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head lang="en">
<title>JAC</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<script src="http://cdn.jsdelivr.net/webjars/jquery/2.1.4/jquery.js"
th:src="#{/webjars/jquery/2.1.4/jquery.min.js}" type="text/javascript"></script>
<script src="http://cdn.jsdelivr.net/webjars/jquery-file-upload/9.10.1/jquery.fileupload.js" type="text/javascript"
th:src="#{/webjars/jquery-file-upload/9.10.1/jquery.fileupload.min.js}"></script>
<link href="http://cdn.jsdelivr.net/webjars/bootstrap/3.3.5/css/bootstrap.min.css"
th:href="#{/webjars/bootstrap/3.3.5/css/bootstrap.min.css}"
rel="stylesheet" media="screen" />
<link href="http://cdn.jsdelivr.net/webjars/jquery-file-upload/9.10.1/jquery.fileupload.css"
rel="stylesheet" media="screen" />
</head>
I have added them in the pom file:
<dependency>
<groupId>org.webjars.npm</groupId>
<artifactId>jquery</artifactId>
<version>2.1.4</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>bootstrap</artifactId>
<version>3.3.5</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery-file-upload</artifactId>
<version>9.10.1</version>
</dependency>
But when calling the page I got a 404 on jquery.min.js and jquery.fileupload.min.js.
GET http://localhost:8888/webjars/jquery-file-upload/9.10.1/jquery.fileupload.min.js
2015-09-21 02:02:04.059 home:9
GET http://localhost:8888/webjars/jquery/2.1.4/jquery.min.js 404 (Not Found)
You are referencing jquery library correctly. Maybe you are missing resource handler configuration.
<mvc:resources mapping="/webjars/**" location="classpath:/META-INF/resources/webjars/"/>
Or if you use JavaConfig
#Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}
Webjars documentation
If this will not work, please check if you have webjars on classpath (open your application JAR in 7Zip and check if webjars resources are inside it.)
After inspecting the webjar for jquery, I got this working by adding a "dist" subpath.
<script src="webjars/jquery/2.1.4/dist/jquery.min.js" type="text/javascript"></script>
Additional answer found on one blog:
When using Spring Framework version 4.2 or higher, it will
automatically detect the webjars-locator library on the classpath and
use it to automatically resolve the version of any WebJars assets.
In order to enable this feature, we’ll add the webjars-locator library
as a dependency of the application:
<dependency>
<groupId>org.webjars</groupId>
<artifactId>webjars-locator</artifactId>
<version>0.30</version>
</dependency>
In this case, we can reference the WebJars assets without using the
version; (...)
if you use servlet 3.x just add :
1- using java config :
#Configuration
#EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/webjars/**").addResourceLocations("/webjars/").resourceChain(false);
registry.setOrder(1);
}
}
2- or xml config :
<mvc:resources mapping="/webjars/**" location="/webjars/">
<mvc:resource-chain resource-cache="false" />
</mvc:resources>
The webjars dependencies should be available on the spring boot classpath, so you should try referencing the webjars using the src attribute like so:
<script src="webjars/jquery/2.1.4/jquery.min.js" type="text/javascript"></script>
<script src="webjars/jquery-file-upload/9.10.1/jquery.fileupload.min.js"></script>
<link href="webjars/bootstrap/3.3.5/css/bootstrap.min.css"
rel="stylesheet" media="screen" />
<link href="webjars/jquery-file-upload/9.10.1/jquery.fileupload.css"
rel="stylesheet" media="screen" />
I ended up doing a mvn clean install (from cmd prompt) to get the target cleaned and all the lib/jars populated correctly. I am using Spring boot with Intelij.
After inspecting the webjars for jquery, I got this working by adding a "THE VERSION OF JQUERY LIBRARY USED IN POM.XML FILE"
<script src = "/webjars/jquery/3.1.0/jquery.min.js"></script>
(in my case I used 3.1.0 version, used that version only that you are using).
Make sure if you have updated the version of bootstrap or jquery when you are adding the dependencies, you should update the URL's in the jsp's or html's with the correct version of bootstrap and jquery.

JSP not Evaluating with Spring MVC

I am trying to render JSP in a Spring 3.2 using annotation driven configuration, but the JSP renders as a string and is not evaluated.
I am using the maven jetty plugin to run the webapp in development. So it seems as if everything should "just work".
The dependencies I am including to use JSP are
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
The bean to configure JSP is
#Configuration
public class WebAppConfiguration {
#Bean
public InternalResourceViewResolver internalResourceViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/views/");
resolver.setSuffix(".jsp");
return resolver;
}
}
The controller is pretty straight forward
#Controller
public class RootController {
#RequestMapping(value = "/login")
public String login() {
return "login";
}
and the JSP is also pretty easy
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head></head>
<body>
<%= "Hello World" %>
${ "Hello World" }
<form name="auth" action="<c:url value='j_spring_security_check' />" method="POST">
<label>Username: <input type="text" name="j_username"></label>
<label>Password: <input type="password" name="j_password"></label>
<input type="submit" value="Submit"/>
</form>
</body>
</html>
As you can see from the image the JSP is not being evaluated. Is there anything I need to do to tell JSP to be evaluated when rendered.
Edit 1
So just for a little extra information I used the Resthub archetype resthub-mongodb-backbonejs-archetype to bootstrap this project, which uses a WebAppInitializer rather than the older web.xml, and it uses new annotation driven beans rather than the xml beans.
EDIT 2
I have been smashing my head on this for all to long so I put the project on github https://github.com/austinbv/calendar/. Since I do not know what is important and what is not.
Thanks for the help
#austinbv Please use the SPRING LINK to check the setup. (As #Rohit has pointed you above - the missing piece)
I had the same problem when using spring boot. Adding these dependencies to the project pom.xml resolved the issue:
<dependency>
<groupId>tomcat</groupId>
<artifactId>jasper-compiler</artifactId>
<version>5.5.23</version>
</dependency>
<dependency>
<groupId>tomcat</groupId>
<artifactId>jasper-runtime</artifactId>
<version>5.5.23</version>
</dependency>
<dependency>
<groupId>tomcat</groupId>
<artifactId>jasper-compiler-jdt</artifactId>
<version>5.5.23</version>
</dependency>
The above given issue fixed for me after making following change in the "web.xml"
The spring servlet needs to be the default servlet. ie mapped to / and not /*.
Ref link: https://code-examples.net/en/q/b49ce1
You need to specify the appropriate view class
public InternalResourceViewResolver internalResourceViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setViewClass(org.springframework.web.servlet.view.JstlView.class);
resolver.setPrefix("/views/");
resolver.setSuffix(".jsp");
return resolver;
}
I do not know how much actual will be my answer, but I had exactly the same issue (Spring + boot + maven + tomcat).
I solved it by removing the scope-provided from tomcat.embed dependence. So, my dependence now looks like this:
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
Because JSP does not obey MVC pattern :P

Categories