前言
在上一章中,我们新建了web项目并且新建了servlet程序,通过Tomcat成功启动并完成访问,接下来我们在上一章的基础上引入springmvc并且完成springmvc服务的创建及访问。
一、准备
1.版本
上一章我们已经确定了大版本
2.引入库
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>6.1.6</version>
</dependency>
二、代码及配置
1.第一个SpringMVC程序
package org.example.springmvc;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import java.io.IOException;
import java.io.PrintWriter;
/**
* Create by zjg on 2024/4/25
*/
@Controller
public class SpringMvcController {
@RequestMapping("hello-springmvc")
public void hello(HttpServletRequest request, HttpServletResponse response){
String message="Hello SpringMVC!";;
// Hello
try(PrintWriter out = response.getWriter()) {
out.println("<html><body>");
out.println("<h1>" + message + "</h1>");
out.println("</body></html>");
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
2.spring配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="org.example.springmvc"></context:component-scan>
</beans>
3.web配置文件
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="https://jakarta.ee/xml/ns/jakartaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/web-app_6_0.xsd"
version="6.0">
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
4.访问
http://localhost:8080/hello-springmvc
总结
到这里我们的SpringMvc就已经成功地运行了,祝你成功。