Jfinal 整合 spring

jfinal是国内的框架,是要支持一下,波哥强啊,一直维护做这个框架的迭代更新。框架是挺好用的,符合快速开发的需求,对一些小项目足够了,但一些大的项目,需要高灵活性,高扩展,就不那么适合了,这里参考波哥的文档,做了一下jfinal整合spring。

一、引入spring的jar包

在这里插入图片描述

二、jfinal配置中加入spring插件

JFinalConfig的配置:

 @Override
    public void configPlugin(Plugins me) {
    	......
		//spring插件
        me.add(new SpringPlugin("classpath*:spring/*.xml"));
    }
	
	
	@Override
    public void configInterceptor(Interceptors me) {
     	 ......
        //ioc拦截器
        me.add(new IocInterceptor());

    }

IocInterceptor拦截器:

import java.lang.reflect.Field;
import org.springframework.context.ApplicationContext;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;

/**
 * IocInterceptor.
 */
public class IocInterceptor implements Interceptor {

    static ApplicationContext ctx;

    public void intercept(Invocation ai) {
        Controller controller = ai.getController();
        Field[] fields = controller.getClass().getDeclaredFields();
        for (Field field : fields) {
            Object bean = null;
            if (field.isAnnotationPresent(Inject.BY_NAME.class))
                bean = ctx.getBean(field.getName());
            else if (field.isAnnotationPresent(Inject.BY_TYPE.class))
                bean = ctx.getBean(field.getType());
            else
                continue ;

            try {
                if (bean != null) {
                    field.setAccessible(true);
                    field.set(controller, bean);
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        ai.invoke();
    }
}

 */
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Inject.
 */
public class Inject {

    private Inject() {}

    @Inherited
    @Retention(RetentionPolicy.RUNTIME)
    @Target({ElementType.FIELD})
    public static @interface BY_TYPE {}

    @Inherited
    @Retention(RetentionPolicy.RUNTIME)
    @Target({ElementType.FIELD})
    public static @interface BY_NAME {}

	/*
	@Inherited
	@Retention(RetentionPolicy.RUNTIME)
	@Target({ElementType.FIELD})
	public static @interface IGNORE {}
	*/
}

三、整合运用

在需要的地方加上@Before(IocInterceptor.class),jfinal切面是通过拦截器来完成的,在使用jfinal开发时,你会发现,会有很多的拦截器,功能上与spring aop差不多,对于事务管理和操作日记的通用功能可以通过jfinal拦截器增强处理。

@Before(IocInterceptor.class)
public class WebServiceController extends Controller {

	private static final Logger logger = Logger.getLogger(WebServiceController.class);

	@Inject.BY_NAME
	private LogInfoService logInfoService;

}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot可以很方便地整合Spring Security和JWT(JSON Web Token)。 首先,需要在pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt</artifactId> <version>0.9.1</version> </dependency> ``` 然后,需要创建一个Security配置类,用于配置Spring Security和JWT: ```java @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint; @Autowired private JwtRequestFilter jwtRequestFilter; @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { // 配置用户认证方式 } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Bean @Override public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } @Override protected void configure(HttpSecurity httpSecurity) throws Exception { httpSecurity.csrf().disable() .authorizeRequests().antMatchers("/authenticate").permitAll(). anyRequest().authenticated().and(). exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint).and().sessionManagement() .sessionCreationPolicy(SessionCreationPolicy.STATELESS); httpSecurity.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class); } } ``` 在上面的配置类中,需要注入JwtAuthenticationEntryPoint和JwtRequestFilter两个类。其中,JwtAuthenticationEntryPoint用于处理未经授权的请求,JwtRequestFilter用于验证JWT并将用户信息添加到Spring Security上下文中。 接下来,需要创建一个JwtTokenUtil类,用于生成和验证JWT: ```java @Component public class JwtTokenUtil { private static final String SECRET_KEY = "secret"; public String generateToken(UserDetails userDetails) { Map<String, Object> claims = new HashMap<>(); return Jwts.builder().setClaims(claims).setSubject(userDetails.getUsername()) .setIssuedAt(new Date(System.currentTimeMillis())) .setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 10)) .signWith(SignatureAlgorithm.HS512, SECRET_KEY).compact(); } public boolean validateToken(String token, UserDetails userDetails) { final String username = getUsernameFromToken(token); return (username.equals(userDetails.getUsername()) && !isTokenExpired(token)); } private boolean isTokenExpired(String token) { final Date expiration = getExpirationDateFromToken(token); return expiration.before(new Date()); } private Date getExpirationDateFromToken(String token) { return Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token).getBody().getExpiration(); } private String getUsernameFromToken(String token) { return Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token).getBody().getSubject(); } } ``` 在上面的类中,需要设置一个密钥,用于生成和验证JWT。generateToken方法用于生成JWT,validateToken方法用于验证JWT是否有效。 最后,需要创建一个JwtAuthenticationEntryPoint类和一个JwtRequestFilter类。JwtAuthenticationEntryPoint类用于处理未经授权的请求,JwtRequestFilter类用于验证JWT并将用户信息添加到Spring Security上下文中。 以上就是整合Spring Security和JWT的基本步骤。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值