方法1:适用于POST请求,不适用于GET{}拼接参数

方法2:适用于模板,页面必须放到error文件夹下,不需要写任何java代码

方法3:适用于根据status值去判断,但是如果页面的图片地址是有动态参数,建议修改成相对引用,或者注入bean

目录

参考文章

前言

准备工作

404.html和ErrorCtrl

开始内部处理

所有访问

getPath()

applicationContext 之 ApplicationContextFactory

启动类SampleApplication

主要逻辑

404拦截处理WebMvcInterceptor

InterceptorConfig

效果图(略)

参考文章

获取本工程中有哪些请求路径

SpringBoot中使用ApplicationContext获取bean对象

SPRINGBOOT加入拦截器INTERCEPTOR

前言

有时候我们在登录网页的时候会发现,输入了错误的页面路径会变成如下页面:

实际上我们想要他能够跳转到404页面!那么这个需求该如何实现呢?

准备工作

404.html和ErrorCtrl

首先第一步我们先要画好404..html页面和对应的webctrl跳转做准备好:

import cloud.maque.biz.tdsc.config.properties.MaqueServiceProperties;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;

import org.springframework.ui.Model;

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

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

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.Cookie;

@Controller

@RequestMapping("/error")

public class ErrorController {

@Autowired

MaqueServiceProperties maqueServiceProperties;

/*404 错误页面*/

@GetMapping("/404")

public String error404(Model model) {

model.addAttribute("subDomainUrl",maqueServiceProperties.getSubDomainUrl());

return "common/404";

}

}

开始内部处理

所有访问

getPath()

这里就比较重要了,我们需要当前访问的web浏览器路径和整个工程中的路径比对,那么前提要获取整个工程的web访问路径,如何获取呢?

参考文章:获取本工程中有哪些请求路径

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.context.ApplicationContext;

import org.springframework.stereotype.Controller;

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

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

import org.springframework.web.method.HandlerMethod;

import org.springframework.web.servlet.handler.AbstractHandlerMethodMapping;

import org.springframework.web.servlet.mvc.method.RequestMappingInfo;

import java.util.*;

@Controller

@RequestMapping(value = "/test")

public class SpringBootTest {

@Autowired

ApplicationContext applicationContext;

@RequestMapping(value = "/getPath")

public

@ResponseBody

List getPath() {

Listlist = new ArrayList<>();

AbstractHandlerMethodMappingobjHandlerMethodMapping =

(AbstractHandlerMethodMapping) applicationContext.getBean("requestMappingHandlerMapping");

MapmapRet = objHandlerMethodMapping.getHandlerMethods();

for (RequestMappingInfo requestMappingInfo : mapRet.keySet()) {

Set set = requestMappingInfo.getPatternsCondition().getPatterns();

Iterator iterator = set.iterator();

while (iterator.hasNext()) {

list.add(iterator.next().toString());

}

}

return list;

}

}

applicationContext 之 ApplicationContextFactory

问题随之而来,我要在内容中可以直接获取,那么就是需要一个applicationContext这个对象去手动调用,这个就用到了ApplicationContextFactory:

import org.springframework.context.ApplicationContext;

/**

* Created by xuhy on 2020/7/30.

* 手动获取applicationContext对象

*/

public class ApplicationContextFactory {

private static ApplicationContext applicationContext = null;

public static void setApplicationContext(ApplicationContext applicationContext) {

ApplicationContextFactory.applicationContext = applicationContext;

}

public static ApplicationContext getApplicationContext() {

return applicationContext;

}

}

启动类SampleApplication

然后在启动的时候放进去:

参考文章:SpringBoot中使用ApplicationContext获取bean对象

ConfigurableApplicationContext app = SpringApplication.run(SampleApplication.class, args);

ApplicationContextFactory.setApplicationContext(app);

主要逻辑

我们开始综上所述写404处理逻辑;

404拦截处理WebMvcInterceptor

这里包含了当前url和所有工程url比对:

import org.springframework.context.ApplicationContext;

import org.springframework.web.method.HandlerMethod;

import org.springframework.web.servlet.HandlerInterceptor;

import org.springframework.web.servlet.handler.AbstractHandlerMethodMapping;

import org.springframework.web.servlet.mvc.method.RequestMappingInfo;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import java.util.*;

/**

* Created by xuhy on 2020/7/30.

* 拦截错误web请求

*/

public class WebMvcInterceptor implements HandlerInterceptor {

@Override

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

// model.addAttribute("subDomainUrl",maqueServiceProperties.getSubDomainUrl());

// 获取所有请求路径

Listpaths = getPath();

// 匹配结果

Object[] result = paths.stream().filter(path -> path.equals(request.getRequestURI())).toArray();

if (result.length == 0) {

return true;

} else {

response.sendRedirect("/error/404");

return false;

}

}

/**

* 获取所有webe请求路径

* @return

*/

ListgetPath() {

Listlist = new ArrayList<>();

ApplicationContext applicationContext = ApplicationContextFactory.getApplicationContext();

AbstractHandlerMethodMappingobjHandlerMethodMapping =

(AbstractHandlerMethodMapping) applicationContext.getBean("requestMappingHandlerMapping");

MapmapRet = objHandlerMethodMapping.getHandlerMethods();

for (RequestMappingInfo requestMappingInfo : mapRet.keySet()) {

Set set = requestMappingInfo.getPatternsCondition().getPatterns();

Iterator iterator = set.iterator();

while (iterator.hasNext()) {

list.add(iterator.next().toString());

}

}

return list;

}

}

InterceptorConfig

/**

*  @description: web拦截器

*  @author xuhy

*  @date: 2020/7/31

*/

@Configuration

