效果图:
主要代码:
index.jsp
(这里的index为action的name)
<a href="index">点击我</a>
main.jsp
(打印日志 : 用户id+创建时间+action名和方法名)
用户id:${rb.userId }<br>
创建时间:${rb.nowDate }<br>
action名和方法名:${rb.actionName }
BaseAction.java
(作为一个工具类主要是获取HttpServletRequest和HttpSession)
public class BaseAction extends ActionSupport{
/**
* 获取request
* @return
*/
public HttpServletRequest getRequest() {
return ServletActionContext.getRequest();
}
/**
* 获取HttpSession
*/
public HttpSession getSession() {
return getRequest().getSession();
}
}
LogAction.java
(日志)
public class LogAction extends BaseAction{
public String index() {
getSession().setAttribute("userId", "10086");
getSession().setAttribute("ctx", "/struts2");
return "success";
}
}
LogInteceptor.java
(拦截器,拦截操作日志)
/**
* 用于记录操作日志
* @author xxs
*
*/
public class LogInteceptor extends BaseAction implements Interceptor{
/**
* 销毁方面,指程序结束
*/
@Override
public void destroy() {
// TODO Auto-generated method stub
System.out.println("销毁");
}
/**
* 初始化方面
*/
@Override
public void init() {
// TODO Auto-generated method stub
System.out.println("初始化");
}
/**
* 拦截器
*/
@Override
public String intercept(ActionInvocation invocation) throws Exception {
// 记录日志
RemarkBean rb = new RemarkBean();
String userId = (String) getSession().getAttribute("userId");
rb.setUserId(userId);
rb.setNowDate(new Date());
rb.setActionName(invocation.getProxy().getActionName()+invocation.getProxy().getMethod());
getSession().setAttribute("rb", rb);
return invocation.invoke();
}
}
struts.xml
(配置action以及拦截器)
<struts>
<package name="default" extends="struts-default">
<!-- 配置拦截器 -->
<interceptors>
<interceptor name="logInterceptor" class="cn.xxs.inteceptor.LogInteceptor"></interceptor>
</interceptors>
<action name="index"
class="cn.xxs.action.LogAction"
method="index">
<interceptor-ref name="logInterceptor"></interceptor-ref>
<result name="success">
/main.jsp
</result>
</action>
</package>
</struts>
web.xml
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>