Problems referencing resources in jsp - java

I couldn't achieve a functional reference scheme to my example application as follows. File teste.js seems not being reached by the resource declaration in jsp file. Any help could be valuable.
jsp
<%# 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 PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title> Composição </title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" charset="UTF-8" src="http://localhost:8080/compo/resources/js/teste.js"></script>
</head>
<body>
Greeting : ${greeting}
<table><tr><td id="save"> clique </td></tr></table>
<script type="text/javascript">
window.onload = function() {
document.getElementById("save").onclick = function fun() {
//alert("hello"); - working
testing("hello 2"); //not working
}
}
</script>
</body>
</html>
teste.js
function testing(message){
alert('messaged script: ' + message);
}
I am using Spring MVC and I've build the application in Eclipse, using its wizard, and for this reason it is using a "WebContent" folder structure, in spite of the fact that I have turn my project into a Maven project after creation. I think this is an important information.
UPDATE
After several tests, I concluded that the problem is in the Web-MVC configuration, because a similar project without Spring performs the access to resources perfectly.
Configuration (Spring 5.0.2):
package com.mycompany.compo;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = "com.mycompany.compo")
public class SpringConfiguration implements WebMvcConfigurer {
#Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry
.addResourceHandler("/resources/**")
.addResourceLocations("public", "classpath:/resources/")
.setCachePeriod(31556926)
;
}
}

Related

CSS File not loading on different url

I have two endpoints each of them is returning the "index.html" view.
http://localhost:8080/
this URL shows the index file and CSS is working as well. image
http://localhost:8080/product/1
this URL only shows the index file but CSS is not loading. image
MainController.java
package com.example.temporary.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
#Controller
public class MainController {
#RequestMapping("/")
public String index() {
return "index";
}
#RequestMapping("/product/1")
public String process() {
return "index";
}
}
index.html
<!DOCTYPE html>
<html lang="en">
<head xmlns:th="http://www.thymeleaf.org">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" th:href="#{css/index.css}">
<title>Document</title>
</head>
<body>
<h1>Index Page</h1>
<a th:href="#{/product/1}">Click Me!</a>
</body>
</html>
index.css
* {
box-sizing: border-box;
}
body {
background-color: black;
color: white;
}
File Structure
image
try to include css as below in html
<link rel="stylesheet" th:href="#{/css/index.css}">
instead of css/index.css it should be /css/index.css

Using HttpServletResponse object in spring MVC handler method

I am new to Spring MVC and Servlets. I am trying to run home() method in controller class SearchController but the output is only from home.jsp file. Statement:
out.println("<h1> this is my response block</h1>");
in not included in the result on browser.
Is there anything that can be done to print the out object statement in the browser with home.jsp file?
package springmvcsearch;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
#Controller
public class SearchController {
#RequestMapping("/home")
public String home(HttpServletResponse res) throws IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("<h1> this is my response block</h1>");
return "home";
}
}
This is home.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<link href="<c:url value='/resources/css/style.css' />"
rel="stylesheet">
<script src="<c:url value='/resources/js/sample.css' /> "></script>
</head>
<body>
This is home view
</body>
</html>
This is the output on the browser:
out.println() is used in jsp file. So you can edit your home.jsp as follows
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<link href="<c:url value='/resources/css/style.css' />"
rel="stylesheet">
<script src="<c:url value='/resources/js/sample.css' /> "></script>
</head>
<body>
This is home view
<%
out.println("<h1> this is my response block</h1>");
%>
</body>
</html>
If you want to add something for home.jsp via the controller class, you can change your controller class as follows.
package springmvcsearch;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
#Controller
public class SearchController {
#RequestMapping("/home")
public String home(HttpServletRequest req,HttpServletResponse res) throws IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
String message = "this is my response block";
req.setAttribute("message", message);
return "home";
}
}
Then change your jsp file as follows.
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<link href="<c:url value='/resources/css/style.css' />"
rel="stylesheet">
<script src="<c:url value='/resources/js/sample.css' /> "></script>
</head>
<body>
This is home view
<h1>${message}</h1>
</body>
</html>
For further explanation, go through this link how to message from servlet and display in jsp

