springmvc登录拦截
参考网址:
https://blog.csdn.net/pan_junbiao/article/details/103808134?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522160740325219724816682724%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fall.%2522%257D&request_id=160740325219724816682724&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2allfirst_rank_v2~rank_v29-6-103808134.first_rank_v2_pc_rank_v29&utm_term=springmvc%E5%9F%BA%E4%BA%8E%E6%8B%A6%E6%88%AA%E5%99%A8%E5%AE%9E%E7%8E%B0%E7%99%BB%E5%BD%95%E5%8A%9F%E8%83%BD&spm=1018.2118.3001.4449
https://blog.csdn.net/shangxingya/article/details/109550776?utm_medium=distribute.pc_relevant.none-task-blog-utm_term-6&spm=1001.2101.3001.4242
1.先使用maven创建springmvc工程
略
2.配置拦截器
2.1.拦截器类
package com.shaoming.interceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
/**
* 登录拦截器
* @author pan_junbiao
**/
public class LoginInterceptor implements HandlerInterceptor
{
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
{
String uri = request.getRequestURI();
//判断当前请求地址是否登录地址
if(uri.contains("Login") || uri.contains("login"))
{
//登录请求,直接放行
return true;
}
else
{
//判断用户是否登录
if(request.getSession().getAttribute("user")!=null)
{
//说明已经登录,放行
return true;
}
else
{
//没有登录,跳转到登录界面
response.sendRedirect(request.getContextPath() + "/toLoginPage");
}
}
//默认拦截
return false;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,Exception ex) throws Exception {
}
}
2.2.配置文件(springmvc-config.xml)配置拦截器
<?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/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<!-- 1.配置前端控制器放行静态资源(html/css/js等,否则静态资源将无法访问) -->
<mvc:default-servlet-handler />
<!-- 2.配置注解驱动,用于识别注解(比如@Controller) -->
<mvc:annotation-driven></mvc:annotation-driven>
<!-- 3.配置需要扫描的包:spring自动去扫描 base-package 下的类, 如果扫描到的类上有 @Controller、@Service、@Component等注解,
将会自动将类注册为bean @Controller public class HelloController{} -->
<context:component-scan
base-package="com.shaoming.controller">
</context:component-scan>
<!-- 4.配置内部资源视图解析器 prefix:配置路径前缀 suffix:配置文件后缀 /WEB-INF/pages/home.jsp -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- 配置文件上传,如果没有使用文件上传可以不用配置,当然如果不配,那么配置文件中也不必引入上传组件包 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 默认编码 -->
<property name="defaultEncoding" value="utf-8" />
<!-- 文件大小最大值 -->
<property name="maxUploadSize" value="10485760000" />
<!-- 内存中的最大值 -->
<property name="maxInMemorySize" value="40960" />
<!-- 启用是为了推迟文件解析,以便捕获文件大小异常 -->
<property name="resolveLazily" value="true" />
<property name="uploadTempDir" value="fileUpload/temp" />
</bean>
<!--统一的异常处理-->
<bean class="com.shaoming.exception.CustomerExceptionResolver"></bean>
<!-- interceptor拦截器 -->
<mvc:interceptors>
<!-- 多个拦截器,顺序执行 -->
<mvc:interceptor>
<!-- /**表示所有url包括子url路径 -->
<mvc:mapping path="/**"/>
<bean class="com.shaoming.interceptor.LoginInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>
</beans>
主要是这个配置
mvc:interceptors
mvc:interceptor
<mvc:mapping path="/**"/>
</mvc:interceptor>
</mvc:interceptors>
3.测试登录的controller
package com.shaoming.controller;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* 登录控制器
* @author pan_junbiao
**/
@Controller
public class LoginController
{
/**
* 登录页面
*/
@RequestMapping("/toLoginPage")
public String toLoginPage()
{
//跳转至登录页面
return "login";
}
/**
* 登录
*/
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String login(Model model, HttpServletRequest request, String user, String password)
{
//验证登录信息
if (user.equals("root") && password.equals("123456"))
{
//验证成功,记录Session信息
request.getSession().setAttribute("user", user);
//重定向到首页
return "redirect:index.jsp";
}
else
{
model.addAttribute("errorMsg", "账号或密码错误!");
}
//跳转至登录页面
return "redirect:toLoginPage";
}
/**
* 登出
*/
@RequestMapping(value = "/logout")
public String logout(HttpServletRequest request)
{
//销毁session对象
request.getSession().invalidate();
//重定向到登录页面
return "redirect:toLoginPage";
}
}
4.测试跳转的页面
- /springmvc-cli/src/main/webapp/WEB-INF/pages
home.jsp
<%@ page pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<h1>Hello World</h1>
</body>
</html>
login.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>用户登录</title>
<meta name="author" content="pan_junbiao的博客">
<style>
.txtBox{
padding: 3px;
width: 250px;
font-size: 16px;
}
</style>
</head>
<body>
<div align="center">
<form name="form1" method="post" action="login" οnsubmit="return SubmitLogin()">
<table>
<caption>用户登录</caption>
<tr>
<th>账号:</th>
<td>
<input type="text" name="user" value="root" class="txtBox"/>
</td>
</tr>
<tr>
<th>密码:</th>
<td>
<input type="password" name="password" class="txtBox" />
</td>
</tr>
<!-- 以下是提交、取消按钮 -->
<tr>
<td colspan="2" style="text-align: center;">
<input type="submit" value="登录" />
<input type="reset" value="取消" />
</td>
</tr>
</table>
<!-- 显示错误信息 -->
<span style="color:red"><%=request.getAttribute("errorMsg") == null ? "" : request.getAttribute("errorMsg")%></span>
</form>
</div>
</body>
<script>
//提交登录
function SubmitLogin() {
//判断用户名是否为空
if (!form1.user.value) {
alert("请输入用户名!");
form1.user.focus();
return false;
}
//判断密码是否为空
if (!form1.password.value) {
alert("请输入密码!");
form1.password.focus();
return false;
}
return true;
}
</script>
<div style="text-align: center;">
<a href="/springmvc-cli/hello">跳转到home.jsp页面 失败, 测试全局异常处理页面是否生效</a>
<a href="/springmvc-cli/hello1">跳转到home.jsp页面</a>
</div>
</html>
- /springmvc-cli/src/main/webapp/
index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>首页</title>
<meta name="author" content="pan_junbiao的博客">
</head>
<body>
<h1>首页</h1>
<p>当前Session中保存的登录人名称:${sessionScope.user}</p>
<p>您好,欢迎访问 pan_junbiao的博客!</p>
<p>博客地址:https://blog.csdn.net/pan_junbiao</p>
<a href="logout" οnclick="return confirm('确定注销吗?');">注销</a>
<hr>
<div style="text-align: center;">
<a href="/springmvc-cli/hello">跳转到home.jsp页面 失败, 测试全局异常处理页面是否生效</a>
<a href="/springmvc-cli/hello1">跳转到home.jsp页面</a>
</div>
</body>
</html>
5.附加全局的异常处理页面
参考网址:
https://blog.csdn.net/shaoming314/article/details/110848350
5.1 自定义异常类
package com.shaoming.exception;
//自定义异常类
public class CustomerException extends RuntimeException {
public CustomerException(String msg){
super(msg);
}
}
5.2 自定义异常处理页面解析
package com.shaoming.exception;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import sun.util.logging.resources.logging;
public class CustomerExceptionResolver implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception ex) {
System.out.println("testException执行了...");
CustomerException e = null;
if(ex instanceof CustomerException) {
e=(CustomerException) ex;
}else {
//如果是预料之外的异常,我们自定义一个友好的异常信息
e = new CustomerException("出现了意料之外的异常,请联系管理员.....110");
}
ModelAndView modelAndView=new ModelAndView();
//如果是我们自己抛出的异常,那么异常页面显示我们自己定义的异常信息
modelAndView.addObject("error",e.getMessage());//接收 错误的异常信息
modelAndView.setViewName("error");
//打印真正的栈异常信息
ex.printStackTrace();
//打印真正的异常信息
System.out.println(ex.getMessage());
return modelAndView;
}
}
5.3 配置异常视图解析器
在springmvc-config.xml配置
<!--统一的异常处理-->
<bean class="com.shaoming.exception.CustomerExceptionResolver"></bean>
5.5 异常页面
/springmvc-cli/src/main/webapp/WEB-INF/pages/error.jsp
<%@ page pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<h1>报错信息页面</h1>
<div>${ error }</div>
</body>
</html>
个人csdn博客网址:https://blog.csdn.net/shaoming314
<bean class="com.shaoming.exception.CustomerExceptionResolver"></bean>
### 5.5 异常页面
`/springmvc-cli/src/main/webapp/WEB-INF/pages/error.jsp`
```jsp
<%@ page pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<h1>报错信息页面</h1>
<div>${ error }</div>
</body>
</html>
个人csdn博客网址:https://blog.csdn.net/shaoming314