Struts 2 拦截器中得到bean以及读取WEB-INF下的spring的xml文件
1.直接得到bean
public class OperaLogInterceptor extends AbstractInterceptor { private static final long serialVersionUID = 1L; @SuppressWarnings("unchecked") protected Set excludeMethods; @SuppressWarnings("unchecked") protected Set includeMethods; /** * 拦截器方法 */ @SuppressWarnings({ "unchecked", "static-access" }) public String intercept(ActionInvocation invocation) { String result = null; HttpServletRequest request = ServletActionContext.getRequest(); BaseAction action = (BaseAction) invocation.getAction(); ServletContext sc = ServletActionContext.getServletContext(); //ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(sc); ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(sc); ModuleService moduleService = (ModuleService) ctx.getBean("moduleService");//模块service OperationLogService logService = (OperationLogService) ctx.getBean("operationService");//模块service try { result = invocation.invoke(); // 判断是否需要写日志 if (applyMethod(excludeMethods, includeMethods, invocation.getProxy().getMethod())) { this.saveLog(getModulename(request, moduleService),AlphaUtil.getIP(request), request.getRemoteHost(),action.getEmployee().getEId(), action.getEmployee().getEName(), logService); } } catch (Exception e) { e.printStackTrace(); return action.SUCCESS; } return result; } /** * 返回模块的url * * @param request * @param action * @return */ @SuppressWarnings("unchecked") private String getModulename(HttpServletRequest request, ModuleService moduleService) { //String modulename = request.getRequestURI() + StringUtil.getparamString(request.getParameterMap()); String modulename = ""; String url = request.getRequestURI(); if (url.length() > 20) { url = url.substring(17); } List mList = moduleService.query("from Tbmodule where MUrl='"+url+"'"); if (null != mList && mList.size()>0) { Tbmodule module = (Tbmodule) mList.get(0); modulename = module.getMName(); } System.out.println("modulename="+modulename); return modulename; } /** * 返回是否需要写操作日志 * * @param excludeMethods * @param includeMethods * @param method * @return */ private boolean applyMethod(Set<String> excludeMethods, Set<String> includeMethods, String method) { if (includeMethods != null) { for (String s : includeMethods) { boolean bl = Pattern.compile(s).matcher(method).matches(); if (bl) return true; } } if (excludeMethods != null) { for (String s : excludeMethods) { boolean bl = Pattern.compile(s).matcher(method).matches(); if (bl) return false; } } return true; } /** * 写操作日志 * @param olBusinussName:业务名称 * @param olOperationIp:操作人IP * @param olOperationTable:操作表名 * @param olOperationUserId:操作人编号 * @param olOperationUserName:操作人名称 * @param logService */ private void saveLog(String olBusinussName, String olOperationIp, String olOperationTable, Integer olOperationUserId, String olOperationUserName, OperationLogService logService) { try { Tboperationlog oplog = new Tboperationlog(); oplog.setOlOperationDate(new Date()); oplog.setOlBusinussName(olBusinussName); oplog.setOlOperationIp(olOperationIp); oplog.setOlOperationTable(olOperationTable); oplog.setOlOperationUserId(olOperationUserId); oplog.setOlOperationUserName(olOperationUserName); logService.save(oplog); } catch (Exception e) { e.printStackTrace(); } } public void setExcludeMethods(String excludeMethods) { this.excludeMethods = TextParseUtil .commaDelimitedStringToSet(excludeMethods); } public Set getExcludeMethodsSet() { return excludeMethods; } public void setIncludeMethods(String includeMethods) { this.includeMethods = TextParseUtil .commaDelimitedStringToSet(includeMethods); } public Set getIncludeMethodsSet() { return includeMethods; } public static void main(String a[]) { boolean bl = Pattern.compile("").matcher("").matches(); // 当条件满足时,将返回true,否则返回false System.out.println(bl); } }2.各种读取xml的方法整理:
读取xml文件/**
* 利用XmlBeanFactory(Resource resource)
* 这里Resource必须是xml格式
* Resource包括:AbstractResource, ClassPathResource, FileSystemResource,
* InputStreamResource, ServletContextResource, UrlResource
*/
/*
* 利用 InputStreamResource(InputStream inputStream)
* 要将applicationContext.xml放在项目根目录下
*/
InputStream is = null;
try {
is = new FileInputStream("applicationContext.xml");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Resource resource = new InputStreamResource(is);
BeanFactory factory = new XmlBeanFactory(resource);
UserDao userDao = (UserDao)factory.getBean("userDao");
/*
* 利用 Properties
* 要将bean.properties放在类路径--源文件夹(src)目录下
*/
具体见http://blog.csdn.net/lwzcjd/archive/2008/10/21/3116298.aspx
1.利用ClassPathXmlApplicationContext
可以从classpath中读取XML文件
(1) ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserDao userDao = (UserDao)context.getBean("userDao");
(2) ClassPathXmlApplicationContext resource = new ClassPathXmlApplicationContext(new String[]{"applicationContext-ibatis-oracle.xml","applicationContext.xml","applicationContext-data-oracle.xml"});
BeanFactory factory = resource;
UserDao userDao = (UserDao) factory.getBean("userDao");
2. 利用ClassPathResource
可以从classpath中读取XML文件
Resource cr = new ClassPathResource("applicationContext.xml");
BeanFactory bf=new XmlBeanFactory(cr);
UserDao userDao = (UserDao)bf.getBean("userDao");
加载一个xml文件 org.springframework.beans.factory.config.PropertyPlaceholderConfigurer不起作用
3.利用XmlWebApplicationContext读取
从Web应用程序的文件架构中,指定相对位置来读取定义文件。
XmlWebApplicationContext 的建构子无法带参数,参考API文件会发现,预设的location会指向/WEB-INF/applicationContext.xml档案。使用其 public static属性DEFAULT_CONFIG_LOCATION可取得此预设档名。由於我使用MyEclipse,预设会多一个"/WebRoot"的 目录在WEB-INF之前,因此若在web project里有一些与web无关的程式要使用context时(例如处理一些MVC架构中的"M"的部份),就无法使用 XmlWebApplicationContext来读取bean定义档,因为default location会差一个"WebRoot"的目录。
即 使在web.xml里面,在DispatcherServlet定义中重新定义contextConfigLocation也一样(此定义可以 override掉XmlWebApplicationContext中的DEFAULT_CONFIG_LOCATION值),因为与web无关的程式 并不会经过web.xml的定义档设定。目前我还没试成功过XmlWebApplicationContext取得bean定义档,使用 ClassPathXmlApplicationContext反而会快一些。
XmlWebApplicationContext ctx = new XmlWebApplicationContext();
ctx.setConfigLocations(new String[] {"/WEB-INF/ applicationContext.xml");
ctx.setServletContext(pageContext.getServletContext());
ctx.refresh();
UserDao userDao = (UserDao ) ctx.getBean("userDao ");
4.利用FileSystemResource读取 Resource rs = new FileSystemResource("D:/tomcat/webapps/test/WEB-INF/classes/ applicationContext.xml"); BeanFactory factory = new XmlBeanFactory(rs); UserDao userDao = (UserDao )factory.getBean("userDao"); 值得注意的是:利用FileSystemResource,则配置文件必须放在project直接目录下,或者写明绝对路径,否则就会抛出找不到文件的异常 5.利用FileSystemXmlApplicationContext读取 可以指定XML定义文件的相对路径或者绝对路径来读取定义文件。 方法一: String[] path={"WebRoot/WEB-INF/applicationContext.xml","WebRoot/WEB-INF/applicationContext_task.xml"}; ApplicationContext context = new FileSystemXmlApplicationContext(path); 方法二: String path="WebRoot/WEB-INF/applicationContext*.xml"; ApplicationContext context = new FileSystemXmlApplicationContext(path); 方法三: ApplicationContext ctx = new FileSystemXmlApplicationContext("classpath:地址"); 没有classpath的话就是从当前的工作目录 ******************************************************************************* ** 分割一下 ** ******************************************************************************* 获取Spring框架管理的类实例的方法有多种,如下: 方法一:在初始化时保存ApplicationContext对象 代码: ApplicationContext ac = new FileSystemXmlApplicationContext("applicationContext.xml"); ac.getBean("beanId"); 说明: 这种方式适用于采用Spring框架的独立应用程序,需要程序通过配置文件手工初始化Spring的情况。 方法二:通过Spring提供的工具类获取ApplicationContext对象 代码: import org.springframework.web.context.support.WebApplicationContextUtils; ApplicationContext ac1 = WebApplicationContextUtils.getRequiredWebApplicationContext(ServletContext sc) ApplicationContext ac2 = WebApplicationContextUtils.getWebApplicationContext(ServletContext sc) ac1.getBean("beanId"); ac2.getBean("beanId"); 说明: 这种方式适合于采用Spring框架的B/S系统,通过ServletContext对象获取ApplicationContext对象,然后 在通过它获取需要的类实例。 上面两个工具方式的区别是,前者在获取失败时抛出异常,后者返回null。 方法三:继承自抽象类ApplicationObjectSupport 说明: 抽象类ApplicationObjectSupport提供getApplicationContext()方法,可以方便的获取到 ApplicationCont ext。Spring初始化时,会通过该抽象类的setApplicationContext(ApplicationContext context)方法将ApplicationContext 对象注入。 方法四:继承自抽象类WebApplicationObjectSupport 说明: 类似上面方法,调用getWebApplicationContext()获取WebApplicationContext 方法五:实现接口ApplicationContextAware 说明: 实现该接口的setApplicationContext(ApplicationContext context)方法,并保存ApplicationContext 对 象。Spring初始化时,会通过该方法将ApplicationContext 对象注入。 以上方法适合不同的情况,请根据具体情况选用相应的方法。 这里值得提一点的是,系统中用到上述方法的类实际上就于Spring框架紧密耦合在一起了,因为这些类是知 道它们是运行在Spring框架上的,因此,系统中,应该尽量的减少这类应用,使系统尽可能的独立于当前运 行环境,尽量通过DI的方式获取需要的服务提供者。 本人认为,方法五比较可行,可以设计一个工具类,专门来获取Spring中的类。减少对业务代码的侵入性。