Spring Boot cannot find controller's mapping - java

DataController
package go.controller;
#Controller
public class DataController {
#RequestMapping(value = "/", method = RequestMethod.GET)
public String start(){
return "index";
}
WebMvcConfig
package go.config;
public class WebMvcConfig extends WebMvcConfigurerAdapter {
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer){
configurer.enable();
}
#Bean
public InternalResourceViewResolver viewResolver(){
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("WEB-INF/pages");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
}
StaticResourceConfiguration
package go.config;
public class StaticResourceConfiguration extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**").addResourceLocations("/**");
}
}
And I have index.jsp in src/main/webapp/WEB-INF/pages/
Why Spring Boot shows 404 Not found?

Related

No mapping for GET /js/home.js

I have the same problem as mentioned in
no mapping for GET
but didn't work for me.
this is the structure :
resource structure in my project
and this is my config class :
#Configuration
#EnableWebMvc
public class MvcConfig implements WebMvcConfigurer {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry
.addResourceHandler("/resources/**")
.addResourceLocations("/resources/");
}
}
and this is my controller:
#RequestMapping("/")
public ModelAndView getHomepage() {
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("home.html");
return modelAndView;
}
and I have this in my html file:
<link rel="stylesheet" href="/css/home.css" />
but still get the error:
No mapping for GET /css/home.css
No mapping for GET /js/home.js
would be appreciated for any suggestions
thank you
this is youre config
#Configuration
#EnableWebMvc
#ComponentScan("directory with youre getHomepage() controller ")
public class MvcConfig implements WebMvcConfigurer {
#Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver resolver =
new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/"); //youre directory with home.jsp
resolver.setSuffix(".jsp");
return resolver;
}
}
this is youre controller
#Controller
#RequestMapping({"/"})
public class HomeController {
#RequestMapping(method=GET)
public String home() {
return "home";
}
}

Error : No mapping found for HTTP request with URI spring mvc without xml

Getting this error while returning Html page in response from controller
org.springframework.web.servlet.PageNotFound noHandlerFound
WARNING: No mapping found for HTTP request with URI [/SpringMVCDemo/WEB-INF/response.html] in DispatcherServlet with name 'dispatcher'
where to put response.html?
Here is my code
Controller class
-----------------
#Controller
public class LoginController {
#RequestMapping("/login")
public ModelAndView login(#RequestParam(name = "username") String username,
#RequestParam(name = "password") String password){
String str = "Welcome " + username;
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("response");
modelAndView.addObject("response",str);
return modelAndView;
}
}
Config file
------------
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = "com.skuba.*")
public class MvcConfig extends WebMvcConfigurerAdapter{
#Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/");
viewResolver.setSuffix(".html");
return viewResolver;
}
}
This is dispatcher controller
------------------------------
public class FrontController extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] {MvcConfig.class};
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class[0];
}
#Override
protected String[] getServletMappings() {
return new String[] {"/"};
}
}
Assuming the view files are in the right directory(i.e., "/WEB-INF/") try adding the following to the MvcConfig class.
// Use the DefaultServletHandlerConfigurer
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}

NPE Spring Webflow with Apache Tiles 3

I have a spring project with MVC and Webflow.
I'm getting a NPE when trying to render a tiles definition specified as a view of a view-state in a webflow.
My WebflowConfig :
#Configuration
public class WebFlowConfig extends AbstractFlowConfiguration {
#Autowired
private List<ViewResolver> viewResolvers;
#Bean
public FlowExecutor flowExecutor() {
return getFlowExecutorBuilder(flowRegistry())
.addFlowExecutionListener(new SecurityFlowExecutionListener(), "*")
.build();
}
#Bean
public FlowDefinitionRegistry flowRegistry() {
return getFlowDefinitionRegistryBuilder(flowBuilderServices())
.setBasePath("/WEB-INF/flows")
.addFlowLocationPattern("/*.xml").build();
}
#Bean
public FlowBuilderServices flowBuilderServices() {
return getFlowBuilderServicesBuilder()
.setViewFactoryCreator(mvcViewFactoryCreator())
.setDevelopmentMode(true)
.build();
}
#Bean
public MvcViewFactoryCreator mvcViewFactoryCreator() {
MvcViewFactoryCreator factoryCreator = new MvcViewFactoryCreator();
factoryCreator.setViewResolvers(viewResolvers);
factoryCreator.setUseSpringBeanBinding(true);
return factoryCreator;
}
#Bean
public LocalValidatorFactoryBean validator() {
return new LocalValidatorFactoryBean();
}
My WebMvcConfig:
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = "py.com.bbva.guepardo")
#Import(WebFlowConfig.class)
public class AppConfig extends WebMvcConfigurerAdapter {
#Override
public void configureViewResolvers(ViewResolverRegistry registry) {
registry.viewResolver(viewResolver());
}
#Bean
public ViewResolver viewResolver(){
TilesViewResolver viewResolver = new TilesViewResolver();
viewResolver.setOrder(2);
viewResolver.setViewClass(TilesView.class);
return viewResolver;
}
#Bean
#Autowired
public FlowHandlerMapping flowHandlerMapping(WebFlowConfig webFlowConfig) {
FlowHandlerMapping handlerMapping = new FlowHandlerMapping();
handlerMapping.setOrder(-1);
handlerMapping.setFlowRegistry(webFlowConfig.flowRegistry());
return handlerMapping;
}
#Bean
#Autowired
public FlowHandlerAdapter flowHandlerAdapter(WebFlowConfig webFlowConfig) {
FlowHandlerAdapter handlerAdapter = new FlowHandlerAdapter();
handlerAdapter.setFlowExecutor(webFlowConfig.flowExecutor());
handlerAdapter.setSaveOutputToFlashScopeOnRedirect(true);
return handlerAdapter;
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
#Bean
public TilesConfigurer tilesConfigurer() {
TilesConfigurer tilesConfigurer = new TilesConfigurer();
tilesConfigurer.setDefinitions(new String[] { "/WEB-INF/layouts/*.xml", "/WEB-INF/views/**/views.xml" });
tilesConfigurer.setCheckRefresh(true);
return tilesConfigurer;
}
The webflow that i'm trying to start has a simple view-state pointing to a tiles definition :
<view-state id="home" view="default_login" >
</view-state>
That same definition its working with a #RequestMapping restful web service in a #Controller class, so the mvc view render works, but it's not working from a webflow definition. Any ideas?
Console error log :
Caused by: org.springframework.webflow.execution.FlowExecutionException: Exception thrown in state 'home' of flow 'home'
at org.springframework.webflow.engine.impl.FlowExecutionImpl.wrap(FlowExecutionImpl.java:573)
at org.springframework.webflow.engine.impl.FlowExecutionImpl.resume(FlowExecutionImpl.java:263)
at org.springframework.webflow.executor.FlowExecutorImpl.resumeExecution(FlowExecutorImpl.java:169)
at org.springframework.webflow.mvc.servlet.FlowHandlerAdapter.handle(FlowHandlerAdapter.java:253)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
... 69 more
Caused by: java.lang.IllegalStateException: Exception occurred rendering view null
at org.springframework.webflow.mvc.view.AbstractMvcView.render(AbstractMvcView.java:200)
at org.springframework.webflow.engine.ViewState.render(ViewState.java:293)
at org.springframework.webflow.engine.ViewState.refresh(ViewState.java:242)
at org.springframework.webflow.engine.ViewState.resume(ViewState.java:220)
at org.springframework.webflow.engine.Flow.resume(Flow.java:537)
at org.springframework.webflow.engine.impl.FlowExecutionImpl.resume(FlowExecutionImpl.java:259)
... 74 more
Caused by: java.lang.NullPointerException
at org.springframework.webflow.mvc.servlet.ServletMvcView.doRender(ServletMvcView.java:55)
at org.springframework.webflow.mvc.view.AbstractMvcView.render(AbstractMvcView.java:196)
... 79 more

