Not getting to the index.jsp page in spring boot - java

When I go to http://localhost:8080/ for my spring boot form it just gives me a whitelabel error page. This is my Controller code
package net.codejava;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
#Controller
public class MvcController {
#RequestMapping("/")
public String home() {
System.out.println("Going home...");
return "index";
}
}
and here's my index.jsp code
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Volunteer Management Form</title>
</head>
<body>
<h1>Volunteer Management Form</h1>
</body>
</html>
I cannot work out why it won't show I do however get "Going home..." printed in the console

i think that you have problem with the view resolver add this to your application.properties:
spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp
and move your index.jsp to /WEB-INF/jsp/
the second method is to set resolver by using WebConfig class like that :
add this class to your source package :
#EnableWebMvc
#Configuration
#ComponentScan("net.codejava")
public class WebConfig implements WebMvcConfigurer {
#Bean
public ViewResolver internalResourceViewResolver() {
InternalResourceViewResolver bean = new
InternalResourceViewResolver();
bean.setViewClass(JstlView.class);
bean.setPrefix("/WEB-INF/view/");
bean.setSuffix(".jsp");
return bean;
}
}
update 16/03/2022
there is some problems with the the newer versions of Spring boot so we should add this been also like the following :
#Configuration
#EnableWebMvc
#ComponentScan
public class MvcConfig extends WebMvcConfigurerAdapter {
#Bean
WebServerFactoryCustomizer<ConfigurableServletWebServerFactory>
enableDefaultServlet() {
return (factory) -> factory.setRegisterDefaultServlet(true);
}
#Bean
public ViewResolver getViewResolver() {
InternalResourceViewResolver resolver = new
InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/view/");
resolver.setSuffix(".html");
return resolver;
}
#Override
public void
configureDefaultServletHandling(DefaultServletHandlerConfigurer
configurer) {
configurer.enable();
}
}

Not sure how did you setup JSP on spring boot because there's some specific dependencies that you need to have. Also, people nowadays use Thymeleaf or Freemarker for templating instead of JSP on spring boot. I was able to follow and run the github project from https://www.baeldung.com/spring-boot-jsp with these urls
http://localhost:8080/spring-boot-jsp/book/viewBooks
http://localhost:8080/spring-boot-jsp/book/addBook

Related

Thymeleaf doesn't see attributes

I have a controller
#Controller
public class FirstController {
#GetMapping("/hello")
public String helloPage(#RequestParam("name") String name,
Model model){
model.addAttribute("message", name);
return "first/hello";
}
}
And view hello.html
<!doctype html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<h1>Hello world!</h1>
<p th:text="${message}"></p>
</body>
</html>
I enter the required parameters: http://localhost:8080/hello?name=Tom
But all that the page displays is "Hello world!"
P.S. I'm working with spring core and therefore I had to write the configs by hand, here's what is in the configs:
#Configuration
#ComponentScan("com.nosferat.springapp")
#EnableWebMvc
public class SpringConfig implements WebMvcConfigurer {
#Bean
public ViewResolver viewResolver() {
var viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".html");
return viewResolver;
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}
Maybe it has something to do with the config
Why do you have a return "first/hello"? you should use return "hello", by the way this may be the answer to your question
i also highly suggest you to use Spring boot so your life will be easier

HTTP Status 404 – Not Found : The origin server did not find a current representation for the target resource

