第一步,前端控制器DispatcherServlet的配置
在web.xml中配置前端控制器:
<servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!--contextConfigLocation配置springmvc加载的配置文件(配置处理器映射器,适配器,处理器等) 如果不配置会默认访问web-inf 下的servlet名-servlet.xml --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <!-- 拦截请求的地址.do 以.do结尾的请求的链接会被访问 /:静态的也调用dispatcherServlet进行解析,可实现resultful风格的url, /*:这种不对不能根据jsp转到handle会报错 -->
第二步,配置处理器映射器HandleMapping
在springmvc.xml中添加约束以及配置处理器适配器、处理器、处理器映射器、视图解析器:
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" 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/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <mvc:annotation-driven/> <!-- 配置处理器Handle,映射“/firstController”请求 --> <bean name="/myController.do" class="com.ssm.controller.MyController" /> <!-- 处理器映射器,将处理器Handle的name作为url进行查找 --> <bean class= "org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping" /> <!-- 处理器适配器,配置对处理器中handleRequest()方法的调用 所有的处理器适配器都实现HandlerAdapter接口--> <bean class= "org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter" /> <!-- 视图解析器 解析jsp--> <bean class= "org.springframework.web.servlet.view.InternalResourceViewResolver"> </bean></beans>
编写处理器
package com.ssm.controller;/** * */import org.springframework.web.servlet.ModelAndView;import org.springframework.web.servlet.mvc.Controller;import javax.servlet.*;public class MyController implements Controller { @Override public ModelAndView handleRequest(javax.servlet.http.HttpServletRequest httpServletRequest, javax.servlet.http.HttpServletResponse httpServletResponse) throws Exception { ModelAndView modelAndView=new ModelAndView(); //相当于request.setAttribute()方法。 modelAndView.addObject("hayabusa","隼龙"); modelAndView.setViewName("index.jsp"); System.out.println("jdsjad"); return modelAndView; }}
编写视图
<%-- Created by IntelliJ IDEA. User: Hayabusa Date: 2019/8/13 Time: 23:37 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> 服务端的信息为:${hayabusa} </body> </html>