jsp--3.cookies

本文介绍如何利用Cookie实现十天内免登录的功能。详细解释了Cookie的工作原理、创建及设置过程,并通过示例展示了如何在Java Web应用中具体实现这一功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1      Cookie

1.1  概述

         服务器脚本向浏览器发送一组Cookie。例如:姓名、年龄或识别号码等。

         浏览器将这些信息存储在本地计算机上,以备将来使用。

         当下一次浏览器向 Web 服务器发送任何请求时,浏览器会把这些 Cookie 信息发送到服务器,服务器将使用这些信息来识别用户。

 

1.2  创建并设置

1.2.1  创建

Cookie cookie1 = new Cookie("username", username);

 

// 为名字和姓氏创建 Cookie     

Cookie name = new Cookie("name",URLEncoder.encode(username, "UTF-8")); // 中文转码

 

1.2.2  设置有效时间

cookie1.setMaxAge(10*24*60*60);

 

1.2.3  设置关联路径

cookie1.setPath(request.getContextPath());

 

1.2.4  写入cookie

response.addCookie(cookie1);

 

1.3  得到并使用

1.3.1  得到cookie

得到一个数组

Cookie[] cookies = request.getCookies();

 

后面步骤通过for遍历得到每一个cookie

 

1.3.2  遍历cookie

 

1.3.3  得到cookie的name和value

String cookieName = cookie.getName();

String cookieValue =cookie.getValue();

 

 

1.3.4  根据name得到value

           

if ("username".equals(cookieName)) {

      username= cookieValue;

}

补充:

   假如记录的用户名和密码,不要被固始思维困扰,此时就不要请求作用域(ognl)的数据,传入的是上面在cookie获得的参数,

   还有一点很重要,假如从cookie获得用户名和密码,不要吝啬servlet(action),就不要写在原来那个需要登录访问的servlet(action),再建一个servlet,重复原来的部分功能都可以

2      十天免登录原始

2.1  先搭建登录环境

2.1.1  Jsp

2.1.1.1       login.jsp

<body>
	<form action="LoginServlet" method="post">
	用户名:<input type="text" name="username"/>	<br />
	密码:<input type="password" name="password" />	<br />
	<input type="checkbox" name="day10" value="ok"/>十天	<br />
		<input type="submit" value="提交"/>
	</form>
</body> 
2.1.1.2       成功页面one.jsp

<body>
登录陈宫<%=session.getAttribute("username") %>
</body> 
2.1.1.3       失败页面fair.jsp

<body>
	失败
</body> 

2.1.2  Servlet

2.1.2.1       登录UserServlet

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		
		User user = new User();
		user.setUsername(username);
		user.setPassword(password);
		
		System.out.println(user.getUsername());
		
		//连接数据库验证用户密码
		UserService userService = new UserService();
		boolean flag = userService.login(user);
		
		//登录成功跳转,失败跳到失页面
		if (flag) {
			
			request.getSession().setAttribute("username", user.getUsername());
			response.sendRedirect("one.jsp");
		} else {
			response.sendRedirect("fair.jsp");
		}
		
	}

2.1.3  Service

 

public boolean login(User user) {
		UserDao userDao = new UserDao();
		return userDao.login(user);
	} 

2.1.4  Dao

public boolean login(User user) {

		Connection conn =  new DbUtil().getDBConn();
		
		PreparedStatement pstmt;
		ResultSet res;
		
		boolean flag = false;
		try {
			
			String sql = "SELECT * FROM t_user WHERE username = ? AND PASSWORD = ?";
			
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, user.getUsername());
			pstmt.setString(2, user.getPassword());
			
			res = pstmt.executeQuery();
			
			if (res.next()) {
				flag = true;
			}
			
			System.out.println(flag);
			return flag;
		} catch (SQLException e) {
			e.printStackTrace();
			return flag;
		}
		
	}

2.1.5  Bean

 

2.1.6  Utils

//连接数据库  登录界面
public class DbUtil {
	 
	 String url = "jdbc:mysql://localhost:3306/cookie" ;
	 String username = "root" ;
	 String password = "root" ;  

	 Connection con = null ;	
	 
	public Connection getDBConn(){
		try {
			Class.forName("com.mysql.jdbc.Driver");
			
			con=DriverManager.getConnection(url,username,password);
			
			return con;
			
		} catch (Exception e) {
			
			e.printStackTrace();
			return null;
		}

	}
}

 

