springmvc 注解配置(方法一)
1.spring-webmvc依赖
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.0.5.RELEASE</version> </dependency>
2.新建一个webmvc配置类,实现WebMvcConfigurer
@Configuration @EnableWebMvc @ComponentScan public class WebConfig1 implements WebMvcConfigurer {
//配置视图解析器 @Bean public ViewResolver viewResolver(){ InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); viewResolver.setPrefix("/WEB-INF/jsp/"); viewResolver.setSuffix(".jsp"); return viewResolver; } }
3.新建一个webapp初始化类,实现WebApplicationInitializer
public class WebAppInit implements WebApplicationInitializer { @Override public void onStartup(javax.servlet.ServletContext servletContext) throws ServletException { // Load Spring web application configuration AnnotationConfigWebApplicationContext ac = new AnnotationConfigWebApplicationContext(); ac.register(WebConfig1.class); // ac.refresh();此处应该注释,否则报错 // Create and register the DispatcherServlet DispatcherServlet servlet = new DispatcherServlet(ac); ServletRegistration.Dynamic registration = servletContext.addServlet("app", servlet); registration.setLoadOnStartup(1); registration.addMapping("/"); } }
或者继承 AbstractAnnotationConfigDispatcherServletInitializer
public class WebAppInit extends AbstractAnnotationConfigDispatcherServletInitializer { @Override protected Class<?>[] getRootConfigClasses() { return null; } @Override protected Class<?>[] getServletConfigClasses() { return new Class<?>[]{WebConfig1.class}; } @Override protected String[] getServletMappings() { return new String[]{"/"}; } }
4.编写controller
@Controller public class HelloController { @RequestMapping("/hello") public String hello(){ return "hello"; } }
5.运行程序,输入http://localhost:8080/hello
注意:在做的过程中,踩得坑,自己装的jdk版本必须跟一下配置匹配,如果不匹配应该修改。
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>

浙公网安备 33010602011771号