SpringMVC 是 Spring 框架的一部分,用于构建 web 应用程序。它是一个 MVC (Model-View-Controller) 框架,可以帮助我们更加便捷地开发 web 应用。
确保你已经安装了以下工具:
在 IDE 中创建一个新的 Maven 项目,并选择 webapp 作为项目的类型。
<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.x.x.RELEASE</version>
</dependency>
@RestController
public class HelloController {
@RequestMapping("/controller")
@ResponseBody
public String hello() {
System.out.println("user controller");
return "{'module':'springmvc controller'}";
}
}
创建一个名为 WebConfig 的Java类并使用 @Configuration 和 @EnableWebMvc 注解:
@Configuration
@ComponentScan(basePackages = "com.example.controller")
public class WebConfig implements WebMvcConfigurer {
}
import org.springframework.web.servlet.support.AbstractDispatcherServletInitializer;
public class MyWebAppInitializer extends AbstractDispatcherServletInitializer {
@Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
@Override
protected WebApplicationContext createRootApplicationContext() {
AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
rootContext.register(RootConfig.class); // 如果你有其他的Root配置类,例如安全配置或数据源配置
return rootContext;
}
@Override
protected WebApplicationContext createServletApplicationContext() {
AnnotationConfigWebApplicationContext servletContext = new AnnotationConfigWebApplicationContext();
servletContext.register(WebConfig.class); // 前面步骤中的WebConfig类
return servletContext;
}
}
现在,当你启动你的Web应用时,MyWebAppInitializer类将被自动识别并用于配置DispatcherServlet。
在pom文件中插入如下代码:
<build>
<plugins>
<!-- Other plugins -->
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<path>/yourAppName</path> <!-- Application path -->
<port>8080</port> <!-- Port to run Tomcat -->
<contextReloadable>true</contextReloadable>
</configuration>
</plugin>
</plugins>
</build>
在Tomcat或其他web服务器中运行应用,并访问 http://localhost:8080/yourAppName/controller,得到如下显示:
{
"message": "Hello, SpringMVC test!"
}
—— 评论区 ——