簡體   English   中英

如何在Java的Spring Aop logger類內的會話中訪問任何數據?

[英]How can i access any data in session inside spring aop logger class in java?

我是Spring AOP的新手,我正在嘗試為Action類實現日志記錄。現在我還想在日志記錄時將某些信息保存在數據庫中。為此,我需要在會話中訪問某些數據記錄器類,但嘗試訪問它,則發生“空指針異常”。 任何幫助將不勝感激...謝謝

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 --->屬性代碼

<!-- 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 ---> Action類

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 */
}

你宣布

Map<String, Object> sesionMap=null;

空指針在這里生成:

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

在這里使用相同的sessionMap ...這就是為什么獲取nullpointer的原因。

為什么這個不為null? 沒有將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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM