javax.servlet.http.Cookie.setHttpOnly(Z)V

本文介绍Servlet 3.0中对Cookie的改进,包括直接修改SessionID名称、设置HttpOnly属性等,并提供了一个使用SessionCookieConfig接口的示例。

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

java.lang.NoSuchMethodError: javax.servlet.http.Cookie.setHttpOnly(Z)V
使用tomcat6 转换为7 即可

在Servlet 3.0中增加对Cookie(请注意,这里所说的Cookie,仅指和Session互动的Cookie,即人们常说的会话Cookie)较为全面的操作API。最为突出特性:支持直接修改Session ID的名称(默认为“JSESSIONID”),支持对cookie设置HttpOnly属性以增强安全,避免一定程度的跨站攻击。


利用拦截器实现,判断每次请求的响应是否包含SET-COOKIE头部,重写会话Cookie,添加需要的属性。虽较为生硬,但灵活性强。
新的规范API
新的规范添加SessionCookieConfig接口,用于操作会话Cookie,需要掌握以下主要方法:

setName(String name)
修改Session ID的名称,默认为"JSESSIONID"
setDomain(String domain)
设置当前Cookie所处于的域
setPath(String path)
设置当前Cookie所处于的相对路径
setHttpOnly(boolean httpOnly)
设置是否支持HttpOnly属性
setSecure(boolean secure)
若使用HTTPS安全连接,则需要设置其属性为true
setMaxAge(int maxAge)
设置存活时间,单位为秒

如何使用呢,很方便,在ServletContextListener监听器初始化方法中进行设定即可;下面实例演示如何修改"JSESSIONID",以及添加支持HttpOnly支持:

/** 全局设置Session-Cookie相交互部分属性
*
* @author yongboy
* @date 2011-1-19
* @version 1.0
*/
@WebListener
public class SessionCookieInitialization implements ServletContextListener {
private static final Log log = LogFactory
.getLog(SessionCookieInitialization.class);

public void contextInitialized(ServletContextEvent sce) {
log.info("now init the Session Cookie");

ServletContext servletContext = sce.getServletContext();

SessionCookieConfig sessionCookie = servletContext
.getSessionCookieConfig();
sessionCookie.setName("YONGBOYID");
sessionCookie.setPath(servletContext.getContextPath());
sessionCookie.setHttpOnly(true);
sessionCookie.setSecure(false);

log.info("name : " + sessionCookie.getName() + "\n" + "domain:"
+ sessionCookie.getDomain() + "\npath:"
+ sessionCookie.getPath() + "\nage:"
+ sessionCookie.getMaxAge());

log.info("isHttpOnly : " + sessionCookie.isHttpOnly());
log.info("isSecure : " + sessionCookie.isSecure());
}

public void contextDestroyed(ServletContextEvent sce) {
log.info("the context is destroyed !");
}
}

需要通过ServletContext对象获得SessionCookieConfig对象,才能够进一步自定义session cookie的名字等属性。
无论以前的硬编码还是新的API实现,目标都是一致的,所产生头部信息也是完全一致。毫无疑问,后者更为方便快捷,省缺了显示的操作响应元数据。
对当前站点的第一次请求,很容易从响应头信息中看到Set-Cookie的属性值:

image


不同浏览器平台上测试

在Safari、IE8、Opera 11 一切都很正常
Firefox 3.6、Chrome 9.0,JSESSIONID会继续存在:

YONGBOYID=601A6C82D535343163B175A4FD5376EA; JSESSIONID=AA78738AB1EAD1F9C649F705EC64D92D; AJSTAT_ok_times=6; JSESSIONID=abcpxyJmIpBVz6WHVo_1s; BAYEUX_BROWSER=439-1vyje1gmqt8y8giva7pqsu1

在所有浏览器中,SESSION ID等于新设置的YONGBOYID值(若不相等,问题就严重了!)
在客户端JS无法获得正确的SESSIONI ID了。

Tomcat服务器内置支持

在Tomcat 6-7,可以不用如上显示设置Cookie domain、name、HttpOnly支持,在conf/context.xml文件中配置即可:

<Context useHttpOnly="true", sessionCookieName="YONGBOYID", sessionCookieDomain="/servlet3" … >
...
</Context>

既然JAVA应用服务器本身支持会话Cookie设定,那就没有必要在程序代码中再次进行编码了。这是一个好的实践:不要重复造轮子。
这里给出一段测试Session重写的一段脚本:

<div style="margin: 40px; paddding: 10px">
<div><a href="sessionCookieTest">正常连接</a></div>
<div><a href="<%=response.encodeURL("sessionCookieTest") %>">重定向连接</a></div>
</div>

会被重写的URL地址类似于:

http://localhost/servlet3/sessionCookieTest;YONGBOYID=19B94935D50245270060E49C9E69F5B6

嗯,在取消会话Cookie之后,可以直接看到修改后的SESSION ID名称了,当然这时候HttpOnly属性也没有多大意义了。
有一点别忘记,设置HttpOnly之后,客户端的JS将无法获取的到会话ID了。
进阶阅读:

