SpringMvc (一)

本文详细介绍了如何在web.xml中配置DispatcherServlet并使用servlet-mapping指定后缀名,以及如何在Handler方法上添加@RequestMapping注解进行路由映射。通过配置servlet.xml来扫描和管理bean,并通过配置注解驱动来实现基于注解的路由和控制器功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.在 web.xml 配置一个DispacherServlet

<!-- 配置  dispatcherServlet handler  -->
    <servlet>
        <servlet-name>dispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!-- 这里用初始化参数改变了路径与命名方式
             (默认是 [servlet-name]servlet.xml 的方式
             并且文件要放在 /WEB-INF/ 下)
         -->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/classes/applicationContext.xml</param-value>
        </init-param>
        <!-- 与容器同时启动 -->
        <load-on-startup>1</load-on-startup>

    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcherServlet</servlet-name>
        <!-- 指定后缀名 -->
        <url-pattern>*.mvc</url-pattern>
    </servlet-mapping>

2.在 WEB-INF 下 创建一个 [servlet-name]servlet.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:context = "http://www.springframework.org/schema/context"
       xmlns:is = "http://www.w3.org/2001/XMLSchema-instance"
       is:schemaLocation =
            "
            http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
            http://www.springframework.org/schema/mvc
            http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd 
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context-4.2.xsd
            "
>
    <!-- scan package beans -->
    <context:component-scan base-package="com.springmvc.*">
    </context:component-scan>

    <!-- 配置 springMvc 注解驱动 -->
     <mvc:annotation-driven></mvc:annotation-driven>
</beans>

3.在 handler 方法上 添加 注解

@RequestMapping(value="/login")
    //这里的handler 可以通过 localhost:端口/上下文/login.mvc(mvc是后缀名       在 servlet-mapping 中指定 )
    public String testHandler3(){
        /*
            跳转到suc.jsp上
            默认方式:forward
        */

        //相当于 "forward:suc.jsp"
        return "suc.jsp";
        //相当于 "redirect:suc.jsp"
        //return "redirect:suc.jsp"
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值