I am getting error while trying to access service in spring framework.
Controller class :-
package com.spring.mvc.tutorial;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
#Controller
#RequestMapping("/")
public class HelloWorldController {
#RequestMapping(method = RequestMethod.GET)
public String sayHello(ModelMap model) {
model.addAttribute("message", "Hello World from Spring 4 MVC");
return "welcome";
}
#RequestMapping(value = "/hello", method = RequestMethod.GET)
public String sayHelloAgain(ModelMap model) {
model.addAttribute("message", "Hello World Again, from Spring 4 MVC");
return "welcome";
}
}
Configuration class :-
package com.spring.mvc.tutorial;
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.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = "com.spring.mvc.tutorial")
public class HelloWorldConfiguration {
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
}
Initialization class :-
package com.spring.mvc.tutorial;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
public class HelloWorldInitializer implements WebApplicationInitializer {
#Override
public void onStartup(ServletContext container) throws ServletException {
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(HelloWorldConfiguration.class);
ctx.setServletContext(container);
ServletRegistration.Dynamic servlet = container.addServlet("dispatcher", new DispatcherServlet(ctx));
servlet.setLoadOnStartup(1);
servlet.addMapping("/");
}
}
View :-
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>HelloWorld page</title>
</head>
<body>
<h2>${message}</h2>
</body>
</html>
NOTE :-
Request : http://localhost:8080/SpringMvcHelloWorld/
This is developed in Eclipse Photon and deployed to Tomcat 8.5.
Try redirecting to the main html page in your controller class :
#RequestMapping(method = RequestMethod.GET)
public String sayHello(ModelMap model) {
model.addAttribute("message", "Hello World from Spring 4 MVC");
return "redirect:/main.html";
}
Replace main.html with the path of your home page
I have got the same problem and resolved it by checking where the attributes like #controller and #RequestMapping were binded to the mvc packages
To check whether the sources are binded:
Go to the controller page and press control and left button on #Controller together.
If source is not binded then it will appear as shown in the figure.
If the source is not binded then attach the source by clicking the attach source button and point towards the spring-webmvc-5.1.3.RELEASE-sources.
Check the other jars by following the above two steps.
I can't comment yet hence this is in form of an answer.
I had similar issue when tomcat was not initializing the web app. Can you please add as System.out.println on your initialiser to see if it is initializing the webapp in the first place.
And share your server logs on here.

Spring Boot i18n issue

I am learning spring Boot framework right now, I am trying to apply i18n concept on my simple application. But whenever I run the application, the following error returned: "No message found under code 'label.welcomeMessage' for locale 'en_US'.". I have read about this issue and tried a lot before I getting here to ask but noting have worked with me.
Here is my AppClass configuration:
package com.abed.main.configuration;
import java.util.Locale;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;
#Configuration
public class AppConfig implements WebMvcConfigurer{
#Bean
public LocaleResolver localeResolver()
{
SessionLocaleResolver slr = new SessionLocaleResolver();
slr.setDefaultLocale(Locale.US);
return slr ;
}
#Bean
public LocaleChangeInterceptor LocaleChangeInterceptor()
{
LocaleChangeInterceptor lci = new LocaleChangeInterceptor();
lci.setParamName("lang");
return lci ;
}
{
}
#Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(LocaleChangeInterceptor());
}
#Bean
public MessageSource messageSource() {
ReloadableResourceBundleMessageSource msgSrc = new ReloadableResourceBundleMessageSource();
msgSrc.setBasename("classpath:messages/ticket");
msgSrc.setDefaultEncoding("UTF-8");
return msgSrc;
}
}
Here is the welcome JSP:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix = "spring" uri="http://www.springframework.org/tags" %>
<!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><spring:message code="label.welcomePageTitle"></spring:message></title>
</head>
<body>
<h1><spring:message code="label.welcomeMessage"></spring:message></h1>
<form action="ticket" method="GET">
<spring:message code="label.ticketId"></spring:message><input type="text" name="Student_Id">
<input type="submit" value="<spring:message code="label.search"></spring:message>">
</form>
<spring:message code="label.createTicketSubmit"></spring:message>
</body>
</html>
and here is the hierarchy of my application:
Any Help Please , Thanks in advance
You need to configuration a bean named messageSource
here is the code, add it to a java code file, make sure #Configuration can be scan:
#Configuration
public class MessageSourceConfig {
#Bean(name = "messageSource")
public ResourceBundleMessageSource getMessageSource() throws Exception {
ResourceBundleMessageSource resourceBundleMessageSource = new ResourceBundleMessageSource();
resourceBundleMessageSource.setDefaultEncoding("UTF-8");
resourceBundleMessageSource.setBasenames("i18n/messages");
return resourceBundleMessageSource;
}
}
The point is : resourceBundleMessageSource.setBasenames("i18n/messages");
remember the base path is classpath, so the i18n properties resource should set in i18n/messages. In order not to crash problem, I suggest you create the properties by using IDEA.
Quote Spring official doc:
Strategy interface for resolving messages, with support for the parameterization and internationalization of such messages.
Spring provides two out-of-the-box implementations for production:
ResourceBundleMessageSource, built on top of the standard ResourceBundle
ReloadableResourceBundleMessageSource, being able to reload message definitions without restarting the VM.
This is the reason we need to configure a bean named messageSource.