维基对HttpOnly的解释
利用HTTP-only Cookie缓解XSS之痛
Tomcat Context 属性
HttpOnly cookie与跨站点追踪

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.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.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 com.fasterxml.jackson.databind.ObjectMapper; import com.kucun.Config.user.CustomUserDetails; // 2. 基础安全配置 @Configuration @EnableWebSecurity // 启用Web安全功能 public class SecurityConfig extends WebSecurityConfigurerAdapter{ /** * 核心安全过滤器链配置 * @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); session.setMaxInactiveInterval(1800); // 30分钟过期 // 将会话 ID 写入响应头 Cookie cookie = new Cookie("JSESSIONID", session.getId()); cookie.setPath("/"); cookie.setHttpOnly(true); 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+'_'+ 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; } } package com.kucun.Config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.stereotype.Service; import com.kucun.Config.Role.RoleConverter; import com.kucun.Config.user.CustomUserDetails; import com.kucun.data.entity.User; import com.kucun.dataDo.UserRepository; /** * 获取数据 * @author Administrator * */ @Service public class CustomUserDetailsService implements UserDetailsService { @Autowired private UserRepository userRepository; @Autowired private RoleConverter roleConverter; public CustomUserDetailsService() { super(); System.out.println("11111"); } /** * 获取数据库中用户信息 * @param andy 账号 * * @return * */ @Override public UserDetails loadUserByUsername(String andy) { System.out.println(andy); User user = userRepository.findByAndy(andy); System.out.println(user); return new CustomUserDetails(user, roleConverter.convert(user.getRole()) // 关键转换点[^1] ); } }package com.kucun.Config.user; import java.util.Collection; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import com.kucun.data.entity.User; public class CustomUserDetails implements UserDetails { /** * */ private static final long serialVersionUID = 1L; private final String andy; // 对应andy字段 private final String name; private final int role; private final String password; private final User users; private final Collection<? extends GrantedAuthority> authorities; public CustomUserDetails(User user, Collection<? extends GrantedAuthority> authorities) { this.andy = user.getAndy(); this.name = user.getName(); this.role = user.getRole(); this.password = user.getPass(); user.setPass(null); this.users=user; this.authorities = authorities; } // 实现UserDetails接口方法 @Override public String getUsername() { return andy; } @Override public String getPassword() { return password; } @Override public Collection<? extends GrantedAuthority> getAuthorities() { return authorities; } // 自定义字段访问方法 public String getName() { return name; } public User getUser() { return users; } public int getRole() { return role; } // 其他必要方法 @Override public boolean isAccountNonExpired() { return true; } @Override public boolean isAccountNonLocked() { return true; } @Override public boolean isCredentialsNonExpired() { return true; } @Override public boolean isEnabled() { return true; } } function https(url,data,fu){ $.ajax({ contentType:"application/json", url: url, // 假设后端 API 地址 method: "POST", data: JSON.stringify(data), type: "json", success:fu, error: function (e) { console.error(e) alert("请求失败,请稍后再试!"+e); } }); } function checkLoginStatus() { if (window.location.href.includes('/login.html')) return; const username = localStorage.getItem("name"); if (!username) { window.location.href = '/KuCun2/login.html'; return; } // 检查会话是否有效 fetch('/KuCun2/check-session', { credentials: 'include' // 强制携带 Cookie }).then(response => { if (!response.ok) { localStorage.removeItem("name"); window.location.href = '/KuCun2/login.html'; } }); } function deepMergeArrays(frontend, backend) { const resultMap = new Map(); // 遍历前端数据并存入 Map 中以便快速查找 frontend.forEach(item => resultMap.set(item.id, { ...item })); // 遍历后端数据并与前端数据进行合并 backend.forEach(item => { if (resultMap.has(item.id)) { // 如果存在相同 ID,则合并两者的内容 resultMap.set( item.id, Object.assign(resultMap.get(item.id), item) ); } else { // 如果不存在相同 ID,则新增该条目 resultMap.set(item.id, { ...item }); } }); // 将最终结果转回数组形式 return Array.from(resultMap.values()); } (function ($){ // 页面加载时检查登录状态 checkLoginStatus(); })(jQuery); function removeSpecificCharactersAndConvertToNumber(str, charsToRemove) { const regex = new RegExp(`[${charsToRemove}]`, 'g'); // 创建用于匹配指定字符的正则表达式 const cleanedStr = str.replace(regex, ''); // 移除指定字符 const numberValue = parseFloat(cleanedStr); // 转换为浮点数 return isNaN(numberValue) ? null : numberValue; // 如果无法解析,则返回 null } /// <reference path="jquery.d.ts" /> // $(document).ready(function(){ // $("#submit").click(function(){ // // // $.ajax({ // url:"../users/login", // async:false, // data:JSON.stringify({ // andy:$("#andy").val(), // pass:$("#pass").val(), // name:$("#name").val()}), // type:"post", // contentType:"application/json", // success:function(e){ // alert(e) // } // }); // // // }); // }) (function ($) { "use strict"; /*================================================================== [ Focus Contact2 ]*/ $('.input100').each(function () { $(this).on('blur', function () { if ($(this).val().trim() != "") { $(this).addClass('has-val'); } else { $(this).removeClass('has-val'); } }) }) /*================================================================== [ Validate ]*/ var input = $('.validate-input .input100'); $('.validate-form').on('submit', function (e) { e.preventDefault(); var check = true; for (var i = 0; i < input.length; i++) { if (validate(input[i]) == false) { showValidate(input[i]); check = false; } } if(check) login(input); return check; }); $('.validate-form .input100').each(function () { $(this).focus(function () { hideValidate(this); }); }); function validate(input) { if ($(input).attr('type') == 'email' || $(input).attr('name') == 'email') { if ($(input).val().trim().match(/^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{1,5}|[0-9]{1,3})(\]?)$/) == null) { return false; } } else { if ($(input).val().trim() == '') { return false; } } } function showValidate(input) { var thisAlert = $(input).parent(); alert(input) $(thisAlert).addClass('alert-validate'); } function hideValidate(input) { var thisAlert = $(input).parent(); $(thisAlert).removeClass('alert-validate'); } // 登录按钮点击事件 function login(datas) { var data={} datas.each(function(a,element){ alert() data[$(element).attr('name')]=$(element).val() }) //var data={ andy,pass } // 模拟 AJAX 请求 https("/KuCun2/users/login",data,function (response) { alert("1"); if (response.name) { localStorage.setItem("name", response.name); // 保存用户名到本地存储 localStorage.setItem("role", response.role); // 保存权限到本地存储 alert( response) window.location.href = '/KuCun2/index.html'; } else { alert("登录失败,请检查用户名和密码!"); } }) }; // 注销按钮点击事件 $("#logout-btn").click(function () { localStorage.removeItem("name"); // 清除本地存储中的用户名 checkLoginStatus(); // 更新登录状态 }); })(jQuery);收到认证请求,路径:/KuCun2/users/login 请求方法:POST Content-Type:application/json Authentication attempt with: 123456_987987 123456 2025-05-29 16:10:16.245 DEBUG 33108 --- [nio-8080-exec-7] 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@5d3a4533123456 0 2025-05-29 16:10:34.013 DEBUG 33108 --- [nio-8080-exec-8] o.s.web.servlet.DispatcherServlet : GET "/KuCun2/index.html", parameters={} 2025-05-29 16:10:34.019 DEBUG 33108 --- [nio-8080-exec-8] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler ["classpath:/jsp/"] 2025-05-29 16:10:34.036 DEBUG 33108 --- [nio-8080-exec-8] o.s.web.servlet.DispatcherServlet : Completed 200 OK 2025-05-29 16:10:34.077 DEBUG 33108 --- [nio-8080-exec-4] o.s.web.servlet.DispatcherServlet : GET "/KuCun2/fonts/font-awesome-4.7.0/css/font-awesome.min.css", parameters={} 2025-05-29 16:10:34.078 DEBUG 33108 --- [nio-8080-exec-4] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler ["classpath:/jsp/"] 2025-05-29 16:10:34.084 DEBUG 33108 --- [nio-8080-exec-4] o.s.web.servlet.DispatcherServlet : Completed 200 OK 2025-05-29 16:10:34.094 DEBUG 33108 --- [nio-8080-exec-9] o.s.web.servlet.DispatcherServlet : GET "/KuCun2/css/util.css", parameters={} 2025-05-29 16:10:34.094 DEBUG 33108 --- [nio-8080-exec-9] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler ["classpath:/jsp/"] 2025-05-29 16:10:34.098 DEBUG 33108 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : GET "/KuCun2/css/main.css", parameters={} 2025-05-29 16:10:34.099 DEBUG 33108 --- [nio-8080-exec-1] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler ["classpath:/jsp/"] 2025-05-29 16:10:34.101 DEBUG 33108 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed 200 OK 2025-05-29 16:10:34.103 DEBUG 33108 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : GET "/KuCun2/css/index2.css", parameters={} 2025-05-29 16:10:34.105 DEBUG 33108 --- [nio-8080-exec-1] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler ["classpath:/jsp/"] 2025-05-29 16:10:34.108 DEBUG 33108 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed 200 OK 2025-05-29 16:10:34.112 DEBUG 33108 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : GET "/KuCun2/js/jquery-3.2.1.min.js", parameters={} 2025-05-29 16:10:34.120 DEBUG 33108 --- [nio-8080-exec-1] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler ["classpath:/jsp/"] 2025-05-29 16:10:34.117 DEBUG 33108 --- [nio-8080-exec-5] o.s.web.servlet.DispatcherServlet : GET "/KuCun2/js/jsyilai.js", parameters={} 2025-05-29 16:10:34.124 DEBUG 33108 --- [nio-8080-exec-5] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler ["classpath:/jsp/"] 2025-05-29 16:10:34.145 DEBUG 33108 --- [nio-8080-exec-5] o.s.web.servlet.DispatcherServlet : Completed 200 OK 2025-05-29 16:10:34.160 DEBUG 33108 --- [nio-8080-exec-9] o.s.web.servlet.DispatcherServlet : Completed 200 OK 2025-05-29 16:10:34.160 DEBUG 33108 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed 200 OK 2025-05-29 16:10:34.279 DEBUG 33108 --- [nio-8080-exec-6] o.s.web.servlet.DispatcherServlet : GET "/KuCun2/main/index.html", parameters={} 2025-05-29 16:10:34.280 DEBUG 33108 --- [nio-8080-exec-6] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler ["classpath:/jsp/"] 2025-05-29 16:10:34.283 DEBUG 33108 --- [nio-8080-exec-6] o.s.web.servlet.DispatcherServlet : Completed 200 OK 2025-05-29 16:10:34.349 DEBUG 33108 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : GET "/KuCun2/main/bootstrap-3.3.7-dist/js/MyTable.js", parameters={} 2025-05-29 16:10:34.350 DEBUG 33108 --- [nio-8080-exec-2] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler ["classpath:/jsp/"] 2025-05-29 16:10:34.354 DEBUG 33108 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : Completed 200 OK 2025-05-29 16:10:34.351 DEBUG 33108 --- [io-8080-exec-10] o.s.web.servlet.DispatcherServlet : GET "/KuCun2/js/main.js?1748506234337&_=1748506234307", parameters={masked} 2025-05-29 16:10:34.356 DEBUG 33108 --- [io-8080-exec-10] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler ["classpath:/jsp/"] 2025-05-29 16:10:34.356 DEBUG 33108 --- [nio-8080-exec-8] o.s.web.servlet.DispatcherServlet : GET "/KuCun2/js/index.js?1748506234340&_=1748506234308", parameters={masked} 2025-05-29 16:10:34.357 DEBUG 33108 --- [nio-8080-exec-8] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler ["classpath:/jsp/"] 2025-05-29 16:10:34.358 DEBUG 33108 --- [io-8080-exec-10] o.s.web.servlet.DispatcherServlet : Completed 200 OK 2025-05-29 16:10:34.359 DEBUG 33108 --- [nio-8080-exec-8] o.s.web.servlet.DispatcherServlet : Completed 200 OK 2025-05-29 16:10:34.448 DEBUG 33108 --- [nio-8080-exec-4] o.s.web.servlet.DispatcherServlet : GET "/KuCun2/check-session", parameters={} 2025-05-29 16:10:34.449 DEBUG 33108 --- [nio-8080-exec-4] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler ["classpath:/jsp/"] 2025-05-29 16:10:34.450 DEBUG 33108 --- [nio-8080-exec-4] o.s.w.s.r.ResourceHttpRequestHandler : Resource not found 2025-05-29 16:10:34.450 DEBUG 33108 --- [nio-8080-exec-4] o.s.web.servlet.DispatcherServlet : Completed 404 NOT_FOUND 2025-05-29 16:10:34.451 DEBUG 33108 --- [nio-8080-exec-4] o.s.web.servlet.DispatcherServlet : "FORWARD" dispatch for GET "/KuCun2/error", parameters={} 2025-05-29 16:10:34.451 DEBUG 33108 --- [nio-8080-exec-4] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController#error(HttpServletRequest) 2025-05-29 16:10:34.455 DEBUG 33108 --- [nio-8080-exec-4] o.s.w.s.m.m.a.HttpEntityMethodProcessor : Using 'application/json', given [*/*] and supported [application/json, application/*+json, application/json, application/*+json] 2025-05-29 16:10:34.456 DEBUG 33108 --- [nio-8080-exec-4] o.s.w.s.m.m.a.HttpEntityMethodProcessor : Writing [{timestamp=Thu May 29 16:10:34 CST 2025, status=404, error=Not Found, message=, path=/KuCun2/check-s (truncated)...] 2025-05-29 16:10:34.456 DEBUG 33108 --- [nio-8080-exec-4] o.s.web.servlet.DispatcherServlet : Exiting from "FORWARD" dispatch, status 404 2025-05-29 16:10:34.754 DEBUG 33108 --- [nio-8080-exec-7] o.s.web.servlet.DispatcherServlet : GET "/KuCun2/main/bootstrap-3.3.7-dist/css/bootstrap.css.map", parameters={} 2025-05-29 16:10:34.754 DEBUG 33108 --- [nio-8080-exec-7] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler ["classpath:/jsp/"] 2025-05-29 16:10:34.758 DEBUG 33108 --- [nio-8080-exec-7] o.s.w.s.r.ResourceHttpRequestHandler : Resource not found 2025-05-29 16:10:34.758 DEBUG 33108 --- [nio-8080-exec-7] o.s.web.servlet.DispatcherServlet : Completed 404 NOT_FOUND 2025-05-29 16:10:34.765 DEBUG 33108 --- [nio-8080-exec-3] o.s.web.servlet.DispatcherServlet : GET "/KuCun2/login.html", parameters={} 2025-05-29 16:10:34.768 DEBUG 33108 --- [nio-8080-exec-3] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler ["classpath:/jsp/"] 2025-05-29 16:10:34.770 DEBUG 33108 --- [nio-8080-exec-3] o.s.web.servlet.DispatcherServlet : Completed 200 OK 2025-05-29 16:10:34.763 DEBUG 33108 --- [nio-8080-exec-7] o.s.web.servlet.DispatcherServlet : "FORWARD" dispatch for GET "/KuCun2/error", parameters={} 2025-05-29 16:10:34.773 DEBUG 33108 --- [nio-8080-exec-7] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController#error(HttpServletRequest) 2025-05-29 16:10:34.773 DEBUG 33108 --- [nio-8080-exec-7] o.s.w.s.m.m.a.HttpEntityMethodProcessor : Using 'application/json', given [*/*] and supported [application/json, application/*+json, application/json, application/*+json] 2025-05-29 16:10:34.773 DEBUG 33108 --- [nio-8080-exec-7] o.s.w.s.m.m.a.HttpEntityMethodProcessor : Writing [{timestamp=Thu May 29 16:10:34 CST 2025, status=404, error=Not Found, message=, path=/KuCun2/main/bo (truncated)...] 2025-05-29 16:10:34.787 DEBUG 33108 --- [nio-8080-exec-7] o.s.web.servlet.DispatcherServlet : Exiting from "FORWARD" dispatch, status 404 2025-05-29 16:10:34.823 DEBUG 33108 --- [nio-8080-exec-5] o.s.web.servlet.DispatcherServlet : GET "/KuCun2/login.html", parameters={} 2025-05-29 16:10:34.824 DEBUG 33108 --- [nio-8080-exec-5] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler ["classpath:/jsp/"] 2025-05-29 16:10:34.829 DEBUG 33108 --- [nio-8080-exec-5] o.s.web.servlet.DispatcherServlet : Completed 200 OK 2025-05-29 16:10:34.984 DEBUG 33108 --- [nio-8080-exec-9] o.s.web.servlet.DispatcherServlet : GET "/KuCun2/fonts/font-awesome-4.7.0/css/font-awesome.min.css", parameters={} 2025-05-29 16:10:34.985 DEBUG 33108 --- [nio-8080-exec-9] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler ["classpath:/jsp/"] 2025-05-29 16:10:34.986 DEBUG 33108 --- [nio-8080-exec-6] o.s.web.servlet.DispatcherServlet : GET "/KuCun2/css/main.css", parameters={} 2025-05-29 16:10:34.986 DEBUG 33108 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : GET "/KuCun2/css/util.css", parameters={} 2025-05-29 16:10:34.987 DEBUG 33108 --- [nio-8080-exec-6] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler ["classpath:/jsp/"] 2025-05-29 16:10:34.987 DEBUG 33108 --- [nio-8080-exec-1] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler ["classpath:/jsp/"] 2025-05-29 16:10:34.991 DEBUG 33108 --- [nio-8080-exec-6] o.s.web.servlet.DispatcherServlet : Completed 200 OK 2025-05-29 16:10:34.994 DEBUG 33108 --- [nio-8080-exec-6] o.s.web.servlet.DispatcherServlet : GET "/KuCun2/js/jquery-3.2.1.min.js", parameters={} 2025-05-29 16:10:34.994 DEBUG 33108 --- [nio-8080-exec-6] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler ["classpath:/jsp/"] 2025-05-29 16:10:35.009 DEBUG 33108 --- [nio-8080-exec-9] o.s.web.servlet.DispatcherServlet : Completed 200 OK 2025-05-29 16:10:35.011 DEBUG 33108 --- [io-8080-exec-10] o.s.web.servlet.DispatcherServlet : GET "/KuCun2/js/jsyilai.js", parameters={} 2025-05-29 16:10:35.013 DEBUG 33108 --- [io-8080-exec-10] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler ["classpath:/jsp/"] 2025-05-29 16:10:35.019 DEBUG 33108 --- [io-8080-exec-10] o.s.web.servlet.DispatcherServlet : Completed 200 OK 2025-05-29 16:10:35.020 DEBUG 33108 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed 200 OK 2025-05-29 16:10:35.024 DEBUG 33108 --- [nio-8080-exec-6] o.s.web.servlet.DispatcherServlet : Completed 200 OK 2025-05-29 16:10:35.105 DEBUG 33108 --- [nio-8080-exec-8] o.s.web.servlet.DispatcherServlet : GET "/KuCun2/images/bg-01.jpg", parameters={} 2025-05-29 16:10:35.106 DEBUG 33108 --- [nio-8080-exec-8] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler ["classpath:/jsp/"] 2025-05-29 16:10:35.110 DEBUG 33108 --- [nio-8080-exec-8] o.s.web.servlet.DispatcherServlet : Completed 200 OK 2025-05-29 16:10:35.123 DEBUG 33108 --- [nio-8080-exec-4] o.s.web.servlet.DispatcherServlet : GET "/KuCun2/js/main.js?1748506235115&_=1748506235076", parameters={masked} 2025-05-29 16:10:35.123 DEBUG 33108 --- [nio-8080-exec-4] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler ["classpath:/jsp/"] 2025-05-29 16:10:35.125 DEBUG 33108 --- [nio-8080-exec-4] o.s.web.servlet.DispatcherServlet : Completed 200 OK 2025-05-29 16:10:35.127 DEBUG 33108 --- [nio-8080-exec-4] o.s.web.servlet.DispatcherServlet : GET "/KuCun2/js/login.js?1748506235119&_=1748506235077", parameters={masked} 2025-05-29 16:10:35.128 DEBUG 33108 --- [nio-8080-exec-4] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler ["classpath:/jsp/"] 2025-05-29 16:10:35.130 DEBUG 33108 --- [nio-8080-exec-4] o.s.web.servlet.DispatcherServlet : Completed 200 OK
最新发布
05-31
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.ALWAYS) .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/**","/check-session","/main/bootstrap-3.3.7-dist/**").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); String contextPath = request.getContextPath(); HttpSession session = request.getSession(true); Cookie cookie = new Cookie("JSESSIONID", session.getId()); cookie.setPath(contextPath.isEmpty() ? "/" : contextPath + "/"); 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+'_'+ 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; } } package com.kucun.Config.Role; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.PostConstruct; import javax.json.Json; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.stereotype.Component; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; /** * 权限转化 * @author Administrator * */ @Component public class RoleConverter { private static final Map<Integer, String> ROLE_MAP = new HashMap<>(); @PostConstruct public void init() { ROLE_MAP.put(0, "ROLE_ADMIN"); ROLE_MAP.put(1, "ROLE_USER"); ROLE_MAP.put(2, "ROLE_MANAGER"); ROLE_MAP.put(3, "ROLE_AUDITOR"); } public List<GrantedAuthority> convert(int roleCode) { ObjectMapper mapper = new ObjectMapper(); try { System.out.println(mapper.writeValueAsString(Collections.singletonList( new SimpleGrantedAuthority(ROLE_MAP.getOrDefault(roleCode, "ROLE_GUEST")))).toString());//输出[{"authority":"ROLE_ADMIN"}] } catch (JsonProcessingException e) { // TODO Auto-generated catch block e.printStackTrace(); } return Collections.singletonList( new SimpleGrantedAuthority(ROLE_MAP.getOrDefault(roleCode, "ROLE_GUEST")) ); } } function https(url,data,fu){ $.ajax({ contentType:"application/json", url: url, // 假设后端 API 地址 method: "POST", data: JSON.stringify(data), type: "json", success:fu, error: function (e) { console.error(e) alert("请求失败,请稍后再试!"+e); } }); } function checkLoginStatus() { if (window.location.href.includes('/login.html')) return; const username = localStorage.getItem("name"); if (!username) { window.location.href = '/KuCun2/login.html'; alert("meijin") return; } // 检查会话是否有效 fetch('/KuCun2/check-session', { headers: { "X-Requested-With": "XMLHttpRequest", // 显式添加头 "Content-Type": "application/json" }, credentials: 'include' // 强制携带 Cookie }).then(response => { if (!response.ok) { localStorage.removeItem("name"); alert("meijin2") window.location.href = '/KuCun2/login.html'; alert("meijin3") } }); } function deepMergeArrays(frontend, backend) { const resultMap = new Map(); // 遍历前端数据并存入 Map 中以便快速查找 frontend.forEach(item => resultMap.set(item.id, { ...item })); // 遍历后端数据并与前端数据进行合并 backend.forEach(item => { if (resultMap.has(item.id)) { // 如果存在相同 ID,则合并两者的内容 resultMap.set( item.id, Object.assign(resultMap.get(item.id), item) ); } else { // 如果不存在相同 ID,则新增该条目 resultMap.set(item.id, { ...item }); } }); // 将最终结果转回数组形式 return Array.from(resultMap.values()); } (function ($){ // 页面加载时检查登录状态 checkLoginStatus(); })(jQuery); function removeSpecificCharactersAndConvertToNumber(str, charsToRemove) { const regex = new RegExp(`[${charsToRemove}]`, 'g'); // 创建用于匹配指定字符的正则表达式 const cleanedStr = str.replace(regex, ''); // 移除指定字符 const numberValue = parseFloat(cleanedStr); // 转换为浮点数 return isNaN(numberValue) ? null : numberValue; // 如果无法解析,则返回 null } /// <reference path="jquery.d.ts" /> // $(document).ready(function(){ // $("#submit").click(function(){ // // // $.ajax({ // url:"../users/login", // async:false, // data:JSON.stringify({ // andy:$("#andy").val(), // pass:$("#pass").val(), // name:$("#name").val()}), // type:"post", // contentType:"application/json", // success:function(e){ // alert(e) // } // }); // // // }); // }) (function ($) { "use strict"; /*================================================================== [ Focus Contact2 ]*/ $('.input100').each(function () { $(this).on('blur', function () { if ($(this).val().trim() != "") { $(this).addClass('has-val'); } else { $(this).removeClass('has-val'); } }) }) /*================================================================== [ Validate ]*/ var input = $('.validate-input .input100'); $('.validate-form').on('submit', function (e) { e.preventDefault(); var check = true; for (var i = 0; i < input.length; i++) { if (validate(input[i]) == false) { showValidate(input[i]); check = false; } } if(check) login(input); return check; }); $('.validate-form .input100').each(function () { $(this).focus(function () { hideValidate(this); }); }); function validate(input) { if ($(input).attr('type') == 'email' || $(input).attr('name') == 'email') { if ($(input).val().trim().match(/^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{1,5}|[0-9]{1,3})(\]?)$/) == null) { return false; } } else { if ($(input).val().trim() == '') { return false; } } } function showValidate(input) { var thisAlert = $(input).parent(); alert(input) $(thisAlert).addClass('alert-validate'); } function hideValidate(input) { var thisAlert = $(input).parent(); $(thisAlert).removeClass('alert-validate'); } // 登录按钮点击事件 function login(datas) { var data={} datas.each(function(a,element){ alert() data[$(element).attr('name')]=$(element).val() }) //var data={ andy,pass } // 模拟 AJAX 请求 https("/KuCun2/users/login",data,function (response) { alert("1"); if (response.name) { localStorage.setItem("name", response.name); // 保存用户名到本地存储 localStorage.setItem("role", response.role); // 保存权限到本地存储 alert( response) //window.location.href = '/KuCun2/index.html'; } else { alert("登录失败,请检查用户名和密码!"); } }) }; // 注销按钮点击事件 $("#logout-btn").click(function () { localStorage.removeItem("name"); // 清除本地存储中的用户名 checkLoginStatus(); // 更新登录状态 }); })(jQuery);2025-05-29 16:48:55.354 DEBUG 2708 --- [nio-8080-exec-5] o.s.web.servlet.DispatcherServlet : GET "/KuCun2/index.html", parameters={} 2025-05-29 16:48:55.372 DEBUG 2708 --- [nio-8080-exec-5] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler ["classpath:/jsp/"] 2025-05-29 16:48:55.400 DEBUG 2708 --- [nio-8080-exec-5] o.s.web.servlet.DispatcherServlet : Completed 200 OK 2025-05-29 16:48:55.441 DEBUG 2708 --- [nio-8080-exec-6] o.s.web.servlet.DispatcherServlet : GET "/KuCun2/fonts/font-awesome-4.7.0/css/font-awesome.min.css", parameters={} 2025-05-29 16:48:55.442 DEBUG 2708 --- [nio-8080-exec-6] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler ["classpath:/jsp/"] 2025-05-29 16:48:55.450 DEBUG 2708 --- [nio-8080-exec-6] o.s.web.servlet.DispatcherServlet : Completed 200 OK 2025-05-29 16:48:55.453 DEBUG 2708 --- [nio-8080-exec-6] o.s.web.servlet.DispatcherServlet : GET "/KuCun2/css/main.css", parameters={} 2025-05-29 16:48:55.455 DEBUG 2708 --- [nio-8080-exec-6] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler ["classpath:/jsp/"] 2025-05-29 16:48:55.457 DEBUG 2708 --- [nio-8080-exec-7] o.s.web.servlet.DispatcherServlet : GET "/KuCun2/css/util.css", parameters={} 2025-05-29 16:48:55.459 DEBUG 2708 --- [nio-8080-exec-7] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler ["classpath:/jsp/"] 2025-05-29 16:48:55.459 DEBUG 2708 --- [nio-8080-exec-9] o.s.web.servlet.DispatcherServlet : GET "/KuCun2/css/index2.css", parameters={} 2025-05-29 16:48:55.460 DEBUG 2708 --- [nio-8080-exec-9] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler ["classpath:/jsp/"] 2025-05-29 16:48:55.461 DEBUG 2708 --- [nio-8080-exec-8] o.s.web.servlet.DispatcherServlet : GET "/KuCun2/js/jsyilai.js", parameters={} 2025-05-29 16:48:55.462 DEBUG 2708 --- [nio-8080-exec-8] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler ["classpath:/jsp/"] 2025-05-29 16:48:55.462 DEBUG 2708 --- [nio-8080-exec-9] o.s.web.servlet.DispatcherServlet : Completed 200 OK 2025-05-29 16:48:55.465 DEBUG 2708 --- [nio-8080-exec-9] o.s.web.servlet.DispatcherServlet : GET "/KuCun2/js/jquery-3.2.1.min.js", parameters={} 2025-05-29 16:48:55.465 DEBUG 2708 --- [nio-8080-exec-9] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler ["classpath:/jsp/"] 2025-05-29 16:48:55.466 DEBUG 2708 --- [nio-8080-exec-8] o.s.web.servlet.DispatcherServlet : Completed 200 OK 2025-05-29 16:48:55.473 DEBUG 2708 --- [nio-8080-exec-6] o.s.web.servlet.DispatcherServlet : Completed 200 OK 2025-05-29 16:48:55.506 DEBUG 2708 --- [nio-8080-exec-7] o.s.web.servlet.DispatcherServlet : Completed 200 OK 2025-05-29 16:48:55.509 DEBUG 2708 --- [nio-8080-exec-9] o.s.web.servlet.DispatcherServlet : Completed 200 OK 2025-05-29 16:48:55.619 DEBUG 2708 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : GET "/KuCun2/main/index.html", parameters={} 2025-05-29 16:48:55.621 DEBUG 2708 --- [nio-8080-exec-2] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler ["classpath:/jsp/"] 2025-05-29 16:48:55.625 DEBUG 2708 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : Completed 200 OK 2025-05-29 16:48:55.678 DEBUG 2708 --- [nio-8080-exec-3] o.s.web.servlet.DispatcherServlet : GET "/KuCun2/js/main.js?1748508535614&_=1748508535584", parameters={masked} 2025-05-29 16:48:55.681 DEBUG 2708 --- [nio-8080-exec-3] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler ["classpath:/jsp/"] 2025-05-29 16:48:55.696 DEBUG 2708 --- [nio-8080-exec-3] o.s.web.servlet.DispatcherServlet : Completed 200 OK 2025-05-29 16:48:55.711 DEBUG 2708 --- [nio-8080-exec-4] o.s.web.servlet.DispatcherServlet : GET "/KuCun2/js/index.js?1748508535617&_=1748508535585", parameters={masked} 2025-05-29 16:48:55.711 DEBUG 2708 --- [nio-8080-exec-4] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler ["classpath:/jsp/"] 2025-05-29 16:48:55.714 DEBUG 2708 --- [nio-8080-exec-4] o.s.web.servlet.DispatcherServlet : Completed 200 OK 2025-05-29 16:48:55.769 DEBUG 2708 --- [nio-8080-exec-5] o.s.web.servlet.DispatcherServlet : GET "/KuCun2/main/bootstrap-3.3.7-dist/js/MyTable.js", parameters={} 2025-05-29 16:48:55.772 DEBUG 2708 --- [nio-8080-exec-5] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler ["classpath:/jsp/"] 2025-05-29 16:48:55.783 DEBUG 2708 --- [nio-8080-exec-5] o.s.web.servlet.DispatcherServlet : Completed 200 OK 2025-05-29 16:48:55.846 DEBUG 2708 --- [nio-8080-exec-8] o.s.web.servlet.DispatcherServlet : GET "/KuCun2/check-session", parameters={} 2025-05-29 16:48:55.851 DEBUG 2708 --- [nio-8080-exec-8] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to com.kucun.Config.SecurityConfig$SessionCheckController#checkSession(HttpServletRequest) 2025-05-29 16:48:55.903 DEBUG 2708 --- [nio-8080-exec-8] o.s.w.s.m.m.a.HttpEntityMethodProcessor : No match for [*/*], supported: [] 2025-05-29 16:48:55.904 DEBUG 2708 --- [nio-8080-exec-8] o.s.web.servlet.DispatcherServlet : Completed 200 OK 2025-05-29 16:48:56.053 DEBUG 2708 --- [nio-8080-exec-6] o.s.web.servlet.DispatcherServlet : GET "/KuCun2/login.html", parameters={} 2025-05-29 16:48:56.054 DEBUG 2708 --- [nio-8080-exec-6] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler ["classpath:/jsp/"] 2025-05-29 16:48:56.057 DEBUG 2708 --- [nio-8080-exec-6] o.s.web.servlet.DispatcherServlet : Completed 200 OK 2025-05-29 16:48:56.177 DEBUG 2708 --- [io-8080-exec-10] o.s.web.servlet.DispatcherServlet : GET "/KuCun2/fonts/font-awesome-4.7.0/css/font-awesome.min.css", parameters={} 2025-05-29 16:48:56.178 DEBUG 2708 --- [io-8080-exec-10] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler ["classpath:/jsp/"] 2025-05-29 16:48:56.188 DEBUG 2708 --- [io-8080-exec-10] o.s.web.servlet.DispatcherServlet : Completed 200 OK 2025-05-29 16:48:56.190 DEBUG 2708 --- [io-8080-exec-10] o.s.web.servlet.DispatcherServlet : GET "/KuCun2/css/util.css", parameters={} 2025-05-29 16:48:56.190 DEBUG 2708 --- [io-8080-exec-10] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler ["classpath:/jsp/"] 2025-05-29 16:48:56.204 DEBUG 2708 --- [io-8080-exec-10] o.s.web.servlet.DispatcherServlet : Completed 200 OK 2025-05-29 16:48:56.206 DEBUG 2708 --- [io-8080-exec-10] o.s.web.servlet.DispatcherServlet : GET "/KuCun2/css/main.css", parameters={} 2025-05-29 16:48:56.206 DEBUG 2708 --- [io-8080-exec-10] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler ["classpath:/jsp/"] 2025-05-29 16:48:56.208 DEBUG 2708 --- [io-8080-exec-10] o.s.web.servlet.DispatcherServlet : Completed 200 OK 2025-05-29 16:48:56.210 DEBUG 2708 --- [io-8080-exec-10] o.s.web.servlet.DispatcherServlet : GET "/KuCun2/js/jquery-3.2.1.min.js", parameters={} 2025-05-29 16:48:56.210 DEBUG 2708 --- [io-8080-exec-10] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler ["classpath:/jsp/"] 2025-05-29 16:48:56.218 DEBUG 2708 --- [io-8080-exec-10] o.s.web.servlet.DispatcherServlet : Completed 200 OK 2025-05-29 16:48:56.220 DEBUG 2708 --- [io-8080-exec-10] o.s.web.servlet.DispatcherServlet : GET "/KuCun2/js/jsyilai.js", parameters={} 2025-05-29 16:48:56.221 DEBUG 2708 --- [io-8080-exec-10] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler ["classpath:/jsp/"] 2025-05-29 16:48:56.224 DEBUG 2708 --- [io-8080-exec-10] o.s.web.servlet.DispatcherServlet : Completed 200 OK 2025-05-29 16:48:56.345 DEBUG 2708 --- [nio-8080-exec-3] o.s.web.servlet.DispatcherServlet : GET "/KuCun2/images/bg-01.jpg", parameters={} 2025-05-29 16:48:56.347 DEBUG 2708 --- [nio-8080-exec-3] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler ["classpath:/jsp/"] 2025-05-29 16:48:56.351 DEBUG 2708 --- [nio-8080-exec-3] o.s.web.servlet.DispatcherServlet : Completed 200 OK 2025-05-29 16:48:56.367 DEBUG 2708 --- [nio-8080-exec-4] o.s.web.servlet.DispatcherServlet : GET "/KuCun2/js/main.js?1748508536335&_=1748508536268", parameters={masked} 2025-05-29 16:48:56.368 DEBUG 2708 --- [nio-8080-exec-4] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler ["classpath:/jsp/"] 2025-05-29 16:48:56.374 DEBUG 2708 --- [nio-8080-exec-4] o.s.web.servlet.DispatcherServlet : Completed 200 OK 2025-05-29 16:48:56.509 DEBUG 2708 --- [nio-8080-exec-5] o.s.web.servlet.DispatcherServlet : GET "/KuCun2/js/login.js?1748508536338&_=1748508536269", parameters={masked} 2025-05-29 16:48:56.510 DEBUG 2708 --- [nio-8080-exec-5] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler ["classpath:/jsp/"] 2025-05-29 16:48:56.512 DEBUG 2708 --- [nio-8080-exec-5] o.s.web.servlet.DispatcherServlet : Completed 200 OK
05-30
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值