I have a problem with mappings and ModelAndView. All simply mappings like "/login" works but I have problem with:
#RestController
#RequestMapping("/note/{noteId:[\\d]+}")
public class NoteController {
#RequestMapping(method = RequestMethod.GET)
public ModelAndView note(#PathVariable String noteId, HttpSession session) {
// not important code
ModelAndView modelAndView = new ModelAndView("note");
return modelAndView;
}
}
I have an error here and path: /note/WEB-INF/views/jsp/note.jsp.
I wanted to get WEB-INF/views/jsp/note.jsp and I have similar path in other ModelAndViews (without prefix).
My configuration:
#Bean
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("WEB-INF/views/jsp/");
resolver.setSuffix(".jsp");
return resolver;
}
M. Deinum solved this problem.
Replace #RestController with #Controller
#RestController returns everything as a response body, it automatically returns your ModelAndView as JSON or XML. #Controller does proper view resolution. Also your prefix should be /WEB-INF/views/jsp/. Include the leading /.
Related
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";
}
}
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
}
}
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;
}
}
I want to create a spring app that doesn't use any XMLs at all (no web.xml no context.xml or anything). So far it seems to work quite fine, except that my view resolver has some problems and I cannot figure it out on my own.
here's my WebApplicationInitializer
public class AppConfig implements WebApplicationInitializer {
private AnnotationConfigWebApplicationContext getContext() {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.setConfigLocation("fi.cogniti.service.config");
return context;
}
#Override
public void onStartup(javax.servlet.ServletContext servletContext) throws ServletException {
WebApplicationContext context = getContext();
servletContext.addListener(new ContextLoaderListener(context));
ServletRegistration.Dynamic dispatcher = servletContext.addServlet("DispatcherServlet", new DispatcherServlet(
context));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/*");
// Enabling spring security
// servletContext.addFilter("springSecurityFilterChain", new DelegatingFilterProxy("springSecurityFilterChain"))
// .addMappingForUrlPatterns(null, false, "/*");
}
}
and my spring configuration
#Configuration
#EnableWebMvc
#ComponentScan("fi.cogniti.service")
public class SpringConfig extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/css/**").addResourceLocations("/css/");
registry.addResourceHandler("/js/**").addResourceLocations("/js/");
}
#Bean
public ViewResolver getViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setViewClass(JstlView.class);
resolver.setPrefix("/pages/");
resolver.setSuffix(".jsp");
return resolver;
}
}
and finally my controller
#Controller
#RequestMapping("/")
public class HomeController {
#RequestMapping
public String entry() {
return "index";
}
}
index.jsp is located in src/main/webapp/pages/index.jsp.
So, if in my controller I use the annotation #ResponseBody, then the controller gives me the response "index", hence I know that my configuration works at least to some extent, however, if I remove the annotation in hopes that it would return the content of index.jsp, I only get a 404 error.
Any suggestions?
Change:
dispatcher.addMapping("/*");
To something that doesn't match everything (you will get this error otherwise). For example:
dispatcher.addMapping("*.html");
In this way, http://localhost:8080/.html should show the jsp (change the #RequestMapping("/") in the controller to something more 'human')
You also should change this line including WEB-INF:
resolver.setPrefix("/WEB-INF/pages/");
I'm not sure if WebApplicationInitializer is getting executed (check this, where they are suggesting to use ServletContextInitializer but it's still creating issues).
If this is the case, you couldn't use the .addMapping("*.html"). If this is the case, you can add the following lines to SpringConfig in order to achieve the same result:
#Bean
public DispatcherServlet dispatcherServlet() {
return new DispatcherServlet();
}
#Bean
public ServletRegistrationBean dispatcherServletRegistration() {
ServletRegistrationBean registration = new ServletRegistrationBean(
dispatcherServlet(), "*.html");
registration
.setName(DispatcherServletAutoConfiguration.DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME);
return registration;
}
Currently all your jsp files are accessible by everyone, it is recommended to put them in WEB-INF instead at the top level.
Then modify your configuration for the view resolver to the following.
#Bean
public ViewResolver getViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/pages/");
resolver.setSuffix(".jsp");
return resolver;
}
You don't need to set the viewClass property as that is determined for you.
Next add the following to have the DispatcherServlet pass on requests that it cannot handle itself. This is needed due to the fact that you mapped the servlet to /.
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
With these 2 changes you have secured your jsps from being accessible by everyone and made default resources being handled again.
I would strongly suggest using Spring Boot as that would really simplify your life.
In your controller the method should look like:
#RequestMapping(method = RequestMethod.GET)
public ModelAndView entry() {
return new ModelAndView("index");
}
Say I have this:
#RequestMapping(value="/hello")
public ModelAndView hello(Model model){
System.out.println("HelloWorldAction.sayHello");
return null;
}
Is it possible to skip the value="hello" part, and just have the #RequestMapping annotation and have spring use the method name as the value, similar to this:
#RequestMapping
public ModelAndView hello(Model model){
System.out.println("HelloWorldAction.sayHello");
return null;
}
Thanks!
===================EDIT=====================
Tried this but not working:
#Controller
#RequestMapping(value="admin", method=RequestMethod.GET)
public class AdminController {
#RequestMapping
public ResponseEntity<String> hello() {
System.out.println("hellooooooo");
}
}
Try to add "/*" on the request mapping value of the class
#Controller
#RequestMapping(value="admin/*")
public class AdminController {
#RequestMapping
public ResponseEntity<String> hello() {
System.out.println("hellooooooo");
}
}
You can go the page http://localhost:8080/website/admin/hello
It should work if you move the RequestMethod on your specific method:
#Controller
#RequestMapping(value="admin")
public class AdminController {
#RequestMapping(method=RequestMethod.GET)
public ResponseEntity<String> hello() {
System.out.println("hellooooooo");
}
}
and access it through http://hostname:port/admin/hello
Have a look here: http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/mvc.html#mvc-ann-requestmapping
Good luck