我想在我的系统中做一些日志,比如用户操作,我知道在servicelet中我可以得到请求的所有session,参数等。
所以我想写Servlet
public class UserActionCheck extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession();
Map map = request.getParameterMap();
Set keSet = map.entrySet();
for (Iterator itr = keSet.iterator(); itr.hasNext(); ) {
Map.Entry me = (Map.Entry) itr.next();
Object ok = me.getKey();
Object ov = me.getValue();
String[] value = new String[1];
if (ov instanceof String[]) {
value = (String[]) ov;
} else {
value[0] = ov.toString();
}
for (int k = 0; k < value.length; k++) {
System.out.println(ok + "=" + value[k]);
}
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//HttpSession session = request.getSession();
}
}
然后我可以在tomcat控制台看到参数输出,但我得到的是空白页面。
似乎页面在 doGet
方法...
那么我应该如何让它继续下去呢?
用那个 RequestDispatcher
?
也是如何处理在 doPost
?
对于你的目的,最好的方法是使用一个叫做 Filter
.
例子 :
@WebFilter(filterName = "monitoringFilter", urlPatterns = { "/*" })
public class MonitoringFilter implements Filter
{
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
{
// Right here do your stuff pretty much like in a servlet
request // ... get information you need
// Process request as normal
chain.doFilter(request,response);
}
@Override
public void init(FilterConfig config) throws ServletException
{
}
@Override
public void destroy()
{
}
}
更多信息 :
你应该使用 log4j 和 文件处理程序 在你的应用程序中实现日志记录.类似这样:::
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
class A{
static Log log = LogFactory.getLog(A.class);
void methodA(){
try{
log.info("I am inside A");
} catch(Exception e) {
log.error("error" , e);
}
}
}