SpringMVC 环境搭建以及静态资源放行

1. 导入 jar

2. 在 web.xml 中配置前端控制器 DispatcherServlet

    2.1 如果不配置<init-param>,它会找/WEB-INF/<servlet-name>-servlet.xml

<servlet>
    <servlet-name>jqk</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!-- 指定SpringMVC配置文件的位置 -->
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:springmvc.xml</param-value>
    </init-param>
    <!-- 配置优先级 -->
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>jqk</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

3. 在 src 下新建 springmvc.xml

    3.1 引入 xmlns:mvc 命名空间

    3.2  若将DispatcheServlet请求映射设置为/,则SpringMVC将捕获WEB容器的所有请求,包括静态资源的请求,SpringMvc会将它们当成一个普通的请求处理,那么将会出现因找不到对应的处理器将导致错误。配置<mvc:resoucres >可以解决这个问题,其中“/xxx/**”代表凡是以满足/xxx/...格式的请求都会在/xxx/目录下去搜寻

<?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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <!-- 扫描注解 -->
    <context:component-scan base-package="com.bjsxt.controller"></context:component-scan>
    <!-- 注解驱动(相当于扫描了下面两个类) -->
    <!-- org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping -->
    <!-- org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter -->
    <mvc:annotation-driven></mvc:annotation-driven>
    <!-- 静态资源 -->
    <mvc:resources location="/js/" mapping="/js/**"></mvc:resources>
    <mvc:resources location="/css/" mapping="/css/**"></mvc:resources>
    <mvc:resources location="/images/" mapping="/images/**"></mvc:resources>
</beans>

4. 编写控制器类

    4.1 RequestMapping是一个用来处理请求地址映射的注解,默认值赋值为value,即要拦截的请求

    4.2 return的值为要跳转的路径

@Controller
public class DemoController {
    @RequestMapping("demo")
    public String demo(){
        System.out.println("执行 demo");
    return "main.jsp";
    }
    @RequestMapping("demo2")
    public String demo2(){
        System.out.println("demo2");
        return "main1.jsp";
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值