org.thymeleaf.templatemode.StandardTemplateModeHandlers can't be resolved

In my Spring boot API, I need to send an email using Thymeleaf.Therefore, I chose this tutorial.However, when adding ThymeleafConfig.java, STS throws the following error.
The import org.thymeleaf.templatemode.StandardTemplateModeHandlers
cannot be resolved
As stated in this answer, I changed the dependencies as follows.But it didn't solve the problem.
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf</artifactId>
<version>3.0.11.RELEASE</version>
</dependency>
<dependency>
<groupId>nz.net.ultraq.thymeleaf</groupId>
<artifactId>thymeleaf-layout-dialect</artifactId>
</dependency>
ThymeleafConfig.java
import java.nio.charset.StandardCharsets;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
//following import is not resolved
import org.thymeleaf.templatemode.StandardTemplateModeHandlers;
import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver;
#Configuration
public class ThymeleafConfig {
#Bean
public ClassLoaderTemplateResolver htmlTemplateResolver(){
ClassLoaderTemplateResolver emailTemplateResolver = new ClassLoaderTemplateResolver();
emailTemplateResolver.setPrefix("/templates/");
emailTemplateResolver.setSuffix(".html");
emailTemplateResolver.setTemplateMode(StandardTemplateModeHandlers.HTML5.getTemplateModeName());
emailTemplateResolver.setCharacterEncoding(StandardCharsets.UTF_8.name());
return emailTemplateResolver;
}
}
Use TemplateMode instead of StandardTemplateModeHandlers
import org.thymeleaf.templatemode.TemplateMode;
#Bean
public SpringResourceTemplateResolver htmlTemplateResolver(){
SpringResourceTemplateResolver emailTemplateResolver = new SpringResourceTemplateResolver();
emailTemplateResolver.setPrefix("classpath:/templates/");
emailTemplateResolver.setSuffix(".html");
emailTemplateResolver.setTemplateMode(TemplateMode.HTML);
emailTemplateResolver.setCharacterEncoding(StandardCharsets.UTF_8.name());
return emailTemplateResolver;
}
In HTML template, use th:text
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>hello</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<p th:text="${name}">
</body>
</html>
When you are processing your template , use thymeleaf's TemplateEngine
import org.thymeleaf.TemplateEngine;
#Autowired
private TemplateEngine templateEngine;
Context context = new Context();
context.setVariables(mail.getModel());
String html = templateEngine.process("email-template", context);

HomeControllers not rendering

I'm using SpringToolSuite with Java and I'm trying to render an index.jsp page onto my localhost:8080, but my Localhost is only going to the Whitelabel error page again & again. I guess it doesn't seem to be recognizing my Homecontroller.java file. The servers are running and have been refreshed. My files are correct. I see no issues anywhere else. What could be wrong that I'm not seeing? How can I render my page?
HomeController.java :
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
#Controller
#RequestMapping("/your_server")
public class HomeController {
#RequestMapping("")
public String index(HttpSession session) {
if (session.isNew()) {
session.setAttribute("counter", 0);
}
Integer count = (Integer) session.getAttribute("counter");
count += 1;
session.setAttribute("counter", count);
return "index.jsp";
}
#RequestMapping("/counter")
public String showCounter(HttpSession session, Model model) {
if (session.isNew()) {
session.setAttribute("counter", 0);
}
model.addAttribute("counter", session.getAttribute("counter"));
return "counter.jsp";
}
#RequestMapping("/reset")
public String resetCounter(HttpSession session) {
session.invalidate();
return "forward:/";
}
}
CounterApplication.java:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class CounterApplication {
public static void main(String[] args) {
SpringApplication.run(CounterApplication.class, args);
}
}
index.jsp:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Welcome! Want to count some stuff?</title>
</head>
<body>
How many times has this page been visited?
<p>Oh, hi.</p>
</body>
</html>
<%# taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %>
<c:out value="${2+2}"/>
counter.jsp:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>How many times are we going to go through this?!</title>
</head>
<body>
<c:out value="${ counter }" />
Go back.
Reset the counter.
</body>
</html>