public class InterceptorConfig implements WebMvcConfigurer {

// 如果没写@Bean 则需要通过new xx写,写了则 registry.addInterceptor(webMvcInterceptor()).addPathPatterns("/**")

@Bean

public WebMvcInterceptor webMvcInterceptor() {

return new WebMvcInterceptor();

}

@Override

public void addInterceptors(InterceptorRegistry registry) {

//404.html blank.html 500.html 此方法添加拦截器

registry.addInterceptor(new WebMvcInterceptor()).addPathPatterns("/**");

}

}

值得注意的是

.excludePathPatterns("/js/**");

//404.html blank.html 500.html 此方法添加拦截器

registry.addInterceptor(new WebMvcInterceptor()).addPathPatterns("/**").

excludePathPatterns("/js/**", "/css/**", "/img/**","/api/**");

,不让然会出现图片访问正常的情况!!!

参考文章:SPRINGBOOT加入拦截器INTERCEPTOR

效果图(略)

java 做登录跳转404_springboot 访问路径错误跳转到404(实现方法一)相关推荐

  1. SpringMVC响应使用案例(带数据页面跳转,快捷访问路径,返回json数据)

    页面跳转 转发(默认) @RequestMapping("/showPage1") public String showPage1() {System.out.println(&q ...

  2. java做登录时要加锁吗_你用对锁了吗?谈谈 Java “锁” 事

    先来盘一盘为什么需要锁这玩意,这得从并发 BUG 的源头说起. 并发 BUG 的源头 这个问题我 19 年的时候写过一篇文章, 现在回头看那篇文章真的是羞涩啊. 让我们来看下这个源头是什么,我们知道电 ...

  3. Java MinIO文件上传返回访问路径及访问配置

    1. MinIO形式文件上传: 首先需要有MinIO服务器,这里略过. @PostMapping("file/upload")public String MinIOUpload(M ...

  4. springmvc 页面跳转样式访问路径总是多一层地址_Net Core实战之基于角色的访问控制的设计...

    前言 上个月,我写了两篇微服务的文章:<.Net微服务实战之技术架构分层篇>与<.Net微服务实战之技术选型篇>,微服务系列原有三篇,当我憋第三篇的内容时候一直没有灵感,因此先 ...

  5. 用java做登录界面_求用JAVA编写的登陆界面!

    展开全部 这是我刚做的,JAVA布局与其它语言相比难度较大,建议你将两张图片PS成一张图片,做32313133353236313431303231363533e4b893e5b19e313332393 ...

  6. 移动磁盘显示无法访问数据错误(循环冗余检查)的文件恢复方法

    数据错误(循环冗余检查)说明这个盘的文件系统结构损坏了.在平时如果数据不重要,那么可以直接格式化就能用了.但是有的时候里面的数据很重要,那么就必须先恢复出数据再格式化.具体恢复方法可以看正文了解(不格 ...

  7. idea 启动php项目路径,关于idea中Java Web项目的访问路径问题

    说明 这里只以 servlet 为例,没有涉及到框架,但其实路径的基本原理和框架的关系不大,所以学了框架的同学如果对路径有疑惑的也可以阅读此文 项目结构 在 idea 中新建一个 Java Web 项 ...

  8. java异地登录验证_同一帐号异地登录

    在此之前也看了很多同一帐号异地登录的,有的是采用后登录者必须等待前登录者释放后才可以登录,我的项目中要用到想qq那样可以踢出,我具体的做法如下: LoginServelt.java 做登录使用 Onl ...

  9. jeecms 修改后台访问路径

    我使用的是jeecmsV8版本. 1.修改web.xml(/jeecms/WebContent/WEB-INF/web.xml) 修改JeeCmsAdmin这个servlet,把/jeeadmin/j ...

最新文章

  1. 打一针就可修复受损心脏,“癌症克星”CAR-T跨界疗法登上Science封面
  2. 设计模式 — 行为型模式 — 迭代器模式
  3. cp linux 显示进度条_Unix/Linux/Mac os下 文件互传
  4. 引入宽字符error: converting to execution character set: Invalid or incomplete multibyte or wide character
  5. oracle scn隐藏参数,Oracle隐含参数scn不一致启动
  6. I00023 鸡兔同笼解法二
  7. Python之十点半小游戏
  8. java流程控制if_[Java]Java基本语法结构(运算符,流程控制语句,if语句)
  9. LINUX 7.0真机系统安装问题
  10. 【算法与数据结构】—— 并查集
  11. 在打开 Office XP 或 Office 2003 文档时,会提示您为 ActiveX 控件授予权限
  12. py文件转换成exe格式
  13. ArcGIS Runtime SDK for Android 读取tpk、vtpk
  14. 根据两点的经纬度求方位角和距离等问题
  15. ubuntu 安装wifi驱动(Device-c822)
  16. win10 屏幕切换鼠标手势桌面边缘快捷切换 ahk
  17. Java语言程序设计与数据结构(基础篇)梁勇第一章书中例题
  18. NuGet命令的用法
  19. 【Android】APK的打包流程
  20. 勘误发布:《数字滤波器的MATLAB与FPGA实现——Xilinx/VHDL版》P320

热门文章

  1. Cookies工作原理
  2. __try 内外不能有 c++ 代码,要封装成一个函数
  3. 大区块的BCH给智能合约更大的发展潜力
  4. 如何让一种币更有生命力——一种BCH开发资金募集方案大讨论
  5. KafKa集群安装、配置
  6. 【码云周刊第 68 期】数据可视化:商业智能的未来!
  7. 微信小程序项目重构之Redux状态管理
  8. S2系统相关-uptime命令总结(S代表系统相关)
  9. Katana-CookieAuthenticationMiddleware-源码浅析
  10. 从Visual Studio里抓取抽象语法树(AST)