Unable to load static file in Spring4

I am trying to create a sample Spring MVC project but static file are not getting loaded.I am getting below mentioned error.
http://localhost:8080/BPMEI/static/css/bootstrap.css Failed to load resource: the server responded with a status of 404 (Not Found)
I will be grateful if someone can help me out to fix this issue.
Project Structure
Configuration Code
package com.dgsl.bpm.configuration;
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = "com.dgsl.bpm")
public class WebConfiguration extends WebMvcConfigurerAdapter {
#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("/static/**").addResourceLocations("/");
}
}
Initializer code
package com.dgsl.bpm.configuration;
public class WebInitializer implements WebApplicationInitializer {
public void onStartup(ServletContext container) throws ServletException {
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(WebConfiguration.class);
ctx.setServletContext(container);
ServletRegistration.Dynamic servlet = container.addServlet("dispatcher", new DispatcherServlet(ctx));
servlet.addMapping("/");
servlet.setLoadOnStartup(1);
}
}
JSP Code
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Student Enrollment Form</title>
<link href="<c:url value='/static/css/bootstrap.css' />" rel="stylesheet"></link>
</head>
<body>
To F2:if you let it download itself instead of me downloading css files and telling Spring where they are,you must let the js files or somethings publish to the web which is not controlled by yourself.The building-owner’s purpose is how to load the static file in a Spring MVC project.I think the problem is on the code of addResourceLocations,it should be addResourceLocations ("classpath:/static/");
may be you made a wrong mapping.
registry.addResourceHandler("/static/**").addResourceLocations("/static/");
this code should works, i tested it on my local machine.
addResourceLocations("/static/") the last slash is mandatory
in sping-core-4.2.5-release.jar StringUtils.java has the following code
public static String applyRelativePath(String path, String relativePath) {
int separatorIndex = path.lastIndexOf(FOLDER_SEPARATOR);
if (separatorIndex != -1) {
String newPath = path.substring(0, separatorIndex);
if (!relativePath.startsWith(FOLDER_SEPARATOR)) {
newPath += FOLDER_SEPARATOR;
}
return newPath + relativePath;
}
else {
return relativePath;
}
}
if not end with a slash, this method will return relativePath
FYI, when i view your attached picture, i found "bootstrap.min.css" in your project. don't forget to use right file name. i wish my suggestion can help you
change addResourceHandlers like
#Override
public void addResourceHandlers(final ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**").addResourceLocations("/");
}
and also change css file name 'bootstrap.min.css'
Change your addResourceHandlers definition like below and try:-
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
}
Please use the context path in your url:
<c:url value='${pageContext.request.contextPath}/static/css/bootstrap.css' />
This will give you the url value:
BPMEI/static/css/bootstrap.css
Let me know if that works.

Thymeleaf and Spring Boot not reading properties from localization files - Question marks appear instead of the localized string

