1、创建Maven项目,导入web项目,添加依赖,不要忘了添加lib 2、创建完项目后在web.xml文件编写(固定代码)
<?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"> <!--配置dispatchServlet--> <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>3、在resources中创建一个名为 的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.www.controller"></context:component-scan> <!-- 视图解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver"> <!-- 前缀 --> <property name="prefix" value="/WEB-INF/jsp/" /> <!-- 后缀 --> <property name="suffix" value=".jsp" /> </bean> </beans>4、在web-WEB-INF下创建一个jsp目录 5、创建一个类,在这样的路径下面
package com.www.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; @Controller //Controller代表这个类会被Spring接管 //被注解的类中的所有的方法的返回值是String类型的,并且有具体的页面可以跳转 //就会被视图解释器解析 public class ControllerTest01 { @RequestMapping("hello") public String test(Model model){ model.addAttribute("msg","ControllerTest666"); return "test"; } @RequestMapping("spring") public String test1(Model model){ model.addAttribute("msg","真不错"); return "test"; } }6、在web-WEB-INF下创建的jsp目录下创建一个test.jsp文件
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <%--把Controller存的取出来--%> ${msg} </body> </html>7、配置Tomcat,启动,测试