写点什么

15- 拦截器

  • 2022 年 5 月 06 日
  • 本文字数:1012 字

    阅读完需:约 3 分钟

</filter>


<filter-mapping>


<filter-name>encoding</filter-name>


<url-pattern>/*</url-pattern>


</filter-mapping>


</web-app>


<?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/mvc


https://www.springframework.org/schema/mvc/spring-mvc.xsd


http://www.springframework.org/schema/context


https://www.springframework.org/schema/context/spring-context.xsd">


<context:component-scan base-package="com.kuang.controller"/>


mvc:default-servlet-handler/


mvc:annotation-driven/


<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">


<property name="prefix" value="/WEB-INF/jsp/"/>


<property name="suffix" value=".jsp" />


</bean>


mvc:interceptors


mvc:interceptor


<mvc:mapping path="/**"/>


<bean class="com.kuang.config.MyIntercepetor"/>


</mvc:interceptor>


</beans>

[](()3.写 controller 类

package com.kuang.controller;


import org.springframework.web.bind.annotation.GetMapping;


import org.springframework.web.bind.annotation.RestController;


@RestController


public class TestController {


@GetMapping("/t1")


public String test(){


System.out.println("TestController");


return "ok";


}


}

[](()4.编写一个拦截器

package com.kuang.config;


import org.springframework.web.servlet.HandlerInterceptor;


import org.springframework.web.servlet.ModelAndView;


import javax.servlet.http.HttpServletRequest;


import javax.servlet.http.HttpServletResponse;


public class MyIntercepetor implements HandlerInterceptor {


public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


System.out.println("处理前");


// return false 就拦截住了 不让访问 t1 后面两个方法相当于日志


return true;//执行下一个拦截器 放行


}


}

用户头像

还未添加个人签名 2022.04.13 加入

还未添加个人简介

评论

发布
暂无评论
15-拦截器_Java_爱好编程进阶_InfoQ写作社区