老师,为什么我的登陆过滤器,登陆了进不去呢?

老师,为什么我的登陆过滤器,登陆了进不去呢?

http://img1.sycdn.imooc.com//climg/5eca35a70986e84201090030.jpg

/**

 *  判断用户是否登录的过滤器

 * */

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

}


}

http://img1.sycdn.imooc.com//climg/5eca35d5097eeb2400910023.jpg

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


正在回答

登陆购买课程后可参与讨论,去登陆

6回答

同学你好,登录成功后,同学将用户信息保存到session中,命名为existUser,如:

http://img1.sycdn.imooc.com//climg/5ecb33ff09c023b506400170.jpg

从session中获取值时,同学获取user,如:

http://img1.sycdn.imooc.com//climg/5ecb3415099dd04f08760189.jpg

获取时和存入的名称不同,所以获取为null,这里应该获取存入session的名称existUser。

如果我的回答解决了你的疑惑,请采纳。祝:学习愉快~

提问者 阿硕A 2020-05-24 21:36:05

http://img1.sycdn.imooc.com//climg/5eca783c099ebc3e12610635.jpg

这是问题

提问者 阿硕A 2020-05-24 21:33:36

http://img1.sycdn.imooc.com//climg/5eca7780098ebb6f01370034.jpg

/**

 * 

 * 监听器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);

    }

}

http://img1.sycdn.imooc.com//climg/5eca77900997370501550016.jpg

/**

 * 用户信息处理类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">

                    &nbsp;&nbsp;&nbsp;&nbsp;

                    <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>

http://img1.sycdn.imooc.com//climg/5eca77a7093856d701190037.jpg

/**

 * 判断用户登录

 * */

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);

}


}


好帮手慕阿满 2020-05-24 18:29:46

同学你好,同学登录的映射是LoginServlet,如:

http://img1.sycdn.imooc.com//climg/5eca4c5309541ffb05600133.jpg

http://img1.sycdn.imooc.com//climg/5eca4c40096c022108400121.jpg

建议同学在登录过滤器的url数组中增加LoginServlet再试试。

祝:学习愉快~

  • 提问者 阿硕A #1
    老师,按照你的改了,点击登录一直是登陆界面
    2020-05-24 21:32:44
  • 提问者 阿硕A #2
    老师,我打印了一下user,里边是空的,所以会一直是登陆界面,这个怎么改呢?
    2020-05-24 21:34:20
提问者 阿硕A 2020-05-24 17:52:48

http://img1.sycdn.imooc.com//climg/5eca43bc09edd21000980029.jpg

<%@ 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">

                    &nbsp;&nbsp;&nbsp;&nbsp;

                    <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>


http://img1.sycdn.imooc.com//climg/5eca43ee0956397c01060028.jpg

/**

 * 判断用户登录

 * */

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);

}


}



好帮手慕阿满 2020-05-24 17:47:28

同学你好,问一下同学跳转登录的映射是/login吗?建议同学将登录相关的代码贴一下,方便我们具体查看。

祝:学习愉快~

问题已解决,确定采纳
还有疑问,暂不采纳

恭喜解决一个难题,获得1积分~

来为老师/同学的回答评分吧

0 星
请稍等 ...
意见反馈 帮助中心 APP下载
官方微信

在线咨询

领取优惠

免费试听

领取大纲

扫描二维码,添加
你的专属老师