How to use Thymeleaf to include html file into another html file

I have been looking at all of the resources available on how to include an html file into another html file using Thymeleaf's th:insert. I am wondering if anyone could tell me what I am doing wrong as I feel like this html looks exactly like the examples I have seen.
My index.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.thymeleaf.org ">
<head>
<title>Default Page</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<div th:insert="templates/Navbar :: navbar"> </div>
</body>
</html>
My Navbar.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.thymeleaf.org ">
<head>
<meta charset="UTF-8"/>
<title>NavigationBar</title>
<link rel="stylesheet" type="text/css" media="all" href="../../css/NavBar.css" th:href="#{/css/NavBar.css}" />
</head>
<body>
<div>
<div th:fragment="navbar" class="navbar">
<div class="navbar-inner">
<a th:href="#{/}" href="/home"> Home</a>
<a th:href="#{/}" href="/help">Help</a>
</div>
</div>
</div>
</body>
</html>
Also, here is my project's resource hierarchy via screen shot
If I put the code between the into the index.html and link the css file, the navbar shows up and works. So, I am not sure why the insert is not working. Here is my configuration file which has been edited based on examples below:
#Configuration
public class WebPageControllerConfig {
private SpringTemplateEngine templateEngine;
private ServletContextTemplateResolver templateResolver;
#Value("${WebController.startHour}")
public String startHour;
#Value("${WebController.endHour}")
public String endHour;
#Value("${WebController.numOfSkus}")
public int numOfSkus;
#Value("${WebController.skusToQuery}")
public File skusToQuery;
#Bean
public ClassLoaderTemplateResolver webPageTemplateResolver(){
ClassLoaderTemplateResolver webPageTemplateResolver = new ClassLoaderTemplateResolver();
webPageTemplateResolver.setPrefix("templates/");
webPageTemplateResolver.setSuffix(".html");
webPageTemplateResolver.setTemplateMode("HTML5");
webPageTemplateResolver.setCharacterEncoding(CharEncoding.UTF_8);
webPageTemplateResolver.setOrder(1);
return webPageTemplateResolver;
}
/* Old way of trying to configure
#Bean
public MessageSource messageSource() {...}
#Bean
public ServletContextTemplateResolver setTemplateResolver(){...}
#Bean
public SpringTemplateEngine setTemplateEngine() {...}
#Bean
public ViewResolver viewResolver() {...}
End of old configuration */
public String getStartHour() {return startHour;}
public String getendHour() {return endHour;}
public Object getnumOfSkus() {return numOfSkus;}
public File getSkusToQuery(){return skusToQuery;}
}
Change to
th:insert="templates/Navbar :: navbar"
and
th:fragment="navbar"
Configuration example:
import org.apache.commons.lang3.CharEncoding;
import org.springframework.context.annotation.*;
import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver;
#Configuration
public class ThymeleafConfiguration {
#Bean
#Description("Thymeleaf template resolver serving HTML 5 emails")
public ClassLoaderTemplateResolver emailTemplateResolver() {
ClassLoaderTemplateResolver emailTemplateResolver = new ClassLoaderTemplateResolver();
emailTemplateResolver.setPrefix("root folder where all thymeleaf files/");
emailTemplateResolver.setSuffix(".html");
emailTemplateResolver.setTemplateMode("HTML5");
emailTemplateResolver.setCharacterEncoding(CharEncoding.UTF_8);
emailTemplateResolver.setOrder(1);
return emailTemplateResolver;
}
}
Try with:
th:replace="/navbar::navbar"
or
th:insert="/navbar::navbar"
It works for me. No need to specify "template/navbar".

Categories

Resources