Spring Security配置使用以及图片上传

这里使用的是Spring Security自带的默认登录

话不多说先配置xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:security="http://www.springframework.org/schema/security"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/security
    http://www.springframework.org/schema/security/spring-security.xsd">

    <security:global-method-security pre-post-annotations="enabled" jsr250-annotations="enabled" secured-annotations="enabled"></security:global-method-security>

    <!-- 配置不拦截的资源 -->
    <security:http pattern="/pages/login.jsp" security="none"/>
    <security:http pattern="/failer.jsp" security="none"/>
    <security:http pattern="/css/**" security="none"/>
    <security:http pattern="/img/**" security="none"/>
    <security:http pattern="/plugins/**" security="none"/>
    <security:http pattern="/index.jsp" security="none"/>
    <!--
    	配置具体的规则
    	auto-config="true"	不用自己编写登录的页面,框架提供默认登录页面
    	use-expressions="false"	是否使用SPEL表达式(没学习过)
    -->
    <security:http auto-config="true" use-expressions="true">
        <!-- 配置具体的拦截的规则 pattern="请求路径的规则" access="访问系统的人,必须有ROLE_USER的角色" -->
        <security:intercept-url pattern="/**" access="hasAnyRole('ROLE_USER','ROLE_ADMIN')"/>

        <security:form-login login-page="/login.jsp"
                             login-processing-url="/login.do"
                            default-target-url="/index.jsp"
                            authentication-failure-url="/failer.jsp"
                            authentication-success-forward-url="/pages/main.jsp"/>

        <!-- 关闭跨域请求 -->
        <security:csrf disabled="true"/>

        <!--退出并跳转到首页-->
        <security:logout invalidate-session="true" logout-url="/logout.do" logout-success-url="/login.jsp"></security:logout>

    </security:http>

    <!-- 切换成数据库中的用户名和密码 -->
    <security:authentication-manager>
        <security:authentication-provider user-service-ref="userService">
            <!-- 配置加密的方式
            <security:password-encoder ref="passwordEncoder"/> -->
        </security:authentication-provider>
    </security:authentication-manager>

    <!-- 配置加密类 -->
    <bean id="passwordEncoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"/>
    <!-- <bean id="webexpressionHandler" class="org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler" />-->
    <!-- 提供了入门的方式,在内存中存入用户名和密码
    <security:authentication-manager>
    	<security:authentication-provider>
    		<security:user-service>
    		<!-{noop}加密-->
<!--    			<security:user name="admin" password="{noop}admin" authorities="ROLE_USER"/>-->
<!--    		</security:user-service>-->
<!--    	</security:authentication-provider>-->
<!--    </security:authentication-manager>-->

</beans>

配置完xml在service继承他的类,重写方法

public interface IUserInfoService extends UserDetailsService{
	UserDetails loadUserByUsername(String username) throws UsernameNotFoundException;
}

注意这里@Service(“userService”)里之所以要叫userService是因为配置里 <security:authentication-provider user-service-ref=“userService”>配置的

@Service("userService")
public class IUserInfoServiceImpl implements IUserInfoService {
 @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserInfo userInfo = iUserInfoDao.findbyUserName(username);
        List<Role> roleList = iRoleDao.findRoleByUserId(userInfo.getId());
        userInfo.setRoleList(roleList);
        User user = new User(userInfo.getUsername(),"{noop}"+userInfo.getPassword(),getAuthority(roleList));
        return user;
    }

    private Collection<? extends GrantedAuthority> getAuthority(List<Role> roleList) {
        List<SimpleGrantedAuthority> list = new ArrayList<>();
        for (Role role:roleList){
            list.add(new SimpleGrantedAuthority("ROLE_"+role.getRname().toUpperCase()));
        }
        return list;
    }

注意这里密码一点要加密{noop}因为Spring Security默认加密数据库出来密码会在加密一次
配置完成

<form action="${pageContext.request.contextPath}/login.do" method="post">

直接传入login.do就行了
注意使用Spring Security一定要注释掉你之前配置的过滤器和拦截器。

图片上传

<form action="${pageContext.request.contextPath}/upLoadController/upload.do"
              method="post" enctype="multipart/form-data">
       <input type="file" class="form-control" accept="image/*" name="myPic"
                                   placeholder="图片" value="" multiple/>
 </form>

后端接收

@RequestMapping("/upload.do")
    public ModelAndView upLoad(@RequestParam("myPic")MultipartFile myPic, HttpSession session) throws IOException {
        //1.文件在服务器上存储
        UUID rid = UUID.randomUUID();
        long uid = rid.getLeastSignificantBits();
        String contextPath = session.getServletContext().getRealPath("/img");
        String suffix = myPic.getOriginalFilename().substring(myPic.getOriginalFilename().lastIndexOf("."));
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String path = contextPath+"\\"+df.format(new Date())+uid+suffix;
        File file = new File(path.replace("-",""));
        myPic.transferTo(file);
        //2.文件地址的回显
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("upLoad");
        modelAndView.addObject("upLoad_file_path",file.getName());
        //3.给出页面的跳转
        return modelAndView;
    }

前端配置jsp完成

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值