码迷,mamicode.com
首页 > 编程语言 > 详细

java springmvc Log4j filter等(稍微完善一下项目)

时间:2016-06-08 15:38:40      阅读:496      评论:0      收藏:0      [点我收藏+]

标签:

仅供参考-接上文

springmvc 

1.设置Log4jConfigListener日志监听(可以为开发调试、发布后运行的意外调试、等)

  在src/main/resources目录下新建log4j.properties文件(可以在别的目录),这些配置内容网上有很多,

 

# This is the configuring for logging displayed in the Application Server
log4j.rootCategory=error, stdout, logfile
#log4j.rootCategory=debug, stdout, logfile
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %5p (%F:%L) - %m%n
log4j.logger.org.springframework=WARN
log4j.logger.org.mybatis.SQL=DEBUG
log4j.logger.org.springframework.transaction=WARN
log4j.logger.org.springframework.orm=WARN
log4j.logger.com.google.code.yanf4j=WARN
log4j.logger.net.rubyeye.xmemcached=WARN
log4j.logger.org.mybatis.spring=WARN
log4j.logger.org.apache.activemq=WARN
log4j.logger.providers.XmlConfigurationProvider=WARN
#log4j.logger.org.springframework.web.servlet.DispatcherServlet=WARN
#log4j.logger.org.acegisecurity=INFO
#log4j.logger.org.springframework.web.servlet.handler=INFO
#### First appender writes to console
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout

log4j.appender.stdout.layout.ConversionPattern=%-4p,%t,%d{MM-dd HH:mm:ss.SSS},%c{2}.%M:%L - %m%n

log4j.appender.logfile=org.apache.log4j.RollingFileAppender
log4j.appender.logfile.File=${catalina.base}/logs/ecms.log
log4j.appender.logfile.MaxFileSize=1024KB
# Keep 9 backup files.
log4j.appender.logfile.MaxBackupIndex=9 
# Pattern to output: date priority [category] - message
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d %t %p [%c] - %m%n

log4j.logger.com.ibatis=debug
log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=debug
log4j.logger.com.ibatis.common.jdbc.ScriptRunner=debug
log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate=debug

log4j.logger.java.sql.Connection=debug
log4j.logger.java.sql.Statement=debug
log4j.logger.java.sql.PreparedStatement=debug,stdout 

 

  在web.xml文件中配置一下

<!-- 日志  -->
      <listener>
        <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
    </listener>
    <context-param>
        <param-name>log4jConfigLocation</param-name>
        <!-- 这里对应的配置文件目录  -->
        <param-value>classpath:log4j.properties</param-value>
    </context-param>
    <context-param>
        <param-name>webAppRootKey</param-name>
        <param-value>webName.root</param-value>
    </context-param>
    <!-- 开一条watchdog线程每6秒扫描一下配置文件的变化  -->
    <context-param>
        <param-name>log4jRefreshInterval</param-name>
        <param-value>60000</param-value>
    </context-param>

  这样配置好了,可以启动一下工程登入,看看控制台是否输出sql等

2.过滤器filter(设置路径,方便前台获取)在com.springmvc.util.action包下新建SetCharacterEncodingFilter类实现Filter

技术分享
package com.springmvc.util.action;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 * 过滤器
 * @author 
 *
 */
public class SetCharacterEncodingFilter implements Filter{

    @Override
    public void destroy() {
        
    }
    @Override
    public void doFilter(ServletRequest arg0, ServletResponse arg1,
            FilterChain arg2) throws IOException, ServletException {
        String path = arg0.getServletContext().getContextPath();
        String basePath = arg0.getScheme()+"://"+arg0.getServerName()+":"+arg0.getServerPort()+path+"/";
        arg0.setAttribute("basePath", basePath);//设置url路径
        arg2.doFilter(arg0, arg1);//通过
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {
    }

}
SetCharacterEncodingFilter

  可以在实现方法中设置很多内容,例如:日志、权限、安全等内容,在doFilter方法中,获取工程路径,设置一下在页面方便获取

