如何在java中的spring aop logger类中访问会话中的任何数据?

时间:2011-11-30 05:56:43

标签: java spring-aop

我是Spring AOP的新手,我正在尝试为我的Action类实现日志记录。现在我还希望在日志记录中保存DataBase中的某些信息。为此我需要在我的会话中使用某些数据。在我的记录器类中访问但尝试访问它时,会出现“出现空指针异常”。任何帮助将非常感谢... Thanx

LoggingInterceptor.java

package com.mcmc.utility;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.interceptor.SessionAware;
import org.springframework.aop.AfterReturningAdvice;
import org.springframework.aop.MethodBeforeAdvice;
import org.springframework.aop.ThrowsAdvice;

import com.mcmc.hn.bean.UserInfo;
import com.mcmc.hn.dao.interfaces.UserManagementDao;

public class LoggingInterceptor implements MethodBeforeAdvice,SessionAware{ //, AfterReturningAdvice, ThrowsAdvice
    private static Log log = null;
    Map<String, Object> sesionMap=null;
    HttpSession session = null;
    UserManagementDao userManagementDao;


public LoggingInterceptor(){
}

public void before(Method arg0, Object[] arg1, Object arg2) throws Throwable {
    log = LogFactory.getLog(arg2.getClass());
    log.info("Beginning method: "+arg0.getName());
    System.out.println("BEFORE>>>>>>>>>>>>>>>Beginning method: "+arg0.getName());

    HashMap loggingDescription = new HashMap(); 
    loggingDescription.put(new Integer(1),"This is a method to display List of Users");
    loggingDescription.put(new Integer(2),"This is a method to display account Information of the logged-in User");

     UserInfo user = (UserInfo)sesionMap.get(MCMCConstants.USER_INFO_OBJECT); <-- THIS IS WHERE NULL POINTER EXCEPTION IS GENERATED.
    String usrName = user.getFname() + " " + user.getLname();
    String usrId = user.getUser_id();
    String method="";
    if(arg0.getName().equals("displayUser")){
        method = (String) loggingDescription.get(1);
    }else{
        method = (String) loggingDescription.get(2);
    }
    userManagementDao.logInfo(method,usrName,usrId);
}

public void setSession(Map<String, Object> map) {
    this.sesionMap = map;
}
}        

的applicationContext.xml ---&GT;属性代码

<!-- Bean configuration -->
<bean id="proxyBean" class="org.springframework.aop.framework.ProxyFactoryBean" >
    <property name="proxyInterfaces" value="com.mcmc.hn.dao.interfaces.UserManagementDao">
    </property>
    <property name="target">
        <ref local="userManagementDao" />
    </property>
    <property name="interceptorNames">
        <list>
            <value>theTracingBeforeAdvisor</value>
        </list>
    </property>
</bean> 

    <!-- Bean Classes -->

<!-- <bean id="userManagementDao" class="com.mcmc.hn.dao.UserManagementDaoImpl" /> -->
<!-- Advisor pointcut definition for before advice -->
<bean id="theTracingBeforeAdvisor" class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">
    <property name="advice">
        <ref local="theTracingBeforeAdvice" />
    </property>
    <property name="pattern">
        <value>.*displayUser.*</value>
    </property>
</bean>

<!-- Advisor pointcut definition for after advice -->

<!-- Advice classes -->
<bean id="theTracingBeforeAdvice" class="com.mcmc.utility.LoggingInterceptor" />

UserManagementAction.java ---&gt;动作类

