No mapping for GET /js/home.js - java

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";
}
}

Related

Set up both .html and .jsp ViewResolvers in Spring 4?

If I need only .jsp as a view in my web application, then I write something like this:
#EnableWebMvc
#ComponentScan("com.test")
public class WebConfig extends WebMvcConfigurerAdapter {
#Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/pages/");
resolver.setSuffix(".jsp");
return resolver;
}
}
Is it possible to use .html as well? For instance:
#Controller
public class HelloController {
#RequestMapping(value = "/hello", method = RequestMethod.GET)
public String printHello(ModelMap model) {
model.addAttribute("message", "Hello Spring MVC Framework!");
return "hello"; // uses jsp extension
}
}
#Controller
public class HomeController {
#RequestMapping(value = "/home", method = RequestMethod.GET)
public String home() {
return "home"; // uses html extension
}
}

IntelliJ IDEA not detect spring configuration (with annotation)

I'm trying little spring project and encounter a problem if i use xml configuration file (web.xml and spring-servlet.xml) everything is fine. If i use java annotation the problem come up :(
I'm so confuse why intellij idea not showing my web views in my webapp folder.
Not show jsp file (pressed Ctrl + space)
And cannot resolve any variable name in my controller class Cannot resolve var name
### Controller CLASS ###
#Controller
public class HomeController {
#RequestMapping(value = "/", method = RequestMethod.GET)
public String home(ModelMap modelMap) {
modelMap.addAttribute("message", "Hello, from java class");
return "welcome";
}
}
Configuration Class
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = "com.toskbilisim")
public class HomeConfiguration extends WebMvcConfigurerAdapter {
#Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
#Bean
public MessageSource messageSource(){
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename("messages");
return messageSource;
}
}

How do I prevent Spring 4.0 MVC #ModelAttribute variables from appearing in URL?

I have a method that let you comment about customer and after adding a comment redirect you again to site with comments.
#RequestMapping(value="customers/details/{id}", method = RequestMethod.GET)
public String showCustomerComments(#ModelAttribute("commentContent") String commentContent, #PathVariable int id, Model model){
model.addAttribute("comment",commentRepository.getAllComments(id));
return "details";
}
#RequestMapping(value ="customers/details/{id}", method = RequestMethod.POST)
public String processAddCustomerComment(#ModelAttribute("commentContent") String commentContent, #PathVariable int id){
commentRepository.
addComment(commentContent, localDate.now().toString(), id);
return "redirect:/customers/details/{id}";
}
}
everything works fine but in the url appears model veriable:
http://localhost:8080/customers/details/62?commentContent=some_text
I already know the solution but I don't know how to implement it. The solution is to set ignoreDefaultModelOnRedirect true on ignoreDefaultModelOnRedirect. In this topic enter link description here they say to just put sth like <mvc:annotation-driven ignoreDefaultModelOnRedirect="true" /> to our xml file. But How to do this in Java Based configuration?
I have a such class:
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = "com.packt.webstore")
public class WebConfiguration extends WebMvcConfigurerAdapter {
#Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
#Bean
public CommonsMultipartResolver multipartResolver(){
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
multipartResolver.setMaxUploadSize(10240000);
return multipartResolver;
}
#Bean
public LocaleResolver localeResolver(){
SessionLocaleResolver sessionLocaleResolver = new SessionLocaleResolver();
sessionLocaleResolver.setDefaultLocale(new Locale("en"));
return sessionLocaleResolver;
}
#Bean
public LocaleChangeInterceptor localeChangeInterceptor(){
LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
localeChangeInterceptor.setParamName("lang");
return localeChangeInterceptor;
}
#Bean
public MessageSource messageSource(){
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename("messages");
return messageSource;
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**")
.addResourceLocations("resources/");
}
#Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(localeChangeInterceptor());
}
}
and I thought to add to it:
#Bean
public RequestMappingHandlerAdapter requestMappingHandlerAdapter(){
RequestMappingHandlerAdapter requestMappingHandlerAdapter = new RequestMappingHandlerAdapter();
requestMappingHandlerAdapter.ignoreDefaultModelOnRedirect(true);
return requestMappingHandlerAdapter;
}
but it dosen't work.
I could add to processAddCustomerComment mehtod:
model.asMap().clear();
return "redirect:" + news.getUrl();
but I am not happy with this solution. Because suppose that we have 20 methods like mine and I don't want to put those two lines of code to every of those 20 methods.
How do I solve the problem?
It is possible that your implementation is not working because a RequestMappingHandlerAdapter is already on the context. Adding another one doesn't change the one used de facto. This article suggests that you autowire the existing RequestMappingHandlerAdapter and set the property instead.
#EnableWebMvc
#Configuration
public class MyWebConfig {
#Autowired
private RequestMappingHandlerAdapter requestMappingHandlerAdapter;
#PostConstruct
public void init() {
requestMappingHandlerAdapter.setIgnoreDefaultModelOnRedirect(true);
}
......
}
All credits go to http://www.logicbig.com/ for the quoted code.
That being said, unless you have a specific reason for using #ModelAttribute, you should perhaps switch to #RequestParam, which is simpler, less strings attached. Here's this topic discussed at length.

