springmvc搭建流程
springmvc环境搭建
-
1.用idea创建web项目
-
2.导入jar包
<dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>6.1.14</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>6.0.11</version> </dependency> <dependency> <groupId>jakarta.servlet</groupId> <artifactId>jakarta.servlet-api</artifactId> <version>6.0.0</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>6.0.11</version> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.0</version> <scope>provided</scope> </dependency> </dependencies>
在传统的Java EE(现在称为Jakarta EE)中,Servlet接口位于
javax.servlet.Servlet
包下。然而,随着 Jakarta EE 9 的发布,命名空间从javax.*
迁移到了jakarta.*
,以避免与Eclipse基金会下的项目产生混淆,因为Oracle将Java EE转移给了Eclipse基金会管理,并且该基金会决定重命名API包以反映这一变化。
-
切记springmvc相关的包要与servlet包匹配,否则org.springframework.web.servlet.DispatcherServlet会报红
-
3.配置前端控制器
配置前端控制器
配置Servlet
配置拦截路径名称
-
4.配置bean配置文件
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!--开启注解扫描--> <context:component-scan base-package="com.pyb"/> <!--视图解析器对象--> <bean id="internalResourceView" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/pages/"/> <property name="suffix" value=".jsp"/> </bean> <!--开启SpringMVC注解支持--> <mvc:annotation-driven/> </beans>
-
5.创建controller类,编写控制器代码
package com.pyb.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * @version 1.0 * @Author 彭彦彬 * @Date 2025/1/9 20:04 * @注释 */ //把类交给ioc容器管理 @Controller public class UserController { //配置请求映射 @RequestMapping("/user") public String users(){ System.out.println("success"); //返回跳转页面 return "success"; } }
-
创建要跳转的页面
<%-- Created by IntelliJ IDEA. User: pyb Date: 2025/1/9 Time: 20:07 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>success</title> </head> <body> <h1>登陆成功</h1> </body> </html>
-
配置Tomcat启动服务器测试
-
向tomcat服务器发送请求
(http://localhost:8089/user)有下方提示,表示springmvc已经成功搭建