实现步骤:1.新建一个web项目
2.导入相关jar包
3.编写web.xml,注册DispatcherServlet
4.编写Springmvc配置文件
5.接下来就是去创建对应的控制类,controller
6.最后完善前端视图和controller之间的对应
7.测试运行调试
首先我们要记住导入lib的问题,防止报错,还有maven中那个防止资源导出的问题
项目结构如下:
首先,编写web.xml配置DispatcherServlet:
<?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>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
然后我们配置Spring核心配置文件:springmvc-servlet.xml
<?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"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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 http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:component-scan base-package="com.kuang.controller"/>
<mvc:default-servlet-handler/> //这个意思是不加载静态资源,比如cs,js等
<mvc:annotation-driven/> //这个代替了原生的映射器和处理器
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/> //前缀
<property name="suffix" value=".jsp"/> //后缀
</bean>
</beans>
然后编写hello.jsp为了测试跳转到这里:
<%--
Created by IntelliJ IDEA.
User: 张文
Date: 2022/8/10
Time: 13:51
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>
${msg}
</body>
</html>
然后就是最后一步了,开始测试,记得使用Controller注解注册到bean中 RequestMapping是访问路径:
package com.kuang.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class HelloController {
@RequestMapping("/hello")
public String hello(Model model){
model.addAttribute("msg","你好我是。。。");
return "hello";
}
}