Spring 3使用@Value

5 篇文章 0 订阅
1 篇文章 0 订阅

1.主要涉及类

1
org.springframework.beans.factory.annotation.Value

2.使用方法

2.1 properties文件创建

auth.properties
1
url.urlroles = ^/FDCF/fdcfstm/.*$ & G00200,G00103  ;\
2
               ^/FDCF/fdcfDF/.*$ & G00200   ;\
3
               ^/FDCF/fdcfFF/.*$ & G00200,G00103 ;\
4
               ^/FDCF/fdcfstm/.*$ & G00200,G00103 ;\
5
               ^/FDCF/userService_400/.*$ & G00400 \
6
7
url.test = Add a URL corresponding to the role of & separated, line plus '\'!

2.2 在spring[applicationContext.sml]中进行配置

1
<!-- 配置properties -->
2
    <bean
3
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
4
        <property name="locations">
5
            <list>
6
                <value>classpath:conf/jdbc.properties</value>
7
                <value>classpath:conf/memcached.properties</value>
8
                <value>classpath:conf/ftp.properties</value>
9
                <value>classpath:conf/auth.properties</value>
10
            </list>
11
        </property>
12
        <property name="ignoreUnresolvablePlaceholders" value="true" />
13
    </bean>

2.3 创建与properties结构相同的bean

1
package com.ufgov.filter;
2
3
import java.util.ArrayList;
4
import java.util.List;
5
6
import org.springframework.beans.factory.annotation.Value;
7
import org.springframework.stereotype.Component;
8
9
@Component
10
public class SecurityUrl { 
11
    //URL  Role 对应信息
12
    @Value("#{'${url.urlroles}'.split(';')}")
13
    private List<String> urlroles = new ArrayList<String>() ;
14
    
15
    @Value("${url.test}")
16
    private String test;
17
18
    public String getTest() {
19
        return test;
20
    }
21
22
    public void setTest(String test) {
23
        this.test = test;
24
    }
25
26
    public List<String> getUrlroles() {
27
        return urlroles;
28
    }
29
30
    public void setUrlroles(List<String> urlroles) {
31
        this.urlroles = urlroles;
32
    }
33
}

2.4 在代码中使用

1
package com.ufgov.filter;
2
3
import java.io.IOException;
4
import java.io.PrintWriter;
5
import java.util.HashMap;
6
import java.util.Iterator;
7
import java.util.List;
8
import java.util.Map;
9
import java.util.regex.Pattern;
10
11
import javax.servlet.Filter;
12
import javax.servlet.FilterChain;
13
import javax.servlet.FilterConfig;
14
import javax.servlet.ServletException;
15
import javax.servlet.ServletRequest;
16
import javax.servlet.ServletResponse;
17
import javax.servlet.http.HttpServletRequest;
18
import javax.servlet.http.HttpServletResponse;
19
20
import org.apache.log4j.Logger;
21
import org.springframework.context.ApplicationContext;
22
import org.springframework.context.support.FileSystemXmlApplicationContext;
23
24
import com.google.gson.Gson;
25
import com.ufgov.entity.SysRole;
26
import com.ufgov.util.DateUtils;
27
import com.ufgov.util.MemcachedUtils;
28
29
public class SecurityFilter implements Filter{
30
31
     private static final Logger log = Logger.getLogger(SecurityFilter.class);
32
 
33
     private static SecurityUrl surl;
34
     
35
    @Override
36
    public void init(FilterConfig filterConfig) throws ServletException {
37
         
38
        @SuppressWarnings("resource")
39
        ApplicationContext ac = new FileSystemXmlApplicationContext("classpath:conf/applicationContext.xml");
40
        surl= (SecurityUrl)ac.getBean("securityUrl");
41
    }
42
43
    @Override
44
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
45
            throws IOException, ServletException {
46
         /**
47
          * 先有个思路,首先得到所有得URL ROLE列表。
48
          * 根据正则匹配当前的URL是否在列表中,在的话取出它对应的角色,
49
          * 然后得到当前登录人的角色,再去判断角色是否在以上中,
50
          * 在的话放行,不再的话,进行无权限的说明。
51
          */
52
        HttpServletRequest req = (HttpServletRequest) request;
53
        HttpServletResponse resp = (HttpServletResponse) response;
54
        
55
        
56
        //当前登录的用户的角色 没有的话不做处理
57
    
58
        SysRole role = MemcachedUtils.getRoleInfo(req);
59
        if(null == role){
60
            chain.doFilter(request, response);
61
            return;
62
        }
63
        
64
        String userRole = role.getRoleType();
65
        log.info(" --当前用户角色--  "+userRole);
66
        
67
        String requrl = req.getRequestURI();
68
        log.info("当前请求的URL: "+requrl);
69
        
70
        List<String> urlroles = surl.getUrlroles();
71
        Iterator<String> it = urlroles.iterator();
72
        boolean isAble = false;
73
        
74
        //没有配置的URL默认都可以访问
75
        while(it.hasNext()){
76
            String ur = it.next();
77
            
78
            String reg = ur.split("&")[0].trim();
79
            if(!Pattern.matches(reg, requrl)){
80
                //如果没有匹配到继续匹配下一次
81
                isAble = true;
82
                continue;
83
            }
84
            //可能有多个角色的
85
            String needrole = ur.split("&")[1].trim();
86
            
87
            log.info("The url need role is = "+needrole);
88
            if(needrole.indexOf(userRole)!=-1){
89
                isAble = true;
90
            }else{
91
                isAble = false;
92
            }
93
         
94
            break;
95
            
96
        }
97
        if(isAble){
98
            chain.doFilter(request, response);
99
        }else{
100
            Gson gson = new Gson();
101
            Map<String,Object> map = new HashMap<String,Object>();
102
            map.put("message", "The user do not have access to this resource,Please contact the administrator!");
103
            map.put("type", "No permission!");
104
        
105
            resp.setStatus(500);
106
            response.setContentType("application/json;charset=UTF-8");// 解决中文乱码
107
           
108
            try {
109
                PrintWriter writer = response.getWriter();
110
                writer.write(gson.toJson(map));
111
                writer.flush();
112
                writer.close();
113
            } catch (Exception e) {
114
                e.printStackTrace();
115
            }
116
        }
117
        
118
    }
119
120
    @Override
121
    public void destroy() {
122
        // TODO Auto-generated method stub
123
        
124
    }
125
126
}
127
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值