先是项目配置:
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 这个是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-serlvet.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <!-- SpringMVC中:/和/*的区别 /:只匹配所有的请求,不会去匹配jsp /*:匹配所有的请求,包括去匹配jsp --> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
然后会去创建controller的控制器
HelloController.class
package com.dong; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.Controller; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; // 实现controller的方法第一种是在类上面添加@Controller // 实现controller的方法第二种是在继承Controller接口,并实现他的handleRequest方法 public class HelloController implements Controller { public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView modelAndView = new ModelAndView(); //业务代码 String result = "HelloSpringMVC"; modelAndView.addObject("msg",result); //视图跳转 modelAndView.setViewName("test"); return modelAndView; } }
springmvc-serlvet.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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!--springmvc核心三要素--> <!--处理器映射器--> <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"></bean> <!--处理器适配器--> <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"></bean> <!--视图解析器--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!--前缀--> <property name="prefix" value="/WEB-INF/jsp/"/> <!--后缀--> <property name="suffix" value=".jsp"/> </bean> <!--BeanNameUrlHandlerMapping:bean--> <bean id="/hello" class="com.dong.HelloController"></bean> </beans>
WEB-INF下面的jsp文件夹下的test.jsp
<%-- Created by IntelliJ IDEA. User: KobeByant Date: 2021/3/22 Time: 11:38 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>
运行结果