When attempting to localize a static string the message is displayed surrounded with questionmarks "??"
e.g. ??ticket.type_en_US??
<p th:text="#{ticket.type}">Blah</p>
I am using SpringBoot 1.3.6.RELEASE
Thymeleaf: 3.0.0.RELEASE
thymeleaf-spring4 artifact
I have configured the basename of my messages in application.properties
and the contents of that messages.properties and messages_en_US.properties is:
ticket.type=BUGS!!!!
Config:
spring.messages.basename=messages
Output on startup:
2016-07-19 08:38:28.673 DEBUG 5175 --- [ main]
ationConfigEmbeddedWebApplicationContext : Using MessageSource
[org.springframework.context.support.ResourceBundleMessageSource:
basenames=[messages]]
I also tried programatically using the MessageResource in the code below. I placed the messages.properties file in the same folder as the application.properties file. src/main/resources/
#Configuration
#ComponentScan("controller")
public class WebConfig extends WebMvcConfigurerAdapter implements ApplicationContextAware{
private ApplicationContext applicationContext;
#Autowired
private MessageSource messageSource;
public void setApplicationContext(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
#Bean
public ViewResolver viewResolver() {
ThymeleafViewResolver resolver = new ThymeleafViewResolver();
resolver.setTemplateEngine(templateEngine());
resolver.setCharacterEncoding("UTF-8");
return resolver;
}
#Bean
public TemplateEngine templateEngine() {
SpringTemplateEngine engine = new SpringTemplateEngine();
engine.setTemplateResolver(templateResolver());
engine.setMessageSource(messageSource);
return engine;
}
#Bean
public ITemplateResolver templateResolver() {
SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
resolver.setApplicationContext(applicationContext);
resolver.setPrefix("/WEB-INF/templates/");
resolver.setTemplateMode(TemplateMode.HTML);
return resolver;
}
}
For completeness here is my application config (like others I had to exluse the Thymeleaf class):
#SpringBootApplication(exclude={org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration.class})
public class Application {
public static void main(String[] args) {
ApplicationContext ctx = SpringApplication.run(Application.class, args);
}
}
I have also verified that the message bundles are being loaded by pring out the contents on one of my REST end-point calls:
#Autowired
private MessageSource messageSource;
#GET
#Produces("application/json")
public List<MyData> getData() {
System.out.println("HERE 1 in Conversions");
System.out.println(messageSource.getMessage("ticket.type", null, Locale.US));
return getTheData();
}
This prints out the following so I know spring-boot is loading the resource bundles, but Thymeleaf is not picking them up somehow:
BUGS!!!!
Here is my full HTML page, perhaps there is an issue with it:
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Kitchen Sink</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<link href="http://cdn.jsdelivr.net/webjars/bootstrap/3.3.4/css/bootstrap.min.css"
th:href="#{/webjars/bootstrap/3.3.4/css/bootstrap.min.css}"
rel="stylesheet" media="screen" />
<script src="http://cdn.jsdelivr.net/webjars/jquery/2.1.4/jquery.min.js"
th:src="#{/webjars/jquery/2.1.4/jquery.min.js}"></script>
<link href="../static/css/mike.css"
th:href="#{css/mike.css}" rel="stylesheet" media="screen"/>
</head>
<body>
<div class="container">
<div class="jumbotron">
<h1>Hello</h1>
<h2>Welcome to the Kitchen Sink!</h2>
<p th:text="#{ticket.type}">Blah</p>
<p th:text="#{test.type}">dssfgf</p>
</div>
</body>
</html>
ok, so I figured it out. Thanks #M.Deinum for poitning out that I should just let spring-boot and Thymeleaf do what they are supposed to do.
I had to set the:
engine.setMessageSource(messageSource);
and also add the:
#Bean
to the 2 other functions. This allowed the MessageSource to be passed into the engine and resolve the properties correctly.
I will update the question above with the correct source so people can use it for referene
Please add
#EnableAutoConfiguration
in your Spring boot startup its look like
#EnableAutoConfiguration
#SpringBootApplication
public class Application {
public static void main(String[] args) {
ApplicationContext ctx = SpringApplication.run(Application.class, args);
}
}
I had a similar problem, and code from your post didn't work for me. The source of my issue was, that I didn't have message.proprerties (without any language).
I had:
messages_en.properties
messages_de.properties
messages_es.properties
but it didn't work.
It started working only when I added
messages.properties

Categories