• SpringBoot拦截器的使用


    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
    
    import com.imooc.controller.interceptor.OneInterceptor;
    import com.imooc.controller.interceptor.TwoInterceptor;
    
    @Configuration
    public class WebMvcConfigurer extends WebMvcConfigurerAdapter {
    
    	@Override
    	public void addInterceptors(InterceptorRegistry registry) {
    		/**
    		 * 拦截器按照顺序执行
    		 */
    		registry.addInterceptor(new TwoInterceptor()).addPathPatterns("/two/**");//.addPathPatterns("/one/**");
    registry.addInterceptor(new OneInterceptor()).addPathPatterns("/one/**"); super.addInterceptors(registry); } }
    package com.imooc.controller.interceptor;
    
    import java.io.IOException;
    import java.io.OutputStream;
    import java.io.UnsupportedEncodingException;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.springframework.web.servlet.HandlerInterceptor;
    import org.springframework.web.servlet.ModelAndView;
    
    import com.imooc.pojo.IMoocJSONResult;
    import com.imooc.utils.JsonUtils;
    
    public class OneInterceptor implements HandlerInterceptor  {
    
    	/**
    	 * 在请求处理之前进行调用(Controller方法调用之前)
    	 */
    	@Override
    	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, 
    			Object object) throws Exception {
    		
    		System.out.println("被one拦截,放行...");
    		return true;
    		
    		/*if (true) {
    			returnErrorResponse(response, IMoocJSONResult.errorMsg("被one拦截..."));
    		}
    		
    		return false;*/
    	}
    	
    	/**
    	 * 请求处理之后进行调用,但是在视图被渲染之前(Controller方法调用之后)
    	 */
    	@Override
    	public void postHandle(HttpServletRequest request, HttpServletResponse response, 
    			Object object, ModelAndView mv)
    			throws Exception {
    		// TODO Auto-generated method stub
    		
    	}
    	
    	/**
    	 * 在整个请求结束之后被调用,也就是在DispatcherServlet 渲染了对应的视图之后执行
    	 * (主要是用于进行资源清理工作)
    	 */
    	@Override
    	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, 
    			Object object, Exception ex)
    			throws Exception {
    		// TODO Auto-generated method stub
    		
    	}
    	
    	public void returnErrorResponse(HttpServletResponse response, IMoocJSONResult result) 
    			throws IOException, UnsupportedEncodingException {
    		OutputStream out=null;
    		try{
    		    response.setCharacterEncoding("utf-8");
    		    response.setContentType("text/json");
    		    out = response.getOutputStream();
    		    out.write(JsonUtils.objectToJson(result).getBytes("utf-8"));
    		    out.flush();
    		} finally{
    		    if(out!=null){
    		        out.close();
    		    }
    		}
    	}
    }
    

      

    package com.imooc.controller.interceptor;
    
    import java.util.ArrayList;
    import java.util.Date;
    import java.util.List;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.ModelMap;
    import org.springframework.web.bind.annotation.PostMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    import com.imooc.pojo.User;
    
    @Controller
    @RequestMapping("one")
    public class OneController {
    
    	@RequestMapping("/index")
        public String index(ModelMap map) {
            map.addAttribute("name", "imooc22");
            return "thymeleaf/index";
        }
    	
    	@RequestMapping("center")
        public String center() {
            return "thymeleaf/center/center";
        }
    
    	@RequestMapping("test")
        public String test(ModelMap map) {
    		
    		User user = new User();
    		user.setAge(18);
    		user.setName("manager");
    		user.setPassword("123456");
    		user.setBirthday(new Date());
    		
    		map.addAttribute("user", user);
    		
    		
    		User u1 = new User();
    		u1.setAge(19);
    		u1.setName("imooc");
    		u1.setPassword("123456");
    		u1.setBirthday(new Date());
    		
    		User u2 = new User();
    		u2.setAge(17);
    		u2.setName("LeeCX");
    		u2.setPassword("123456");
    		u2.setBirthday(new Date());
    		
    		List<User> userList = new ArrayList<>();
    		userList.add(user);
    		userList.add(u1);
    		userList.add(u2);
    		
    		map.addAttribute("userList", userList);
    		
            return "thymeleaf/test";
        }
    	
    	@PostMapping("postform")
        public String postform(User user) {
    		System.out.println(user.getName());
            return "redirect:/th/test";
        }
    }
    

      

    package com.imooc.controller.interceptor;
    
    import java.io.IOException;
    import java.io.OutputStream;
    import java.io.UnsupportedEncodingException;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.web.servlet.HandlerInterceptor;
    import org.springframework.web.servlet.ModelAndView;
    
    import com.imooc.pojo.IMoocJSONResult;
    import com.imooc.utils.JsonUtils;
    
    public class TwoInterceptor implements HandlerInterceptor  {
    
    	final static Logger log = LoggerFactory.getLogger(TwoInterceptor.class);
    	
    	/**
    	 * 在请求处理之前进行调用(Controller方法调用之前)
    	 */
    	@Override
    	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception {
    		
    		if (true) {
    			returnErrorResponse(response, IMoocJSONResult.errorMsg("被two拦截..."));
    		}
    		
    		System.out.println("被two拦截...");
    		
    		return false;
    	}
    	
    	/**
    	 * 请求处理之后进行调用,但是在视图被渲染之前(Controller方法调用之后)
    	 */
    	@Override
    	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object object, ModelAndView mv)
    			throws Exception {
    		// TODO Auto-generated method stub
    		
    	}
    	
    	/**
    	 * 在整个请求结束之后被调用,也就是在DispatcherServlet 渲染了对应的视图之后执行(主要是用于进行资源清理工作)
    	 */
    	@Override
    	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object object, Exception ex)
    			throws Exception {
    		// TODO Auto-generated method stub
    		
    	}
    	
    	public void returnErrorResponse(HttpServletResponse response, IMoocJSONResult result) throws IOException, UnsupportedEncodingException {
    		OutputStream out=null;
    		try{
    		    response.setCharacterEncoding("utf-8");
    		    response.setContentType("text/json");
    		    out = response.getOutputStream();
    		    out.write(JsonUtils.objectToJson(result).getBytes("utf-8"));
    		    out.flush();
    		} finally{
    		    if(out!=null){
    		        out.close();
    		    }
    		}
    	}
    }
    

      

    import java.util.ArrayList;
    import java.util.Date;
    import java.util.List;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.ModelMap;
    import org.springframework.web.bind.annotation.PostMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    import com.imooc.pojo.User;
    
    @Controller
    @RequestMapping("two")
    public class TwoController {
    
    	@RequestMapping("/index")
        public String index(ModelMap map) {
            map.addAttribute("name", "itzixi22");
            return "thymeleaf/index";
        }
    	
    	@RequestMapping("center")
        public String center() {
            return "thymeleaf/center/center";
        }
    
    	@RequestMapping("test")
        public String test(ModelMap map) {
    		
    		User user = new User();
    		user.setAge(18);
    		user.setName("manager");
    		user.setPassword("123456");
    		user.setBirthday(new Date());
    		
    		map.addAttribute("user", user);
    		
    		
    		User u1 = new User();
    		u1.setAge(19);
    		u1.setName("itzixi");
    		u1.setPassword("123456");
    		u1.setBirthday(new Date());
    		
    		User u2 = new User();
    		u2.setAge(17);
    		u2.setName("LeeCX");
    		u2.setPassword("123456");
    		u2.setBirthday(new Date());
    		
    		List<User> userList = new ArrayList<>();
    		userList.add(user);
    		userList.add(u1);
    		userList.add(u2);
    		
    		map.addAttribute("userList", userList);
    		
            return "thymeleaf/test";
        }
    	
    	@PostMapping("postform")
        public String postform(User user) {
    		System.out.println(user.getName());
            return "redirect:/th/test";
        }
    }
    

      

      

  • 相关阅读:
    SQL 分组 行变列的一个例子
    用JS如何獲得DropDownList所選Text和Value?
    用了.net2.0,再用1.1的问题。1.1里修改.cs文件不重新编译,.dll不重新生成。
    ASP.NET中上传文件
    获得用户控件的值!
    在没有vs2005环境里部署Crystal Reports 10水晶报表
    onkeypress,onkeydown,onkeyup区别
    2012湖南大学第八届程序设计竞赛 Incredible[公式]
    POJ3624 Charm Bracelet[01背包问题入门]
    HDOJ1257 最少拦截系统[DP入门]
  • 原文地址:https://www.cnblogs.com/pejsidney/p/8661604.html
Copyright © 2020-2023  润新知