springboot项目中如何在代码的service获取Request,Response对象?

1. 通过 RequestContextHolder 对象

package com.order.utils;

import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author guoyiguang
 * @description houqu  Request duixiang  he  Response  duixiang
 * @date 2021/12/24$
 */
public class WebUtil {

    /** 获取request对象 **/
    public static HttpServletRequest getRequest(){
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if (requestAttributes == null){
            return null;
        }
        return ((ServletRequestAttributes)requestAttributes).getRequest();
    }
    /** 获取response对象 **/
    public static HttpServletResponse getResponse(){
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if (requestAttributes == null){
            return null;
        }
        return ((ServletRequestAttributes)requestAttributes).getResponse();
    }
}

理解:


	对 RequestContextHolder  的理解:
	
	RequestContextHolder  里有 ThreadLocal 对象,可以存放 线程的私有属性,如下:
	
	
	  private static final ThreadLocal<RequestAttributes> requestAttributesHolder = new NamedThreadLocal<>("Request attributes");
			

	  private static final ThreadLocal<RequestAttributes> inheritableRequestAttributesHolder = new NamedInheritableThreadLocal<>("Request context");

原理:


	Servlet 监听器(RequestContextListener implements ServletRequestListener ) 监听请求,
	HttpServletRequest  这个对象创建完之后,会把他作为 ServletRequestAttributes 构造器的参数 ,对 ServletRequestAttributes  进行实例化
	这样通过 ServletRequestAttributes 和  HttpServletRequest 对象就就行了绑定
	
	如下:(所在类: ServletRequestAttributes) 
	public ServletRequestAttributes(HttpServletRequest request) {
		Assert.notNull(request, "Request must not be null");
		this.request = request;
	}
	
	
	然后:作为线程的私有属性放到 ThreadLocal 里 
	
	inheritableRequestAttributesHolder.set(ServletRequestAttributes);
	


    最后使用:
	   
	
	    // 获取请求 对象
	    RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if (requestAttributes == null){
            return null;
        }
        return ((ServletRequestAttributes)requestAttributes).getRequest();
		
		// 获取响应 对象
	    RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if (requestAttributes == null){
            return null;
        }
        return ((ServletRequestAttributes)requestAttributes).getResponse();

相关的监听器:

RequestContextListener  implements ServletRequestListener extends EventListener

Thread里 有 ThreadLocalMap 类,每个Thread都会实例化一个 ThreadLocalMap 实例

set 方法如下:


// key 就是 经常用的  ThreadLocal 实例 ,value就是要设置的值 
private void set(ThreadLocal<?> key, Object value);

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是在Spring Boot项目使用Spring Security的示例代码: 1. 添加依赖项: 在Maven构建文件添加以下依赖项: ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> ``` 2. 创建Security配置类: 创建一个类来配置Spring Security,该类需要继承WebSecurityConfigurerAdapter类。以下是一个简单的示例: ``` @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private UserDetailsService userDetailsService; @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService); } @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/admin/**").hasRole("ADMIN") .antMatchers("/user/**").hasAnyRole("ADMIN", "USER") .anyRequest().authenticated() .and() .formLogin() .loginPage("/login") .permitAll() .and() .logout() .permitAll(); } } ``` 在上面的配置,我们指定了哪些URL需要保护,并定义了用户身份验证方式。具体来说: - configureGlobal方法用于配置用户存储,我们使用了一个实现了UserDetailsService接口的类来加载用户信息。 - configure方法用于配置访问控制和身份验证方式。我们使用了一个基于角色的访问控制策略,指定了哪些URL需要哪些角色。我们还配置了登录页面和注销功能。 3. 配置用户存储: 我们可以使用内存,数据库或LDAP等不同类型的存储来存储用户及其角色信息。以下是一个使用内存存储的示例: ``` @Service public class UserDetailsServiceImpl implements UserDetailsService { private Map<String, UserDetails> users = new HashMap<>(); public UserDetailsServiceImpl() { User admin = new User("admin", "{noop}admin123", AuthorityUtils.createAuthorityList("ROLE_ADMIN")); User user = new User("user", "{noop}user123", AuthorityUtils.createAuthorityList("ROLE_USER")); users.put(admin.getUsername(), admin); users.put(user.getUsername(), user); } @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { UserDetails user = users.get(username); if (user == null) { throw new UsernameNotFoundException("User not found: " + username); } return user; } } ``` 在上述示例,我们创建了两个用户,一个是管理员,一个是普通用户。我们使用了NoOpPasswordEncoder来存储用户密码。在实际项目,建议使用更安全的PasswordEncoder。 4. 配置登录和注销: 在Security配置类,我们可以通过配置登录和注销URL,以及相关的身份验证和授权逻辑,来实现用户登录和注销功能。以下是一个简单的示例: ``` @Controller public class LoginController { @GetMapping("/login") public String login() { return "login"; } @GetMapping("/logout") public String logout(HttpServletRequest request, HttpServletResponse response) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if (auth != null) { new SecurityContextLogoutHandler().logout(request, response, auth); } return "redirect:/login?logout"; } } ``` 在上述示例,我们定义了/login和/logout两个URL,分别用于用户登录和注销。我们使用了Spring Security提供的SecurityContextHolder和SecurityContextLogoutHandler来实现注销功能。 5. 配置访问控制: 我们可以通过配置访问规则,以及使用注解或表达式来控制用户访问应用程序的各个部分。以下是一个使用注解控制访问的示例: ``` @Controller @RequestMapping("/user") public class UserController { @PreAuthorize("hasRole('USER')") @GetMapping("/profile") public String profile() { return "profile"; } } ``` 在上述示例,我们在UserController类定义了/profile URL,并使用了@PreAuthorize注解来指定只有拥有USER角色的用户才能访问该URL。 这些示例代码可以帮助您在Spring Boot项目使用Spring Security。请注意,这只是一个简单的概述,实际实现可能会更加复杂。建议您查看Spring Security官方文档,以获取更详细的信息和示例代码

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值