springMvc

鸢鬏 / 2023-04-29 / 原文

Spring MVC入门步骤

1.创建maven项目 选择 webapp的模板
2.完善项目的目录结构
新建 java 和resources文件夹
3.在pom.xml文件中导入springmvc依赖
4.编写核心配置文件 springmvc.xml
   配置注解扫描
5.在web.xml文件中 配置 前端控制器(DispatchServlet),
 加载springmvc.xml
6.编写页面页面(index.jsp)发送一个请求
7.在controller中写一个类 接收请求
8.配置tomcat服务器 启动项目
 
 

1.创建maven项目 选择 webapp的模板

2.完善项目的目录结构

新建 java 和resources文件夹

3.在pom.xml文件中导入springmvc的依赖

<dependencies>

 <dependency>
 <groupId>junit</groupId>
 <artifactId>junit</artifactId>
<version>4.11</version>
 <scope>test</scope>
</dependency>
    <!--引入springmvc的依赖-->
<dependency>
 <groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
 <version>5.3.4</version>
</dependency>
<!--引入 jsp的依赖-->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
 </dependency>
<!--引入servlet的依赖-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.3</version>
</dependency>

4.编写核心配置文件 springmvc.xml

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

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/context

http://www.springframework.org/schema/context/spring-context.xsd">

 <!--注解扫描-->

<context:component-scan base-package="com.ynlg"/>

</beans>

 
 

5.在web.xml文件中 配置 前端控制器(DispatchServlet)

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee

 http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"

 version="4.0">

<!--配置前端控制器-->

 <servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
 <!--加载springmvc的配置文件-->
 <init-param>
 <param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
 </init-param>
</servlet>
 <!--配置路径映射-->
 <servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
 <!--/ 表示 所有的请求-->
 <url-pattern>/</url-pattern>
</servlet-mapping>
</web-app >
 
 

6.编写页面页面(index.jsp)发送一个请求

<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<html>

<body>

<h2>Hello World!</h2>

<a href="nihao">你好</a>

</body>

</html>

 

7.在controller中写一个类 接收请求

@Controller //实例化

beanpublic class SpringNiHao {

@RequestMapping("/nihao")//请求映射
public void test(){
System.out.println("吃饭了没有");
   }
} 

8.配置tomcat 启动项目