老师,为什么我的登陆过滤器,登陆了进不去呢?
/**
* 判断用户是否登录的过滤器
* */
package com.imooc.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.imooc.domain.User;
public class AuthFilter implements Filter{
@Override
public void destroy() {
// TODO Auto-generated method stub
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
//获取请求页面的相对路径
HttpServletRequest req= (HttpServletRequest) request;
HttpServletResponse res=(HttpServletResponse) response;
HttpSession session=req.getSession();
User user=(User) session.getAttribute("user");
String path=req.getServletPath();
String url[]= {"/login","/json",".js",".css",".ico","jpg",".png",".jpeg","/KaptchaServlet","/login.jsp"};
System.out.println(path);
boolean flag=true;
for(String str:url) {
if(path.endsWith(str)) {
flag=false;
break;
}
}
if(flag) {
if(user!=null) {
chain.doFilter(request, response);
}else {
res.sendRedirect(req.getContextPath()+"/login.jsp");
}
}else {
chain.doFilter(request, response);
}
}
@Override
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub
}
}
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>regise_login_xm</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>KaptchaServlet</servlet-name>
<servlet-class>com.google.code.kaptcha.servlet.KaptchaServlet</servlet-class>
<!-- 修改随机的字母或数字的长度 -->
<init-param>
<param-name>kaptcha.textproducer.char.length</param-name>
<param-value>4</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>KaptchaServlet</servlet-name>
<url-pattern>/KaptchaServlet</url-pattern>
</servlet-mapping>
<listener>
<listener-class>com.imooc.web.listener.GategoryListener</listener-class>
</listener>
<!-- 配置中文乱码过滤器 -->
<filter>
<filter-name>EncodeFilter</filter-name>
<filter-class>com.imooc.filter.EncodeFilter</filter-class>
<!-- 设置参数 -->
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>EncodeFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 配置登陆过滤器 -->
<filter>
<filter-name>AuthFilter</filter-name>
<filter-class>com.imooc.filter.AuthFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>AuthFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
正在回答
同学你好,登录成功后,同学将用户信息保存到session中,命名为existUser,如:
从session中获取值时,同学获取user,如:
获取时和存入的名称不同,所以获取为null,这里应该获取存入session的名称existUser。
如果我的回答解决了你的疑惑,请采纳。祝:学习愉快~
/**
*
* 监听器InitListener:
方法:contentDestroyed()方法和contextInitialized()方法
* */
package com.imooc.web.listener;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import com.imooc.domain.User;
@WebListener
public class InitListener implements ServletContextListener {
public InitListener() {
}
public void contextDestroyed(ServletContextEvent sce) {
}
public void contextInitialized(ServletContextEvent sce) { //创建监听器
System.out.println("项目中的数据已初始化!");
//创建一个用于保存用户信息的lists集合
List<User> userList=new ArrayList<User>();
userList.add(new User("a","a"));//登陆的用户
userList.add(new User("b","b"));
//将list集合存到ServletContext域中
sce.getServletContext().setAttribute("userList",userList);
}
}
/**
* 用户信息处理类UserServiceImpl:
方法:
用户登录: public int login(List<User> listUser,User user) {}
* */
package com.imooc.impl;
import java.util.List;
import com.imooc.domain.User;
import com.imooc.service.UserService;
public class UserServiceImpl implements UserService{
public void regist(List<User> listUser,User user) {
listUser.add(user);//用于保存用户信息
}
public int login(List<User> listUser,User user) {
for(User existUser:listUser) {
if(existUser.getUsername().equals(user.getUsername()) && existUser.getPassword().equals(user.getPassword())) {
return 1;
}
}
return 0 ;
}
}
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>登录</title>
<link rel="stylesheet" href="css/login.css">
<script type="text/javascript">
function changeImg(){
var codeImg = document.getElementById("codeImg");
codeImg.src="${pageContext.request.contextPath }/KaptchaServlet?time="+new Date().getTime();
}
</script>
</head>
<body>
<div class="login">
<div class="header">
<h1>
<a href="/login.do">登录</a>
</h1>
<button></button>
</div>
<form action="${pageContext.request.contextPath }/LoginServlet" method="post">
<div class="name">
<input type="text" id="name" name="username" >
<p></p>
</div>
<div class="pwd">
<input type="password" id="pwd" name="password" >
<p></p>
</div>
<div class="code">
<input type="text" id="code" name="verifyCode" style="width: 150px">
<img id="codeImg" onclick="changeImg()" src="${pageContext.request.contextPath }/KaptchaServlet" style="width: 150px;height: 42px;vertical-align: middle;">
<p>${ msg }</p>
</div>
<div class="btn-red">
<input type="submit" value="登录" id="login-btn">
</div>
</form>
</div>
</body>
</html>
/**
* 判断用户登录
* */
package com.imooc.web.servlet;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.imooc.domain.User;
import com.imooc.impl.UserServiceImpl;
import com.imooc.service.UserService;
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//完成验证码校验:
//获得Sesstion中保存的验证码信息
String code1 =(String) request.getSession().getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
//接收前台表单提交的验证码信息
String code2 = request.getParameter("verifyCode");
if(code2==null || !code2.equalsIgnoreCase(code1)) {
request.setAttribute("msg", "验证码错误");
request.getRequestDispatcher("/login.jsp").forward(request, response);
return;
}
//接收数据
String username = request.getParameter("username");
String password = request.getParameter("password");
//封装数据
User user=new User();
user.setUsername(username);
user.setPassword(password);
//处理数据:完成登录
UserService userService=new UserServiceImpl();
//获得用户列表集合
List<User> userList=(List<User>) getServletContext().getAttribute("userList");
int existUser =userService.login(userList, user);
//完成登录
if(existUser == 0) {
//登录失败
request.setAttribute("msg", "用户名或密码错误!");
request.getRequestDispatcher("/login.jsp").forward(request, response);
}else {
//登陆成功
//用户保存信息
request.getSession().setAttribute("existUser", existUser);
response.sendRedirect(request.getContextPath()+"/categoryList.jsp");
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>登录</title>
<link rel="stylesheet" href="css/login.css">
<script type="text/javascript">
function changeImg(){
var codeImg = document.getElementById("codeImg");
codeImg.src="${pageContext.request.contextPath }/KaptchaServlet?time="+new Date().getTime();
}
</script>
</head>
<body>
<div class="login">
<div class="header">
<h1>
<a href="/login.do">登录</a>
</h1>
<button></button>
</div>
<form action="${pageContext.request.contextPath }/LoginServlet" method="post">
<div class="name">
<input type="text" id="name" name="username" >
<p></p>
</div>
<div class="pwd">
<input type="password" id="pwd" name="password" >
<p></p>
</div>
<div class="code">
<input type="text" id="code" name="verifyCode" style="width: 150px">
<img id="codeImg" onclick="changeImg()" src="${pageContext.request.contextPath }/KaptchaServlet" style="width: 150px;height: 42px;vertical-align: middle;">
<p>${ msg }</p>
</div>
<div class="btn-red">
<input type="submit" value="登录" id="login-btn">
</div>
</form>
</div>
</body>
</html>
/**
* 判断用户登录
* */
package com.imooc.web.servlet;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.imooc.domain.User;
import com.imooc.impl.UserServiceImpl;
import com.imooc.service.UserService;
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//完成验证码校验:
//获得Sesstion中保存的验证码信息
String code1 =(String) request.getSession().getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
//接收前台表单提交的验证码信息
String code2 = request.getParameter("verifyCode");
if(code2==null || !code2.equalsIgnoreCase(code1)) {
request.setAttribute("msg", "验证码错误");
request.getRequestDispatcher("/login.jsp").forward(request, response);
return;
}
//接收数据
String username = request.getParameter("username");
String password = request.getParameter("password");
//封装数据
User user=new User();
user.setUsername(username);
user.setPassword(password);
//处理数据:完成登录
UserService userService=new UserServiceImpl();
//获得用户列表集合
List<User> userList=(List<User>) getServletContext().getAttribute("userList");
int existUser =userService.login(userList, user);
//完成登录
if(existUser == 0) {
//登录失败
request.setAttribute("msg", "用户名或密码错误!");
request.getRequestDispatcher("/login.jsp").forward(request, response);
}else {
//登陆成功
//用户保存信息
request.getSession().setAttribute("existUser", existUser);
response.sendRedirect(request.getContextPath()+"/categoryList.jsp");
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
- 参与学习 人
- 提交作业 676 份
- 解答问题 9666 个
本阶段将从前端网页搭建入手,到Java Web基础,前后端结合助你完成Java Web小白的蜕变!
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星