maven依赖(javax.servlet-api版本与spring-webmvc班恩要匹配不然会报java.lang.NoSuchMethodError: javax.servlet.http.HttpServletRespons······):
<dependencies><dependency><groupId>javax.servlet</groupId><artifactId>javax.servlet-api</artifactId><version>3.1.0</version><scope>provided</scope></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>5.2.10.RELEASE</version></dependency></dependencies><properties><maven.compiler.source>8</maven.compiler.source><maven.compiler.target>8</maven.compiler.target><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties>
<!-- tomcat插件--><build><plugins><plugin><groupId>org.apache.tomcat.maven</groupId><artifactId>tomcat7-maven-plugin</artifactId><version>2.1</version><configuration><port>8080</port><path>/</path><uriEncoding>UTF-8</uriEncoding></configuration></plugin></plugins></build>
controller类(访问路径:localhost:8080/user/save):
@RestController
@RequestMapping("/user")
public class userController {@RequestMapping(value = "/save",method = RequestMethod.GET)public String save(){return "这是usersave";}
}
spring配置类:
@Configuration //定义为配置类
@ComponentScan("com.dt")//包扫描
@EnableWebMvc//开启SpringMvc的辅助功能
public class SpringConfig {}
servlet类:
public class ServletContainerInitConfig extends AbstractDispatcherServletInitializer {@Overrideprotected WebApplicationContext createServletApplicationContext() {AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext();applicationContext.register(spring配置类.class);return applicationContext;}@Overrideprotected String[] getServletMappings() {return new String[]{"/"};}@Overrideprotected WebApplicationContext createRootApplicationContext() {return null;}//设置参数编码为UTF-8@Overrideprotected Filter[] getServletFilters() {CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();characterEncodingFilter.setEncoding("UTF-8");return new Filter[]{characterEncodingFilter};}
}
注意:要添加webapp文件夹否则Tomcat插件会启动异常
Tomcat插件启动: