IntelliJ IDEA not detect spring configuration (with annotation) - java

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

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

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

Spring MVC 4 controllers not called

EDIT: I realized I made a mistake in my ComponentScan as a lot of commenters pointed out, I changed it but it is still not working (still 404).
I have a project and I'm using all annotations-based configuration. Here is the configuration files:
WebConfig.java
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = "src.controller")
public class WebConfig extends WebMvcConfigurerAdapter{
#Bean
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/jsp/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
}
WebInitializer.java
public class WebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return null;
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] { WebConfig.class };
}
#Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
I also have a persistence config but I don't think that's relevant to this problem. Anyways, here is my root path controller:
AuthorController.java
#Controller
#RequestMapping({"/authors", "/"})
public class AuthorController {
#Autowired
AuthorService authorservice;
#RequestMapping(method=RequestMethod.GET)
public String getAuthors(ModelMap model){
System.out.println("----------called--------------"); //not printed
List<Author> authors = authorservice.getAllAuthors();
model.addAttribute("authors", authors);
return "authors";
}
}
The controller never gets called and I end up getting a 404 error.
Can you tell the name of the package to which 'AuthorController' belongs ? I think issue is with #ComponentScan(basePackages = "src"). Here you should add package name of the controller classes.
#ComponentScan(basePackages = "com.sample.app")
#ComponentScan(basePackages = "com.sample.*")
#ComponentScan(basePackages = "com.*")
All the above are valid entries for ComponentScan annotation.
The basePackages property of #ComponentScan annotation doesn't represent the folder where your java code is. It represents the root package of java classes where Spring should scan for Spring beans.
So, if you have your controllers in com.myapp.web.controllers then configure it as follows:
#ComponentScan(basePackages = "com.myapp.web.controllers")

Fastest way to deliver jsp views without xml-conf using spring project stub from start.spring.io

I am using spring again after a longer period and happy to see that xml configurations are no longer required in every case.
I want to build a RESTful App, but I still have to deliver the frontend app. I figured the simplest way without using any additional template engines like thymeleaf would be serving a static jsp.
I'm using the project template from start.spring.io with just spring-mvc as dependency, thus i'm using spring boot as well.
I wrote a controller in order to deliver the jsp, but it seems that the mapping for the views has to be configured first.
#Controller
public class StaticPagesController {
#RequestMapping(value = "/")
public String index(){
return "index";
}
}
So i created a configuration class:
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = "de.tuberlin.sense.emp")
public class WebConfiguration {
#Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".html");
return viewResolver;
}
}
index.html is located in main/webapp/WEB-INF/views/
When i send a request to /, I get a WARN in the logs wich states No mapping found for HTTP request with URI [/WEB-INF/views/index.html] in DispatcherServlet with name 'dispatcherServlet'
What am I missing? Can I do this without any xml configuration?
Here is my main application class code:
UPDATE:
#SpringBootApplication
public class ExperimentManagementPlatformApplication {
public static void main(String[] args) {
SpringApplication.run(ExperimentManagementPlatformApplication.class, args);
}
}
Try adding a view controller:
#Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("index");
}
Reference
It seems to me that your controller is not being detected, I would suggest to check your file structure, is the StaticPagesController controller in the de.tuberlin.sense.emp package? (as stated in:)
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = "de.tuberlin.sense.emp")
public class WebConfiguration
I was able to serve the static page without needing any controller at all by just adding the html file to the static directory. Furthermore i found out that the entire webapp directory is not included when the app is deployed as jar which explains why the files in there could not be found.
The Spring documentation
Your config class should extend WebMvcConfigurerAdapter class
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = "de.tuberlin.sense.emp")
public class WebConfiguration extends WebMvcConfigurerAdapter{
#Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".html");
return viewResolver;
}
}

Spring configuration without any XMLs at all

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

Categories

Resources