这让我发疯了。我已经做了很多Spring编码,但这是我第一次尝试用Java进行所有配置。我搜索了遍布stackoverflow和其他地方,而其他人已经看到了这个问题,他们的解决方案都没有对我有用。
以下是我的源文件:
初始化器:
public class EnhancedCandidateInfoInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
private static final Logger logger = LoggerFactory.getLogger(EnhancedCandidateInfoInitializer.class);
@Override
protected Class<?>[] getRootConfigClasses() {
logger.info("@@@@@ getRootConfigClasses called - returning null @@@@@");
return null;
}
@Override
protected Class<?>[] getServletConfigClasses() {
logger.info("@@@@@ getServletConfigClasses called returning EnhancedCandidateInfoWebConfiguration.class @@@@@");
return new Class[] { EnhancedCandidateInfoWebConfiguration.class };
}
@Override
protected String[] getServletMappings() {
logger.info("@@@@@ getServletMappings called @@@@@");
return new String[] { "/" };
}
}
WebMvcConfiguration:
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = {"com.mojorank.restapi"})
public class EnhancedCandidateInfoWebConfiguration extends WebMvcConfigurerAdapter {
private static final Logger logger = LoggerFactory.getLogger(EnhancedCandidateInfoWebConfiguration.class);
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
logger.info("#### My Configuration handler was called ####");
configurer.enable();
}
}
控制器:
@RestController
public class EnhanceCandidateInfoController {
@RequestMapping("/")
public String welcome() {//Welcome page, non-rest
return "Welcome to RestTemplate Example.";
}
@RequestMapping("/hello/{player}")
public Message message(@PathVariable String player) {//REST Endpoint.
Message msg = new Message(player, "Hello " + player);
return msg;
}
}
当我构建应用程序并将其部署到tomcat时,我得到以下异常堆栈跟踪:
引起:java.lang.IllegalArgumentException:无法注册名为'dispatcher'的servlet。如果在同一名称下注册了另一个servlet,请检查。 在org.springframework.util.Assert.notNull(Assert.java:115) 在org.springframework.web.servlet.support.AbstractDispatcherServletInitializer.registerDispatcherServlet(AbstractDispatcherServletInitializer.java:98) 在org.springframework.web.servlet.support.AbstractDispatcherServletInitializer.onStartup(AbstractDispatcherServletInitializer.java:71) 在org.springframework.web.SpringServletContainerInitializer.onStartup(SpringServletContainerInitializer.java:169) at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5274) 在org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
正如我所说,我已经搜索了stackoverflow和其他地方,并发现其他人有同样的问题,但当我尝试实施建议的修复时,我的问题仍然存在。提前感谢您的帮助。
答案 0 :(得分:-1)
将WebMvcConfiguration
方法更改为:
public class EnhancedCandidateInfoWebConfiguration extends WebMvcConfigurerAdapter {
@Override
public void configureViewResolvers(ViewResolverRegistry registry) {
InternalResourceViewResolver ivr=new InternalResourceViewResolver();
ivr.setPrefix("/WEB-INF/jsp/");
ivr.setSuffix(".jsp");
ivr.setExposeContextBeansAsAttributes(true);
registry.viewResolver(ivr);
}
}