2.2  Cookie修改

2.2.1  实现思路

         获得cookie的username和password,然后servlet重新请求,说白了就是新建一个servlet

         新建是servlet作为程序的入口

2.2.2  Sevlet—修改UserServlet

 

String day10 = request.getParameter("day10");
			System.out.println(day10);
			if ("ok".equals(day10)) {
				//创建cookie
				Cookie cookie1 = new Cookie("username", username);
				Cookie cookie2 = new Cookie("password", password);
				
				//设置有效时间
				cookie1.setMaxAge(10*24*60*60);
				cookie2.setMaxAge(10*24*60*60);
				
				//设置关联路径
				cookie1.setPath(request.getContextPath());
				cookie2.setPath(request.getContextPath());
				
				//发送cookie给浏览器
				response.addCookie(cookie1);
				response.addCookie(cookie2);
			}

2.2.3  Servlet—isLogin,

程序入口改为这个

 

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//从request获取所有cookie
		Cookie[] cookies = request.getCookies();
		String username = null;
		String password = null; 
		
		
		if (cookies != null) {
			//遍历cookie
			for (Cookie cookie : cookies) {
				String cookieName = cookie.getName();
				String cookieValue = cookie.getValue();
				
				if ("username".equals(cookieName)) {
					username = cookieValue;
				}
				
				if ("password".equals(cookieName)) {
					password = cookieValue;
				}
			}
		}
		
		if (username != null && password != null) {
			User user = new User();
			user.setUsername(username);
			user.setPassword(password);
			
			//连接数据库验证用户密码
			UserService userService = new UserService();
			boolean flag = userService.login(user);
			
			//登录成功跳转
			if (flag) {
				request.getSession().setAttribute("username", user.getUsername());
				response.sendRedirect("one.jsp");
			} else {
				response.sendRedirect("fair.jsp");
			}
			
		} else {
			response.sendRedirect("login.jsp");
		}
	}

注意:此时属性封装的不是页面数据,而是cookie的数据,所以需要新的servlet,准确的点说,不在同一个方法

 

3      Struts中

3.1  Action

  

 

3.2  实现思路:

         和原始方式大同小异,重新来个action,程序入口改为这个

 

3.3  修改UserAction

 

3.4  修改IndexAction

 

 

 

3.5  Struts.xml

 

 

 

 

 源代码文件:http://download.youkuaiyun.com/detail/qq_26553781/9825051

 

 

 

 

 