  在web.xml设置,之前搭建项目是使用过filter,定义编码

<!--配置过滤器-->
    <filter>
    <!--过滤器名称,随便定义-->
            <filter-name>UrlFilter</filter-name>
    <!--filter-class指向自定义的过滤器,完整的包名+类名-->
            <filter-class>
                com.springmvc.util.action.SetCharacterEncodingFilter
            </filter-class>
    <!--过滤器中的默认参数,默认的字符编码是UTF-8-->
            <init-param>
                <param-name>defaultEncoding</param-name>
                <param-value>UTF-8</param-value>
            </init-param>
    </filter>
    <!--filter和filter-mapping是成对出现的-->
        <filter-mapping>
    <!--过滤器名称,一定要和上面的一样,-->
            <filter-name>UrlFilter</filter-name>
    <!--表示拦截所有的请求-->
            <url-pattern>/*</url-pattern>
        </filter-mapping>

  这样可以在页面获取绝对路径了

技术分享
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<jsp:include page="/WEB-INF/util/bootstrap.jsp"></jsp:include>
<script type="text/javascript"  src="${basePath }static/view/js/login.js"> </script>
<title>登入</title>
<style type="text/css">
    .tab-content{
        position:absolute;
        height:200px;
        width:300px;
        margin-top:180px;
        margin-left:50%;
        left:-150px;
    }
    .login-input{
        margin :20px 0px;
        width : 300px;
    }
</style>
</head>
<body>
    <div class="tab-content">
        <ul class="nav nav-tabs">
           <li class="active"><a href="#login" aria-controls="login" role="tab" data-toggle="tab" aria-controls="login">登录</a></li>
           <li><a href="#register" aria-controls="register" role="tab" data-toggle="tab" aria-controls="register">注册</a></li>
       </ul>
        <!-- Tab Log in -->
        <form class="tab-pane fade in active" id="login" onsubmit="return false;">
            <c:if test="${!empty error }">
                <c:out value="${error }"/>
            </c:if>
            <input id="login-email" name="email" class="form-control login-input" placeholder="邮箱">
            <input type="password" name="password" id="login-password" class="form-control login-input" placeholder="密码">
            <div class="checkbox">
            <label class="f-white" style="color:white;">
            <input type="checkbox" id="login-remember"> 记住我
            </label>
            <a class="pull-right" href="javascript:void(0);" style="color:#33B74B;">忘记密码</a>
            </div>
            <button class="btn btn-lg btn-primary btn-block" onclick="loginFunction.loginSubmit();">登录</button>
        </form>
        <!-- Tab Register -->
        <form  class="tab-pane fade" id="register" onsubmit="return false;">
            <input id="login-email" class="form-control login-input" placeholder="邮箱">
            <input type="password" class="form-control login-input" placeholder="密码">
            <button class="btn btn-lg btn-primary btn-block">注册</button>
        </form> 
    </div>
    <div id="banner" style="background-image:url(${basePath }static/images/banner-image.jpg);height:575px;width:100%;"> 
    </div>
</body>
</html>
页面
技术分享
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%-- <%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>  --%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">

<link href="${basePath }static/bootstrap/css/bootstrap.min.css" rel="stylesheet">

<script type="text/javascript" src="${basePath }static/js/jquery.min.js"></script>
<script type="text/javascript" src="${basePath }static/bootstrap/js/bootstrap.min.js"></script>
<script type="text/javascript">
    var basePath = "${basePath}";
</script>
</head>
页面
技术分享
var loginFunction={
        //登入
        loginSubmit : function(){
            var email = $("#login-email").val();//邮箱
            var password = $("#login-password").val();//密码
            if(email =="") {
                alert("请输入邮箱");
                return;
            }
            if(password =="") {
                alert("请输入密码");
                return;
            }
            //$("#login").attr("action",basePath+"index.htm");
            //$("#login").submit();
            $.ajax({
                url: basePath+"101/loginCheck.htm",
                type:"post",
                data:{email : email,password:password},//密码得加密
                dataType:"json",
                success: function(data){
                    if(data.status == "success"){
                        window.location.href = basePath+"101/index.htm";
                    }else{
                        alert("用户名或密码错误");
                    }
                },  
                error : function(data) {
                    
                }
            });
            
        }
};
$(function(){
});
js

  可以在公共页面这样设置,在引用js中可以使用

<script type="text/javascript">
    var basePath = "${basePath}";
</script>

3.根据项目需求,设置一些公共类,可以设置一些类继承,这样相对来说就规范和方便一些

  在com.springmvc.util.model包下简单设置两个类HttpStatus.java、Response.java

技术分享
package com.springmvc.util.model;

public class HttpStatus {

    public final static String HTTP_SUCCESS = "success"; // 操作成功
    public final static String HTTP_ERROR = "error"; // 操作失败
    public final static String HTTP_500 = "500"; // 服务器内部错误
}
HttpStatus.java
技术分享
package com.springmvc.util.model;

import java.util.HashMap;
import java.util.Map;

public class Response {
    private String status;
    private String message;
    private Map<String, Object> parameter;

    public void addAttribute(String key, Object value) {
        if (parameter == null) {
            parameter = new HashMap<String, Object>();
        }
        parameter.put(key, value);
    }

    public void setStatusAndMessage(String status, String message) {
        this.status = status;
        this.message = message;
    }
    
    public void setSuccess(String message) {
        this.status = HttpStatus.HTTP_SUCCESS;
        this.message = message;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public Map<String, Object> getParameter() {
        return parameter;
    }

    public void setParameter(Map<String, Object> parameter) {
        this.parameter = parameter;
    }

}
Response.java

  在com.springmvc.util.action包中新建BaseAction.java类,所有action都可以继承BaseAction.java,在这里设置request、response、session等

  在这个类中使用@ModelAttribute注解

package com.springmvc.util.action;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ModelAttribute;

import com.springmvc.util.model.Response;

public class BaseAction{
    
    public Response responseUtil;
    private HttpServletRequest request;
    private HttpServletResponse response;  
    private HttpSession session; 
    /**
     * 验证一个值是否为空值
     * 
     * @param str
     * @return
     */
    public boolean isEmpty(Object str) {
        return StringUtils.isEmpty(str);
    }