public class UserManagementAction extends ActionSupport implements ModelDriven<UserInfo>, RequestAware,SessionAware, ServletResponseAware, ServletRequestAware {


private UserInfo userInfo = new UserInfo();
private UserAddress userAddress = new UserAddress();

UserManagementDao userManagementDao;
KeywordCategoryDao keywordCategoryDao;

HttpServletRequest request = null;  
HttpServletResponse response = null;
HttpSession session = null;
/*ProxyFactoryBean proxyBean = null;*/

Map<Long, Object> userSessionMap=new HashMap<Long, Object>();  // Map is used to hold the user session reference in Servlet Context 

String userName="";
String password="";
String remStatus="";

Map<String, Object> reqMap=null;
Map<String, Object> sesionMap=null;

String usrName="";              //Variables for logging 
String usrId="";



/**
 * Calls a function to retrieve the values from Database. 
 * @return SUCCESS in oder to load the JSP page.
 */
@SuppressWarnings({ "unchecked" })

public String displayUser(){

    UserInfo user = (UserInfo)sesionMap.get(MCMCConstants.USER_INFO_OBJECT);
    usrName = user.getFname() + " " + user.getLname();
    usrId = user.getUser_id();
    String method="This is a method to display List of Users";
    userManagementDao.logInfo(method,usrName,usrId);

    ApplicationContext appContext = new FileSystemXmlApplicationContext("classpath:../../WEB-INF/applicationContext.xml");
    UserManagementDao userManagementDao=(UserManagementDao) appContext.getBean("proxyBean");
    List<UserInfo>  Lst  = userManagementDao.displayUser();
    reqMap.put("userList", Lst);

    return SUCCESS;
}

    public String login(){
    ApplicationContext appContext = new FileSystemXmlApplicationContext("classpath:../../WEB-INF/applicationContext.xml");
    UserManagementDao userManagementDao=(UserManagementDao) appContext.getBean("proxyBean");
    String returnStatus = SUCCESS;
    session = request.getSession();
    long usr_id;
    long roleId;
    int count=0,flag=0;
    Map<Long, Object> userMap=new HashMap<Long, Object>();

    int status=0;
    if(remStatus.equals("on")){
        status=1;
    }else{
        status=0;
    }
    session.setAttribute("status", status);

    UserInfo user=userManagementDao.login(userName, password);
    userMap=(Map<Long, Object>)session.getServletContext().getAttribute(MCMCConstants.USER_SESSION_REFERENCE_MAP); //Retrieving userMap from Servlet Context with User Session Info

    if( userMap!= null){
        if(userMap.containsKey(user.getId())){
            flag=1;
        }
    }

    if(user!=null && flag==0 ){
        count=1;
        sesionMap.put(MCMCConstants.USER_INFO_OBJECT, user);<--THIS IS THE DATA THAT IS IN SESSION THAT I NEED TO ACCESS IN LOGGINGINTERCEPTOR.java
        usr_id=user.getId();
        roleId=user.getRoleId();            
        //System.out.println("USERID::::::"+roleId);
        sesionMap.put(MCMCConstants.USER_INFO_ID,usr_id);
        sesionMap.put(MCMCConstants.USER_ROLE_ID,roleId);
        // Loading Constants into Session
        SessionUtility.loadCategoryList(sesionMap, keywordCategoryDao);
        if(status==1){
            Cookie cookie = new Cookie ("loginData",userName + "|" + password+"?" + status);
            response.addCookie(cookie);
        }

        userSessionMap.put(user.getId(), user.getUser_id());
        session.getServletContext().setAttribute(MCMCConstants.USER_SESSION_REFERENCE_MAP, userSessionMap); //Setting userSessionMap to ServletContext

        returnStatus=SUCCESS;
    }else{
        returnStatus= "input";
    }

    return returnStatus;
}

/* Getter And Setter Methods as required */
}

2 个答案:

答案 0 :(得分:0)

为什么这不是空的? UserManagementDao尚未注入LoggingInterceptor,也未初始化。实际上它已在配置文件中注释掉了

<!--<bean id="userManagementDao" class="com.mcmc.hn.dao.UserManagementDaoImpl"/>-->

除非userManagementDao中有@Repository和组件扫描,否则它甚至不是Spring bean。请仔细阅读他的参考资料http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/htmlsingle/spring-framework-reference.html#beans-introduction

答案 1 :(得分:0)

你宣布了

Map<String, Object> sesionMap=null;

这里生成了空指针:

UserInfo user = (UserInfo)sesionMap.get(MCMCConstants.USER_INFO_OBJECT); 

在这里使用相同的sessionMap ...这就是获取nullpointer的原因。