基于注解的SpringMVC框架开发的步骤
1)新建项目,选择webapp模板.
2)修改目录,添加缺失的test,java,resources(两套),并修改目录属性
3)修改pom.xml文件,添加SpringMVC的依赖,添加Servlet的依赖
<dependency>
<groupId>jakarta.servlet</groupId>
<artifactId>jakarta.servlet-api</artifactId>
<version>5.0.0</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>6.0.2</version>
</dependency>
4)添加springmvc.xml配置文件,指定包扫描,添加视图解析器.
<!--添加包扫描-->
<context:component-scan base-package="com.bjpowernode.controller"></context:component-scan>
<!--添加视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!--配置前缀-->
<property name="prefix" value="/admin/"></property>
<!--配置后缀-->
<property name="suffix" value=".jsp"></property>
</bean>
5)删除web.xml文件,新建web.xml
6)在web.xml文件中注册springMVC框架(所有的web请求都是基于servlet的)
<!--注册SpringMVC框架-->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<!--
指定拦截什么样的请求
http://localhost:8080/one
http://localhost:8080/index.jsp
http://localhost:8080/demo.action
<a href="${pageContext.request.contextPath}/demo.action">访问服务器</a>
-->
<url-pattern>*.action</url-pattern>
</servlet-mapping>
7)在webapp目录下新建admin目录,在admin目录下新建main.jsp页面,删除index.jsp页面,并新建,发送请求给服务器
<%--
Created by IntelliJ IDEA.
User: 86173
Date: 2023/8/13
Time: 9:36
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<a href="${pageContext.request.contextPath}/demo.action">访问服务器</a>
</body>
</html>
8)开发控制器(Servlet),它是一个普通的类.
@Controller //交给Spring去创建对象
public class DemoAction {
/**
* 以前的Servlet的规范
* protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {}
* action中所有的功能实现都是由方法来完成的
* action方法的规范
* 1)访问权限是public
* 2)方法的返回值任意
* 3)方法名称任意
* 4)方法可以没有参数,如果有可是任意类型
* 5)要使用@RequestMapping注解来声明一个访问的路径(名称)
*
*/
//版本不同这里的注解参数不同,tomact10及以上,servlet5及以上,需要添加上.action
@RequestMapping("/demo.action")
public String demo(){
System.out.println("服务器被访问到了.......");
return "main"; //可以直接跳到/admin/main.jsp页面上
}
}
9)添加tomcat进行测试功能
4.分析web请求
web请求执行的流程
核心处理器
index.jsp<--------------->DispatcherServlet<------------------->SpringMVC的处理器是一个普通的方法
one.jsp <--------------->DispatcherServlet<------------------->SpringMVC的处理器是一个普通的方法
DispatcherServlet要在web.xml文件中注册才可用.