Spring Boot cannot find controller's mapping

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?

Spring JavaConfig is not catching PageNotFound?

I am trying to setup a page not found catch in my Spring WebMVCConfig bit its not working..
here is my config:
#Configuration
#EnableWebMvc
#PropertySource("classpath:application.properties")
#Import(DatabaseConfig.class)
#ImportResource("/WEB-INF/spring/applicationContext.xml")
public class WebMVCConfig extends WebMvcConfigurerAdapter {
private static final String MESSAGE_SOURCE = "/WEB-INF/classes/messages";
private static final Logger logger = LoggerFactory.getLogger(WebMVCConfig.class);
#Autowired
Environment env;
#Bean
public ViewResolver resolver() {
UrlBasedViewResolver url = new UrlBasedViewResolver();
url.setPrefix("/WEB-INF/view/");
url.setViewClass(JstlView.class);
url.setSuffix(".jsp");
return url;
}
#Bean(name = "messageSource")
public MessageSource configureMessageSource() {
logger.debug("setting up message source");
ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
messageSource.setBasename(MESSAGE_SOURCE);
messageSource.setCacheSeconds(5);
messageSource.setDefaultEncoding("UTF-8");
return messageSource;
}
#Bean
public LocaleResolver localeResolver() {
SessionLocaleResolver lr = new SessionLocaleResolver();
lr.setDefaultLocale(Locale.ENGLISH);
return lr;
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
logger.debug("setting up resource handlers");
registry.addResourceHandler("/resources/").addResourceLocations("/resources/**");
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
logger.debug("configureDefaultServletHandling");
configurer.enable();
}
#Override
public void addInterceptors(final InterceptorRegistry registry) {
registry.addInterceptor(new LocaleChangeInterceptor());
}
public #Bean HandlerExceptionResolver exceptionResolver() {
Properties mappings = new Properties();
mappings.put("org.springframework.web.servlet.PageNotFound", "404");
mappings.put(DataAccessException.class.getName(), "dataAccessFailure");
mappings.put(TransactionException.class.getName(), "dataAccessFailure");
SimpleMappingExceptionResolver resolver = new SimpleMappingExceptionResolver();
resolver.setExceptionMappings(mappings);
return resolver;
}
#Bean
public DefaultAnnotationHandlerMapping mapping() {
DefaultAnnotationHandlerMapping m = new DefaultAnnotationHandlerMapping();
m.setDetectHandlersInAncestorContexts(true);
return m;
}
}
now if I put in a URL that is not mapped I would think it would goto my 404.jsp page?
The way to configure a custom error page (for 404 or any other error code) is in the web.xml...
<error-page>
<error-code>404</error-code>
<location>/my-custom-page-not-found.html</location>
</error-page>
The url can be a static page, a custom jsp or even a Spring controller.
You can use #ExceptionHandler annotated method or #ControllerAdvice class.
Several methods are described in this post of the forum.
Alternatively, you can also refer Spring Docs - Handling exceptions section.

Categories

Resources