Spring MVC loads blank webpage, but '/' is configured to load homepage. Setup done using no xml

I'm trying to build a Spring MVC application, using no XML. To load the application I am using a tomcat server. I want the homepage "home.html" to load, when I go to http://localhost:8080/.
I have followed many other spring mvc helloworld tutorials, but I can't see what I'm doing wrong. The webpage that loads, when I run the application is completely blank. When I inspect the html, it has an empty body. Any help is much appreciated.
Initialization class
public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[] {ApplicationConfig.class};
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[]{WebMvcConfig.class};
}
#Override
protected Filter[] getServletFilters() {
CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
characterEncodingFilter.setEncoding("UTF-8");
characterEncodingFilter.setForceEncoding(true);
DelegatingFilterProxy securityFilterChain = new DelegatingFilterProxy("springSecurityFilterChain");
return new Filter[] {characterEncodingFilter, securityFilterChain};
}
#Override
protected void customizeRegistration(ServletRegistration.Dynamic registration) {
registration.setInitParameter("defaultHtmlEscape", "true");
registration.setInitParameter("spring.profiles.active", "default");
}
}
MVC configuration
#Configuration
class WebMvcConfig extends WebMvcConfigurationSupport {
private static final String MESSAGE_SOURCE = "/WEB-INF/i18n/messages";
private static final String VIEWS = "/WEB-INF/views/";
private static final String RESOURCES_LOCATION = "/resources/";
private static final String RESOURCES_HANDLER = RESOURCES_LOCATION + "**";
#Override
public RequestMappingHandlerMapping requestMappingHandlerMapping() {
RequestMappingHandlerMapping requestMappingHandlerMapping = super.requestMappingHandlerMapping();
requestMappingHandlerMapping.setUseSuffixPatternMatch(false);
requestMappingHandlerMapping.setUseTrailingSlashMatch(false);
return requestMappingHandlerMapping;
}
#Bean(name = "messageSource")
public MessageSource messageSource() {
ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
messageSource.setBasename(MESSAGE_SOURCE);
messageSource.setCacheSeconds(5);
return messageSource;
}
#Bean
public ITemplateResolver templateResolver() {
SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
resolver.setPrefix(VIEWS);
resolver.setSuffix(".html");
resolver.setTemplateMode(TemplateMode.HTML);
resolver.setCacheable(false);
return resolver;
}
#Bean
public SpringTemplateEngine templateEngine() {
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.setTemplateResolver(templateResolver());
templateEngine.addDialect(new SpringSecurityDialect()); //TODO no using Spring security
templateEngine.addDialect(new Java8TimeDialect());
return templateEngine;
}
#Bean
public ViewResolver viewResolver() {
ThymeleafViewResolver thymeleafViewResolver = new ThymeleafViewResolver();
thymeleafViewResolver.setTemplateEngine(templateEngine());
thymeleafViewResolver.setCharacterEncoding("UTF-8");
return thymeleafViewResolver;
}
#Override
public Validator getValidator() {
LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
validator.setValidationMessageSource(messageSource());
return validator;
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler(RESOURCES_HANDLER).addResourceLocations(RESOURCES_LOCATION);
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
/**
* Handles favicon.ico requests assuring no <code>404 Not Found</code> error is returned.
*/
#Controller
static class FaviconController {
#RequestMapping("favicon.ico")
String favicon() {
return "forward:/resources/images/favicon.ico";
}
}
}
Home controller
#Controller
public class HomeController {
#RequestMapping(value = "/")
public String index() {
return "home";
}
}
Here is what my views look like

Spring Boot internationalization (messages.properties)

I'm trying to simply add the version number of an application to a Thymeleaf fragment. I'm using Spring Boot 1.2.5. If I have a file named /resources/messages.properties defined like this:
application.version=1.0.0
And I have a Thymeleaf view with the following fragment:
Application Version: <span th:text="#{application.version}">
It's displaying something like ??application.version_en_US?? instead of 1.0.0. (I also have files named messages_en.properties and messages_en_US.properties in the classpath with the same contents too.) I am really not sure how to resolve this problem... I've spent hours on something which seems incredibly trivial...
Application.java
#SpringBootApplication
#ComponentScan(basePackages = {"org.application"})
#EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class, ThymeleafAutoConfiguration.class})
#PropertySources(value = {#PropertySource("classpath:website.properties")})
public class Application extends SpringBootServletInitializer {
public static void main(String[] args) throws Exception {
SpringApplication.run(Application.class, args);
}
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}
}
WebConfig.java
#EnableWebMvc
#Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
#Bean
public SpelAwareProxyProjectionFactory projectionFactory() {
return new SpelAwareProxyProjectionFactory();
}
#Bean
public SessionHandler sessionHandler() {
return new SessionHandler();
}
#Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/web/auth/login").setViewName("auth/login");
registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations(
"/resources/");
}
#Bean
public LocaleChangeInterceptor localeChangeInterceptor() {
LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
localeChangeInterceptor.setParamName("language");
return localeChangeInterceptor;
}
#Bean
public CookieLocaleResolver localeResolver() {
CookieLocaleResolver localeResolver = new CookieLocaleResolver();
localeResolver.setDefaultLocale(Locale.ENGLISH);
return localeResolver;
}
#Bean
public ResourceBundleMessageSource messageSource() {
return new ResourceBundleMessageSource();
}
#Override
public void addInterceptors(InterceptorRegistry registry) {
// Locale change interceptor
registry.addInterceptor(localeChangeInterceptor());
// Utility interceptor which helps with the "active" link styles in the navigation. --mm
registry.addInterceptor(new BaseInterceptor());
// Expire session after a period of time
registry.addInterceptor(sessionHandler());
}
}
ThymeleafConfig.java
#Configuration
public class ThymeleafConfig {
#Bean
public ServletContextTemplateResolver templateResolver() {
ServletContextTemplateResolver resolver = new ServletContextTemplateResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".html");
// must use Legacy HTML5 as the template, otherwise Handlebars will not parse!
//
// this should hopefully be fixed in Thymeleaf 3.0
resolver.setTemplateMode("LEGACYHTML5");
resolver.setCacheable(false);
return resolver;
}
public SpringTemplateEngine templateEngine() {
SpringTemplateEngine engine = new SpringTemplateEngine();
engine.setTemplateResolver(templateResolver());
// Add Spring security
Set<IDialect> dialects = new HashSet<IDialect>();
engine.setAdditionalDialects(dialects);
engine.addDialect(new SpringSecurityDialect());
return engine;
}
#Bean
public ViewResolver viewResolver() {
ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
viewResolver.setTemplateEngine(templateEngine());
viewResolver.setOrder(1);
viewResolver.setViewNames(new String[]{"*"});
viewResolver.setCache(false);
return viewResolver;
}
}
Will buy a virtual round of shots to whomever can resolve this issue...
i guess you could always add this in your templateEngine method:
engine.addMessageResolver(new StandardMessageResolver());
or engine.setMessageResolver(new StandardMessageResolver());
Also,from the design perspective,i would suggest you to try using the autoconfiguration for thymeleaf(removing the exclude),and many other stuff which spring boot provides automatically for you.

Categories

Resources