[英]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). 编辑:我意识到我在ComponentScan
犯了一个错误,因为很多评论者指出,我对其进行了更改,但仍然无法正常工作(仍然是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. 控制器永远不会被调用,最终我会收到404错误。
Can you tell the name of the package to which 'AuthorController' belongs ? 您能告诉'AuthorController'所属的软件包的名称吗? I think issue is with @ComponentScan(basePackages = "src")
. 我认为问题出在@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. 以上所有都是ComponentScan批注的有效条目。
The basePackages
property of @ComponentScan
annotation doesn't represent the folder where your java code is. @ComponentScan
批注的basePackages
属性不表示Java代码所在的文件夹。 It represents the root package of java classes where Spring should scan for Spring beans. 它代表Spring应该在其中扫描Spring Bean的Java类的根包。
So, if you have your controllers in com.myapp.web.controllers
then configure it as follows: 因此,如果您的控制器位于com.myapp.web.controllers
中, com.myapp.web.controllers
如下所示进行配置:
@ComponentScan(basePackages = "com.myapp.web.controllers")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.