有类似的主题,但它们都使用xml配置文件。我写这个问题的原因是我正在使用注释。
我在运行应用时遇到问题:
这是我的代码(跳过包和导入):
1)初始化程序
public class WebInitializer implements WebApplicationInitializer{
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext ctx =
new AnnotationConfigWebApplicationContext();
ctx.register(AppConfig.class);
ctx.setServletContext(servletContext);
ServletRegistration.Dynamic servlet =
servletContext.addServlet("dispatcher", new DispatcherServlet(ctx));
servlet.addMapping("/");
servlet.setLoadOnStartup(1);
}
}
2)app config
@Configuration
@ComponentScan("ua.kiev.prog")
@EnableWebMvc
public class AppConfig {
@Bean
public EntityManager entityManager() {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("AdvJPA");
return emf.createEntityManager();
}
@Bean
public AdvDAO advDAO() {
return new AdvDAOImpl();
}
@Bean
public UrlBasedViewResolver setupViewResolver() {
UrlBasedViewResolver resolver = new UrlBasedViewResolver();
resolver.setPrefix("/WEB-INF/pages/");
resolver.setSuffix(".jsp");
resolver.setViewClass(JstlView.class);
resolver.setOrder(1);
return resolver;
}
@Bean
public CommonsMultipartResolver multipartResolver() {
return new CommonsMultipartResolver();
}
}
3)控制器
@Controller
@RequestMapping("/Advertisement")
public class MainController {
@Autowired
private AdvDAO advDAO;
@RequestMapping("/")
public ModelAndView listAdvs() {
return new ModelAndView("index", "advs", advDAO.list());
}
@RequestMapping(value = "/add_page", method = RequestMethod.POST)
public String addPage(Model model) {
return "add_page";
}
@RequestMapping(value = "/search", method = RequestMethod.POST)
public ModelAndView search(@RequestParam(value="pattern") String pattern) {
return new ModelAndView("index", "advs", advDAO.list(pattern));
}
// more code goes here
}
控制器映射到/ Advertisement,因此app应该可以在URL localhost:8080 / Advertisement /获得,但事实并非如此。当我将注释中的映射更改为“/”时,它将在localhost:8080 / Advertisement /中可用。怎么会这样? 当我将其更改回“/ Advertisement”时 - 同样的问题诅咒(错误404和异常“没有找到带HTTP的HTTP请求的映射......”)
那么,我在代码中犯了错误? 或者问题出在Eclipse / TomCat / Maven中?
来源 - https://github.com/KostyantynPanchenko/prog.kiev.ua.lesson09.adv
答案 0 :(得分:0)
您应该更改映射
@Controller
@RequestMapping("/")
public class MainController {
@Autowired
private AdvDAO advDAO;
@RequestMapping("/Advertisement")
public ModelAndView listAdvs() {
return new ModelAndView("index", "advs", advDAO.list());
}
映射器使用注释中的值来匹配请求URL的错误,并且它不能与最后一个斜杠匹配。注意,它不应该出现在上面的代码中。
答案 1 :(得分:0)
你是如何运行该应用程序的?在tomcat中,每个部署的应用程序都是从特定的上下文路径提供的。上下文路径是根据基本文件名确定的,更多的是here。
因此,如果您正在部署 Advertisement.war ,即使您将DispatcherServlet和Controller声明为/
,也会从localhost:8080 / Advertisement /提供对应用程序的所有请求。