spring boot+freemarker+spring security标签权限判断

spring boot+freemarker+spring security标签权限判断

SpringBoot+SpringSecurity+Freemarker项目中在页面上使用security标签控制按钮显示隐藏达到对按钮级权限控制还是比较方便的,如下配置即可。

1、引入依赖

<dependency>			
<groupId>org.springframework.security</groupId>			
<artifactId>spring-security-taglibs</artifactId>		
</dependency> 		

<dependency>			
<groupId>javax.servlet.jsp</groupId>			
<artifactId>jsp-api</artifactId>			
<version>2.2.1-b03</version>		
</dependency>

  

2、依赖引入后到spring-security-taglibs包中META-INF下security.tld复制出来,放到/resources/下,最后建一个目录tags,如下:

 

3、建一个配置类:ClassPathTldsLoader.java

import java.util.Arrays;
import java.util.List;

import javax.annotation.PostConstruct;

import org.apache.commons.lang.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

public class ClassPathTldsLoader {

	  /**
     * 指定路径
     */
    private static final String SECURITY_TLD = "/security.tld";

    final private List<String> classPathTlds;

    public ClassPathTldsLoader(String... classPathTlds) {
        super();
        if(ArrayUtils.isEmpty(classPathTlds)){
            this.classPathTlds = Arrays.asList(SECURITY_TLD);
        }else{
            this.classPathTlds = Arrays.asList(classPathTlds);
        }
    }
    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;

    @PostConstruct
    public void loadClassPathTlds() {
        freeMarkerConfigurer.getTaglibFactory().setClasspathTlds(classPathTlds);
    }
}

  

4.然后在网站配置文件SecurityConfig.java中加入bean

/**
	 * 自动加载security-taglibs
	 * @return
	 */
	    @Bean
	    @ConditionalOnMissingBean(ClassPathTldsLoader.class)
	    public ClassPathTldsLoader classPathTldsLoader(){
	        return new ClassPathTldsLoader();
	    }

  

参考:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
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.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@EnableWebSecurity
//启用全局post安全方法设置
@EnableGlobalMethodSecurity(prePostEnabled=true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

	private static final String key = "muyang.my";
	
	@Autowired
	private UserDetailsService userDetailsService;
	
	
	@Bean
	public PasswordEncoder passwordEncoder()
	{
		return new BCryptPasswordEncoder();
		
	}
	
	@Bean
	public AuthenticationProvider authenticationProvider() {
		DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
		authenticationProvider.setUserDetailsService(userDetailsService);
		//密码加密方式
		authenticationProvider.setPasswordEncoder(passwordEncoder());
		return authenticationProvider;
		
	}
	
	@Override
	protected void configure(HttpSecurity http) throws Exception {
		// TODO Auto-generated method stub
		//super.configure(http);
		//关闭csrf验证:跨站攻击
		//http.csrf().disable();
		//权限设置
		http.authorizeRequests()     //定义那些url需要保护,哪些不需要保护
		.antMatchers("/static/**").permitAll()  //都可以访问
		.antMatchers("/user/**").hasRole("ADMIN") //需要登陆才能访问
		.and()		
		.headers().frameOptions().disable() //解决js跨站把x-frame-options disable即可
		.and()
		.formLogin() //基于FORM表单登陆验证
		.loginPage("/login").failureUrl("/login-error") //自定义登陆界面//自定义登陆错误页面
		.and().rememberMe().key(key) //记住我
		.and().exceptionHandling().accessDeniedPage("/403");  // 处理异常,拒绝访问就重定向到 403 页面
	}

	
	
	/**
	 * 认证信息管理
	 * @param auth
	 * @throws Exception
	 */
	@Autowired
	public  void configureGlobal(AuthenticationManagerBuilder  auth) throws Exception {
		// TODO Auto-generated method stub
		//super.configure(auth);
		//auth.inMemoryAuthentication().withUser("admin").password("123456").roles("ADMIN");
		auth.userDetailsService(userDetailsService);
		auth.authenticationProvider(authenticationProvider());
	}

	
	/**
	 * 自动加载security-taglibs
	 * @return
	 */
	    @Bean
	    @ConditionalOnMissingBean(ClassPathTldsLoader.class)
	    public ClassPathTldsLoader classPathTldsLoader(){
	        return new ClassPathTldsLoader();
	    }
	
	
}

  

5、在freemarker页面顶部引入标签

<#assign security=JspTaglibs["http://www.springframework.org/security/tags"] />

  

使用标签

<@security.authorize access="hasRole('ADMIN')">
222
</@security.authorize>

  

6.或者

 

<%@taglib uri="http://www.springframework.org/security/tags" prefix="sec"%>
<sec:authorize access="isAuthenticated()">
    <% response.sendRedirect("main"); %>
</sec:authorize>

  

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot是一个流行的开源框架,它简化了构建独立的、生产级Java应用的过程。对于评论管理功能,Spring Boot可以与Spring MVC、Hibernate或MyBatis等持久层技术结合,使用诸如Thymeleaf、Freemarker等模板引擎展示评论,以及Spring Security进行权限控制。 在Spring Boot中构建评论管理模块,通常包括以下几个步骤: 1. **模型层**(Model):创建Comment实体类,存储评论的内容、作者信息、时间戳等。 ```java public class Comment { private Long id; private String content; private User author; private LocalDateTime createdAt; // getters and setters } ``` 2. **服务层**(Service):定义评论服务,处理CRUD操作,可能包括保存新评论、获取评论列表、删除评论等。 ```java @Service public class CommentService { @Autowired private CommentRepository commentRepository; public Comment save(Comment comment) { return commentRepository.save(comment); } // 其他方法... } ``` 3. **仓库层**(Repository):使用Spring Data JPA或MyBatis等ORM工具,提供数据库访问操作。 4. **控制器层**(Controller):处理HTTP请求,调用服务层的方法,并将结果返回给前端。 ```java @RestController @RequestMapping("/comments") public class CommentController { @Autowired private CommentService commentService; @PostMapping public ResponseEntity<Comment> createComment(@RequestBody Comment comment) { Comment savedComment = commentService.save(comment); return ResponseEntity.ok(savedComment); } // GET、PUT、DELETE方法等 } ``` 5. **前端展示**:使用HTML、Thymeleaf或Freemarker等模板语言,展示评论列表和评论表单。 6. **安全性**:使用Spring Security进行身份验证和授权,确保只有注册用户才能发表评论。 7. **评论审核机制**:如果需要,可以添加评论审核流程,比如通过邮箱验证或管理员后台审批。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值