收到认证请求,路径:/KuCun2/users/login 请求方法:POST Content-Type:application/json Authentication attempt with: 123456_987987 123456 2025-05-29 16:22:32.170 DEBUG 28236 --- [nio-8080-exec-2] org.hibernate.SQL : select * from user where andy=? Hibernate: select * from user where andy=? {id:1, name:超管, andy:123456, pass:$2a$10$JflS0yjBRY6yDRxdhAuHVunetrG2P6q8gj8HQzuaPtW8tt/OqO73S, role:0} 0 [{"authority":"ROLE_ADMIN"}] 0 com.kucun.Config.user.CustomUserDetails@2362529c123456 0 2025-05-29 16:22:34.049 DEBUG 28236 --- [nio-8080-exec-3] o.s.web.servlet.DispatcherServlet : GET "/KuCun2/index.html", parameters={} 2025-05-29 16:22:34.049 DEBUG 28236 --- [nio-8080-exec-3] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler ["classpath:/jsp/"] 2025-05-29 16:22:34.054 DEBUG 28236 --- [nio-8080-exec-3] o.s.web.servlet.DispatcherServlet : Completed 200 OK 2025-05-29 16:22:34.138 DEBUG 28236 --- [nio-8080-exec-5] o.s.web.servlet.DispatcherServlet : GET "/KuCun2/css/util.css", parameters={} 2025-05-29 16:22:34.139 DEBUG 28236 --- [nio-8080-exec-5] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler ["classpath:/jsp/"] 2025-05-29 16:22:34.150 DEBUG 28236 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : GET "/KuCun2/fonts/font-awesome-4.7.0/css/font-awesome.min.css", parameters={} 2025-05-29 16:22:34.152 DEBUG 28236 --- [nio-8080-exec-1] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler ["classpath:/jsp/"] 2025-05-29 16:22:34.155 DEBUG 28236 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed 200 OK 2025-05-29 16:22:34.156 DEBUG 28236 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : GET "/KuCun2/css/main.css", parameters={} 2025-05-29 16:22:34.158 DEBUG 28236 --- [nio-8080-exec-1] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler ["classpath:/jsp/"] 2025-05-29 16:22:34.162 DEBUG 28236 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed 200 OK 2025-05-29 16:22:34.168 DEBUG 28236 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : GET "/KuCun2/css/index2.css", parameters={} 2025-05-29 16:22:34.169 DEBUG 28236 --- [nio-8080-exec-1] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler ["classpath:/jsp/"] 2025-05-29 16:22:34.171 DEBUG 28236 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed 200 OK 2025-05-29 16:22:34.174 DEBUG 28236 --- [nio-8080-exec-6] o.s.web.servlet.DispatcherServlet : GET "/KuCun2/js/jquery-3.2.1.min.js", parameters={} 2025-05-29 16:22:34.175 DEBUG 28236 --- [nio-8080-exec-6] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler ["classpath:/jsp/"] 2025-05-29 16:22:34.198 DEBUG 28236 --- [nio-8080-exec-8] o.s.web.servlet.DispatcherServlet : GET "/KuCun2/js/jsyilai.js", parameters={} 2025-05-29 16:22:34.199 DEBUG 28236 --- [nio-8080-exec-8] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler ["classpath:/jsp/"] 2025-05-29 16:22:34.202 DEBUG 28236 --- [nio-8080-exec-8] o.s.web.servlet.DispatcherServlet : Completed 200 OK 2025-05-29 16:22:34.210 DEBUG 28236 --- [nio-8080-exec-6] o.s.web.servlet.DispatcherServlet : Completed 200 OK 2025-05-29 16:22:34.225 DEBUG 28236 --- [nio-8080-exec-5] o.s.web.servlet.DispatcherServlet : Completed 200 OK 2025-05-29 16:22:34.309 DEBUG 28236 --- [nio-8080-exec-9] o.s.web.servlet.DispatcherServlet : GET "/KuCun2/main/index.html", parameters={} 2025-05-29 16:22:34.309 DEBUG 28236 --- [nio-8080-exec-9] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler ["classpath:/jsp/"] 2025-05-29 16:22:34.314 DEBUG 28236 --- [nio-8080-exec-9] o.s.web.servlet.DispatcherServlet : Completed 200 OK 2025-05-29 16:22:34.319 DEBUG 28236 --- [nio-8080-exec-9] o.s.web.servlet.DispatcherServlet : GET "/KuCun2/js/main.js?1748506954294&_=1748506954258", parameters={masked} 2025-05-29 16:22:34.319 DEBUG 28236 --- [nio-8080-exec-9] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler ["classpath:/jsp/"] 2025-05-29 16:22:34.322 DEBUG 28236 --- [nio-8080-exec-9] o.s.web.servlet.DispatcherServlet : Completed 200 OK 2025-05-29 16:22:34.324 DEBUG 28236 --- [io-8080-exec-10] o.s.web.servlet.DispatcherServlet : GET "/KuCun2/js/index.js?1748506954296&_=1748506954259", parameters={masked} 2025-05-29 16:22:34.324 DEBUG 28236 --- [io-8080-exec-10] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler ["classpath:/jsp/"] 2025-05-29 16:22:34.326 DEBUG 28236 --- [io-8080-exec-10] o.s.web.servlet.DispatcherServlet : Completed 200 OK 2025-05-29 16:22:34.456 DEBUG 28236 --- [nio-8080-exec-3] o.s.web.servlet.DispatcherServlet : GET "/KuCun2/check-session", parameters={} 2025-05-29 16:22:34.457 DEBUG 28236 --- [nio-8080-exec-3] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to com.kucun.Config.SecurityConfig$SessionCheckController#checkSession(HttpServletRequest) 2025-05-29 16:22:34.473 DEBUG 28236 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : GET "/KuCun2/main/bootstrap-3.3.7-dist/js/MyTable.js", parameters={} 2025-05-29 16:22:34.473 DEBUG 28236 --- [nio-8080-exec-1] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler ["classpath:/jsp/"] 2025-05-29 16:22:34.476 DEBUG 28236 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed 200 OK 2025-05-29 16:22:34.493 DEBUG 28236 --- [nio-8080-exec-3] o.s.w.s.m.m.a.HttpEntityMethodProcessor : No match for [*/*], supported: [] 2025-05-29 16:22:34.494 DEBUG 28236 --- [nio-8080-exec-3] o.s.web.servlet.DispatcherServlet : Completed 200 OK 2025-05-29 16:22:34.628 DEBUG 28236 --- [nio-8080-exec-4] o.s.web.servlet.DispatcherServlet : GET "/KuCun2/login.html", parameters={} 2025-05-29 16:22:34.628 DEBUG 28236 --- [nio-8080-exec-4] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler ["classpath:/jsp/"] 2025-05-29 16:22:34.631 DEBUG 28236 --- [nio-8080-exec-4] o.s.web.servlet.DispatcherServlet : Completed 200 OK 2025-05-29 16:22:34.744 DEBUG 28236 --- [nio-8080-exec-7] o.s.web.servlet.DispatcherServlet : GET "/KuCun2/fonts/font-awesome-4.7.0/css/font-awesome.min.css", parameters={} 2025-05-29 16:22:34.746 DEBUG 28236 --- [nio-8080-exec-7] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler ["classpath:/jsp/"] 2025-05-29 16:22:34.747 DEBUG 28236 --- [nio-8080-exec-8] o.s.web.servlet.DispatcherServlet : GET "/KuCun2/css/util.css", parameters={} 2025-05-29 16:22:34.748 DEBUG 28236 --- [nio-8080-exec-8] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler ["classpath:/jsp/"] 2025-05-29 16:22:34.758 DEBUG 28236 --- [nio-8080-exec-5] o.s.web.servlet.DispatcherServlet : GET "/KuCun2/js/jquery-3.2.1.min.js", parameters={} 2025-05-29 16:22:34.758 DEBUG 28236 --- [nio-8080-exec-5] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler ["classpath:/jsp/"] 2025-05-29 16:22:34.777 DEBUG 28236 --- [nio-8080-exec-6] o.s.web.servlet.DispatcherServlet : GET "/KuCun2/css/main.css", parameters={} 2025-05-29 16:22:34.778 DEBUG 28236 --- [nio-8080-exec-7] o.s.web.servlet.DispatcherServlet : Completed 200 OK 2025-05-29 16:22:34.779 DEBUG 28236 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : GET "/KuCun2/js/jsyilai.js", parameters={} 2025-05-29 16:22:34.780 DEBUG 28236 --- [nio-8080-exec-2] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler ["classpath:/jsp/"] 2025-05-29 16:22:34.779 DEBUG 28236 --- [nio-8080-exec-6] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler ["classpath:/jsp/"] 2025-05-29 16:22:34.782 DEBUG 28236 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : Completed 200 OK 2025-05-29 16:22:34.786 DEBUG 28236 --- [nio-8080-exec-8] o.s.web.servlet.DispatcherServlet : Completed 200 OK 2025-05-29 16:22:34.787 DEBUG 28236 --- [nio-8080-exec-6] o.s.web.servlet.DispatcherServlet : Completed 200 OK 2025-05-29 16:22:34.799 DEBUG 28236 --- [nio-8080-exec-5] o.s.web.servlet.DispatcherServlet : Completed 200 OK 2025-05-29 16:22:34.854 DEBUG 28236 --- [nio-8080-exec-9] o.s.web.servlet.DispatcherServlet : GET "/KuCun2/images/bg-01.jpg", parameters={} 2025-05-29 16:22:34.855 DEBUG 28236 --- [nio-8080-exec-9] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler ["classpath:/jsp/"] 2025-05-29 16:22:34.859 DEBUG 28236 --- [nio-8080-exec-9] o.s.web.servlet.DispatcherServlet : Completed 200 OK 2025-05-29 16:22:34.905 DEBUG 28236 --- [io-8080-exec-10] o.s.web.servlet.DispatcherServlet : GET "/KuCun2/js/main.js?1748506954900&_=1748506954847", parameters={masked} 2025-05-29 16:22:34.905 DEBUG 28236 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : GET "/KuCun2/js/login.js?1748506954903&_=1748506954848", parameters={masked} 2025-05-29 16:22:34.907 DEBUG 28236 --- [nio-8080-exec-1] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler ["classpath:/jsp/"] 2025-05-29 16:22:34.909 DEBUG 28236 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed 200 OK 2025-05-29 16:22:34.910 DEBUG 28236 --- [io-8080-exec-10] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler ["classpath:/jsp/"] 2025-05-29 16:22:34.914 DEBUG 28236 --- [io-8080-exec-10] o.s.web.servlet.DispatcherServlet : Completed 200 OK package com.kucun.Config; import java.io.IOException; import java.io.InputStream; import java.util.Collections; import java.util.HashMap; import java.util.Map; import javax.json.Json; import javax.servlet.Filter; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.security.authentication.AuthenticationServiceException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.AuthenticationEntryPoint; import org.springframework.security.web.access.AccessDeniedHandler; import org.springframework.security.web.authentication.AuthenticationFailureHandler; import org.springframework.security.web.authentication.AuthenticationSuccessHandler; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import com.fasterxml.jackson.databind.ObjectMapper; import com.kucun.Config.user.CustomUserDetails; // 2. 基础安全配置 @Configuration @EnableWebSecurity // 启用Web安全功能 public class SecurityConfig extends WebSecurityConfigurerAdapter{ @Override public void configure(WebSecurity web) { web.ignoring().antMatchers("/check-session"); } // 添加自定义Controller @RestController public static class SessionCheckController { @GetMapping("/check-session") public ResponseEntity<?> checkSession(HttpServletRequest request) { return request.getSession(false) != null ? ResponseEntity.ok().build() : ResponseEntity.status(HttpStatus.UNAUTHORIZED).build(); } } /** * 核心安全过滤器链配置 * @param http HTTP安全构建器 * @return 安全过滤器链 * @throws Exception 配置异常 * * █ 配置逻辑说明: * 1. authorizeHttpRequests: 定义访问控制规则 * 2. formLogin: 配置表单登录 * 3. logout: 配置注销行为 * 4. exceptionHandling: 处理权限异常[^3] */ // 修正后的配置方法 @Override protected void configure(HttpSecurity http) throws Exception { http .csrf().disable() .sessionManagement() .sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED) .invalidSessionUrl("/login.html?session=invalid") .maximumSessions(1) .maxSessionsPreventsLogin(false) .and() .and() .addFilterBefore(jsonAuthFilter(), UsernamePasswordAuthenticationFilter.class) // 关键配置 .authorizeRequests() .antMatchers("/login.html", "/users/login").permitAll() .antMatchers("/js/**", "/css/**", "/fonts/**", "/images/**").permitAll() .antMatchers("/users/guanli/**").hasAuthority("ROLE_ADMIN") .anyRequest().authenticated() .and() .formLogin().disable() // .loginPage("/login.html") // .loginProcessingUrl("/users/login") // // .successHandler(ajaxAuthenticationSuccessHandler()) // 自定义成功处理器 // .failureHandler(ajaxAuthenticationFailureHandler()) // 自定义失败处理器 // .defaultSuccessUrl("/index.html") // .failureUrl("/login.html?error=true") // .usernameParameter("andy") // 修改用户名参数名 // .passwordParameter("pass") // 修改密码参数名 // .and() .logout() .logoutUrl("/logout") .logoutSuccessUrl("/login.html") .and() .csrf() .ignoringAntMatchers("/users/login") .and() .headers() .frameOptions().sameOrigin() .and() .exceptionHandling() .accessDeniedHandler(accessDeniedHandler()); // 统一使用Handler } // 返回JSON格式的成功响应 @Bean public AuthenticationSuccessHandler ajaxAuthenticationSuccessHandler() { return (request, response, authentication) -> { // 强制创建服务端会话 request.getSession(true); HttpSession session = request.getSession(true); Cookie cookie = new Cookie("JSESSIONID", session.getId()); cookie.setPath("/KuCun2/"); // 明确指定上下文路径 cookie.setMaxAge(1800); // 30分钟 response.addCookie(cookie); //构建安全响应数据 Map<String, Object> responseData = new HashMap<>(); responseData.put("sessionId", request.getSession().getId()); responseData.put("userInfo",Collections.unmodifiableMap(new HashMap<String, Object>() {/** * */ private static final long serialVersionUID = 1L; { put("Name", ((CustomUserDetails)authentication.getPrincipal()).getName()); put("role", ((CustomUserDetails)authentication.getPrincipal()).getRole()); }})); // 统一返回JSON格式 response.setContentType(MediaType.APPLICATION_JSON_VALUE); // new ObjectMapper().writeValue(response.getWriter(), responseData); response.setContentType(MediaType.APPLICATION_JSON_VALUE); CustomUserDetails userDetails = (CustomUserDetails) authentication.getPrincipal(); response.setStatus(HttpStatus.OK.value()); System.out.println(authentication.getPrincipal()+""+authentication.getName()); if (request.getHeader("X-Requested-With") == null) { // 非AJAX请求 response.sendRedirect("/index.html"); } else { //String re=userDetails.getUser().toString() new ObjectMapper().writeValue(response.getWriter(), userDetails.getUser() ); } }; } // 返回401状态码和错误信息 @Bean public AuthenticationFailureHandler ajaxAuthenticationFailureHandler() { return (request, response, exception) -> { if (request.getHeader("X-Requested-With") == null) { response.sendRedirect("/login.html?error=true"); } else { response.setStatus(HttpStatus.UNAUTHORIZED.value()); response.getWriter().write("{\"error\":\"Authentication failed\"}"); } }; } // 处理未认证请求 @Bean public AuthenticationEntryPoint ajaxAuthenticationEntryPoint() { return (request, response, exception) -> { if (request.getHeader("X-Requested-With") == null) { response.sendRedirect("/login.html?error=true"); } else { response.setStatus(HttpStatus.UNAUTHORIZED.value()); response.getWriter().write("{\"error\":\"Authentication failed\"}"); } }; } @Bean public JsonUsernamePasswordAuthenticationFilter jsonAuthFilter() throws Exception { JsonUsernamePasswordAuthenticationFilter filter = new JsonUsernamePasswordAuthenticationFilter(); filter.setAuthenticationManager(authenticationManagerBean()); filter.setUsernameParameter("andy"); // 设置自定义参数名 filter.setPasswordParameter("pass"); filter.setFilterProcessesUrl("/users/login"); filter.setAuthenticationSuccessHandler(ajaxAuthenticationSuccessHandler()); filter.setAuthenticationFailureHandler(ajaxAuthenticationFailureHandler()); return filter; } /** * 密码编码器(必须配置) * 使用BCrypt强哈希算法加密 */ @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Bean public AccessDeniedHandler accessDeniedHandler() { System.out.println("0000"); return (request, response, ex) -> { if (!response.isCommitted()) { response.sendRedirect("/error/403"); } }; } } class JsonUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter { private final ObjectMapper objectMapper = new ObjectMapper(); @Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException { System.out.println("收到认证请求,路径:" + request.getRequestURI()); System.out.println("请求方法:" + request.getMethod()); System.out.println("Content-Type:" + request.getContentType()); if (request.getContentType() != null && request.getContentType().startsWith(MediaType.APPLICATION_JSON_VALUE)) { try (InputStream is = request.getInputStream()) { Map<String, String> authMap = objectMapper.readValue(is, Map.class); String username = authMap.getOrDefault(getUsernameParameter(), ""); String password = authMap.getOrDefault(getPasswordParameter(), ""); // 调试日志 System.out.println("Authentication attempt with: " + username+&#39;_&#39;+ password); UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password); setDetails(request, authRequest); return this.getAuthenticationManager().authenticate(authRequest); } catch (IOException e) { throw new AuthenticationServiceException("认证请求解析失败", e); } } Authentication aut= super.attemptAuthentication(request, response); System.out.println("结果:"+aut.isAuthenticated()); return aut; } }
最新发布
05-30
<think>好的,用户提供了最新的日志和代码,并询问为什么登录后仍然重定向到登录页面。我需要仔细分析问题原因,并给出解决方案。首先,用户之前的问题是关于AJAX请求未携带Cookie导致的重定向问题,现在用户已经按照建议修改了代码,但问题依然存在。查看最新的日志,发现用户实现了`/check-session`端点,并且Cookie路径已设置为`/KuCun2/`。然而,日志显示`/check-session`请求返回了200,但随后又出现了对`/login.html`的请求,说明前端仍然触发了重定向。接下来,我需要检查用户提供的代码。在`SecurityConfig`中,用户添加了`SessionCheckController`,并且配置了`web.ignoring().antMatchers("/check-session");`,这可能导致该端点绕过Spring Security的过滤器链,但可能未正确处理会话验证。此外,`ajaxAuthenticationSuccessHandler`中设置了Cookie路径为`/KuCun2/`,但可能前端在检查会话时未正确发送Cookie,或者后端会话未正确创建。 观察日志中的关键点:用户登录成功后,`/check-session`返回200,但随后又请求了`/login.html`,这说明前端可能仍然认为会话无效。需要检查前端代码中的会话检查逻辑是否正确处理了响应,以及Cookie是否被正确发送。 另一个可能的原因是`SessionCreationPolicy`设置为`IF_REQUIRED`,这意味着只有在需要时才会创建会话。如果某些请求未触发会话创建,可能导致会话未被正确维护。此外,检查`SecurityConfig`中的权限配置,确保所有必要的路径都被正确允许访问,特别是静态资源路径和`/check-session`端点。 可能的问题点包括:Cookie设置是否正确,会话管理策略是否合适,前端AJAX请求是否携带Cookie,以及权限配置是否存在冲突。需要逐一排查这些方面,找出导致重定向的根本原因。</think>根据最新代码和日志分析,**登录后仍重定向的根本原因在于会话 Cookie 未正确传递到后续请求**。以下是具体分析和解决方案: --- ### **问题原因** 1. **Cookie 作用域冲突** - 代码中设置 `cookie.setPath("/KuCun2/")`,但实际访问路径为 `/KuCun2`(无末尾斜杠),导致浏览器不发送 Cookie。 2. **会话创建策略缺陷** - `sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)` 导致部分请求未创建会话。 3. **静态资源权限覆盖** - `web.ignoring().antMatchers("/check-session")` 使健康检查端点绕过安全过滤器链。 --- ### **解决方案** #### 1. 修正 Cookie 路径(后端) 修改 Cookie 路径为应用根路径(兼容带/不带斜杠的请求): ```java @Bean public AuthenticationSuccessHandler ajaxAuthenticationSuccessHandler() { return (request, response, authentication) -> { Cookie cookie = new Cookie("JSESSIONID", request.getSession(true).getId()); cookie.setPath(request.getContextPath() + "/"); // 动态获取上下文路径 cookie.setMaxAge(1800); response.addCookie(cookie); // 返回用户信息... }; } ``` #### 2. 强制会话创建策略 修改会话管理配置为必须创建会话: ```java @Override protected void configure(HttpSecurity http) throws Exception { http .sessionManagement() .sessionCreationPolicy(SessionCreationPolicy.ALWAYS) // 强制创建会话 .invalidSessionUrl("/login.html?session=invalid") .maximumSessions(1) .maxSessionsPreventsLogin(false); } ``` #### 3. 调整安全过滤规则 移除 `web.ignoring()` 配置,改为显式权限控制: ```java @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/check-session").permitAll() // 显式放行 .antMatchers("/login.html", "/users/login").permitAll() // 其他配置... } ``` --- ### **前端关键修正** 修改 `checkLoginStatus` 方法确保携带 Cookie: ```javascript function checkLoginStatus() { fetch(&#39;/KuCun2/check-session&#39;, { credentials: &#39;include&#39;, // 强制携带 Cookie headers: { "X-Requested-With": "XMLHttpRequest" // 标识为 AJAX 请求 } }).then(response => { if (response.status === 401) { window.location.href = &#39;/KuCun2/login.html&#39;; } }); } ``` --- ### **验证指标** | 检查项 | 预期结果 | 验证方法 | |--------------------------|----------------------------|----------------------------| | `/check-session` 响应码 | 200 OK | 浏览器开发者工具 Network 面板 | | Cookie 路径 | `/KuCun2/` | Application 面板 Cookies 项 | | 后续请求的 Cookie 头 | 包含 JSESSIONID | 请求头检查 | | 静态资源请求响应码 | 200 OK | 日志监控 | --- ### **技术原理说明** 1. **Cookie 路径匹配规则** - 浏览器根据 `Path` 属性决定是否发送 Cookie- `/KuCun2/`:匹配 `/KuCun2/*` 的所有请求 - `/KuCun2`:仅匹配精确路径 2. **SessionCreationPolicy 策略** - `ALWAYS`:无论是否需要都创建会话 - `IF_REQUIRED`:仅当需要安全操作时创建(易导致会话丢失) --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值