    public boolean isEmpty(List<?> list) {
        if (list == null)
            return true;
        if (CollectionUtils.isEmpty(list))
            return true;
        return false;
    }
       
    @ModelAttribute  
    public void setReqAndRes(HttpServletRequest request, HttpServletResponse response){  
        this.request = request;  
        this.response = response;  
        this.session = request.getSession();  
    }
    public HttpServletRequest getRequest() {
         return this.request;
    }
     public HttpServletResponse getResponse() {
         return this.response;
     }
     
     public HttpSession getSession() {
         return this.session;
     }
}
package com.springmvc.action;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.springmvc.model.User;
import com.springmvc.service.UserService;
import com.springmvc.util.action.BaseAction;
import com.springmvc.util.model.HttpStatus;
import com.springmvc.util.model.Response;

@Controller
@RequestMapping(value = "/101")
public class IndexAction extends BaseAction {

    @Autowired
    private UserService userService;

    /**
     * 首页
     * 
     * @return
     */
    @RequestMapping(value = "/index.htm")
    public String index() {
        return "index";
    }

    /**
     * 登入页面
     * 
     * @return
     */
    @RequestMapping(value = "/login.htm")
    public String login() {
        return "login";
    }

    /**
     * 登入验证
     * 
     * @return
     */
    @RequestMapping(value = "/loginCheck.htm", method = RequestMethod.POST)
    @ResponseBody
    public Response loginCheck(User user) {
        responseUtil = new Response();
        List<User> list = userService.getUser(user);
        if (list != null && list.size() > 0) {
            responseUtil.setStatusAndMessage(HttpStatus.HTTP_SUCCESS, "验证成功");
        }
        return responseUtil;
    }

}

个人笔记

java springmvc Log4j filter等(稍微完善一下项目)

标签:

原文地址:http://www.cnblogs.com/wangyingwei/p/5569916.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!