resetful项目搭建(四):项目开始的基本开发配置

所有的项目搭建完了,接下来要做一些基本的配置开发
  • core项目的spring配置 : applicationContext-core.xml


    
    
       
     
    
    
    
        
    
    
        
    
    
    
    
        
        
            
                classpath:/jdbc/jdbc.*.properties
            
        
          
        
    
    
    
    
    
    
    

  • base项目的spring配置



    
    
        
    

    
    
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
    

    
        
            
        
        
        
            
                test.base.*.bean
            
        
        
            
                ${baseserver.hibernate.dialect}
                ${hibernate.show_sql}
                ${hibernate.format_sql}
                ${hibernate.use_sql_comments}
                none
                org.springframework.orm.hibernate5.SpringSessionContext   
                ${hibernate.hbm2ddl.auto}
                false
                true
                true 
                false
                 org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory 
            
        
    
    
        
    
    


  • core项目中重写下sql方言,处理mysql编码问题
package test.core.dialet;

import org.hibernate.dialect.MySQL5InnoDBDialect;

public class MySQL5DialectUTF8 extends MySQL5InnoDBDialect {

    @Override
    public String getTableTypeString() {
        return " ENGINE=InnoDB DEFAULT CHARSET=utf8";
    }
}

  • 在web项目中添加配置文件


    image.png

jdbc.test.properties:数据库的链接配置(*改为自己的数据库信息)

baseserver.jdbc.driverClassName=com.mysql.jdbc.Driver
baseserver.jdbc.url=jdbc\:mysql\://***\:3306/test_base?zeroDateTimeBehavior\=convertToNull&useUnicode\=true&characterEncoding\=utf-8&autoReconnect\=true&failOverReadOnly\=false
baseserver.jdbc.username=***
baseserver.jdbc.password=***
baseserver.hibernate.dialect=test.core.dialet.MySQL5DialectUTF8

test.properties : hibernate和druid的一些配置

#显示sql语句
hibernate.show_sql=true
#格式化sql语句
hibernate.format_sql=true
#在SQL中生成有助于调试的注释信息
hibernate.use_sql_comments=true
hibernate.generate_statistics=true
hibernate.hbm2ddl.auto=update
#阿里druid的配置信息
druid.maxActive=50
druid.initialSize=10
druid.maxWait=60000
druid.minIdle=1

appConfig.properties:项目启动的配置文件,主要存储一些动态配置信息

@profiles=deploy

#deploy
[appConfig]
cookieIndate=7200
apps=

log4j.properties:日志配置文件,可以不需要,视自己情况而定

 ### 设置###
log4j.rootLogger = debug,stdout,D,E

### 输出信息到控制抬 ###
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target = System.out
log4j.appender.stdout.Threshold = INFO 
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern = [%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} %l method:%n%m%n%n

### 输出DEBUG 级别以上的日志到=E://logs/debug.log ###
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File = E://logs/debug.log
log4j.appender.D.DatePattern = '.'yyyy-MM-dd 
log4j.appender.D.Append = true
log4j.appender.D.Threshold = DEBUG 
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n

### 输出ERROR 级别以上的日志到=E://logs/error.log ###
log4j.appender.E = org.apache.log4j.DailyRollingFileAppender
log4j.appender.E.File =E\://logs/error.log
log4j.appender.E.DatePattern = '.'yyyy-MM-dd  
log4j.appender.E.Append = true
log4j.appender.E.Threshold = ERROR
log4j.appender.E.layout = org.apache.log4j.PatternLayout
log4j.appender.E.layout.ConversionPattern =%-d{yyyy-MM-dd HH\:mm\:ss}  [ %t\:%r ] - [ %p ]  %m%n
  • 编写PropsUtil和GlobalConfig类,读取配置文件

PropsUtil.java

package test.core.utils;

import com.google.common.base.Strings;
import java.io.IOException;
import java.io.InputStream;
import jodd.props.Props;

public class PropsUtil
{
  private Props props = null;
  
  public PropsUtil(String filename)
    throws IOException
  {
    InputStream in = PropsUtil.class.getClassLoader().getResourceAsStream(filename);
    this.props = new Props();
    this.props.load(in);
    in.close();
  }
  
  public PropsUtil(Class s, String filename)
    throws IOException
  {
    InputStream in = s.getResourceAsStream(filename);
    this.props = new Props();
    this.props.load(in);
    in.close();
  }
  
  public Props getPorps()
  {
    return this.props;
  }
  
  public String getValue(String key, String defValue)
  {
    String result = this.props.getValue(key);
    if (Strings.isNullOrEmpty(result)) {
      return defValue;
    }
    return result;
  }
}

GlobalConfig.java

package test.core.config;

import com.alibaba.fastjson.JSON;

import java.io.IOException;

import org.apache.log4j.Logger;

import test.core.utils.PropsUtil;

public class GlobalConfig
{
  private static final Logger log = Logger.getLogger(GlobalConfig.class);
  public static boolean druidMonitor = true;
  public static boolean useClientFilter = false;
  public static String apps = null;
  //cookie有效期
  public static int cookieIndate = 86400;
  //是否开启跨域
  public static boolean cross = false;
  //authToken有效期
  public static int authValid = 86400;
  
  static
  {
    try
    {
      System.out.println("正在加载配置文件...");
      PropsUtil p1 = new PropsUtil("appConfig.properties");
      String[] profile = p1.getPorps().getActiveProfiles();
      System.out.println("profiles is " + JSON.toJSONString(profile));
      useClientFilter = Boolean.valueOf(p1.getValue("appConfig.useClientFilter", String.valueOf(useClientFilter))).booleanValue();
      cookieIndate = Integer.parseInt(p1.getValue("appConfig.cookieIndate", String.valueOf(cookieIndate)));
      cross = Boolean.valueOf(p1.getValue("appConfig.cross", String.valueOf(cross))).booleanValue();
      authValid = Integer.parseInt(p1.getValue("appConfig.authValid", String.valueOf(authValid)));
      apps = p1.getPorps().getValue("appConfig.apps");
    }
    catch (IOException e)
    {
      log.warn("读取 appConfig.props 出错!", e);
    }
  }
}
  • jersey的相关配置类:RestApplication.java
package test.core.config;
import org.codehaus.jackson.jaxrs.JacksonJsonProvider;
import org.glassfish.jersey.logging.LoggingFeature;
import org.glassfish.jersey.server.ResourceConfig;

public class RestApplication extends ResourceConfig {
    public RestApplication() {
        packages("test");
        //打印访问日志,便于跟踪调试,正式发布可清除
        register(LoggingFeature.class);
        //注册JSON转换器
        register(JacksonJsonProvider.class);
    }
}
  • 跨域相关的过滤器,解决跨域问题,重写了org.apache.catalina.filters.CorsFilter类,重写的原因貌似是因为原本的类不支持delete和put请求,类有些大,就不贴出来了,只贴出修改的部分
public static final String DEFAULT_ALLOWED_HTTP_METHODS = "GET,POST,HEAD,OPTIONS,PUT,DELETE";
  • 项目中采用实现WebApplicationInitializer的方式来代替web.xml的配置访问,编写TestWebApplicationInitializer类,定义启动配置
package test.core.config;

import com.google.common.base.Strings;

import java.util.ArrayList;
import java.util.HashMap;

import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

import org.apache.commons.lang3.StringUtils;
import org.springframework.core.annotation.Order;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.request.RequestContextListener;
import org.springframework.web.util.IntrospectorCleanupListener;
//定义执行顺序
@Order(1)
public class TestWebApplicationInitializer implements WebApplicationInitializer {
    private void setInitParameter(ServletContext servletContext) {
        ArrayList list = new ArrayList();
        //默认加载base和core项目的spring配置文件,并根据appConfig.properties中的app项动态加载其它子项目的spring配置文件
        list.add("classpath:applicationContext-core.xml");
        list.add("classpath:applicationContext-base-server.xml");
        String apps = GlobalConfig.apps;
        if (!Strings.isNullOrEmpty(apps)) {
            System.out.println("loading config files:");
            String[] applist = apps.split(";");
            for (String app : applist) {
                list.add(app);
                System.out.println("\t" + app);
            }
        }
        String config = StringUtils.join(list.toArray(), ",");
        servletContext.setInitParameter("contextConfigLocation", config);
    }

    public void onStartup(ServletContext servletContext)
            throws ServletException {
        
        setInitParameter(servletContext);
        //此监听器主要用于解决java.beans.Introspector导致的内存泄漏的问题
        servletContext.addListener(IntrospectorCleanupListener.class);
        //Spring监听器
        servletContext.addListener(ContextLoaderListener.class);
        //ServletRequestListener监听器接口
        servletContext.addListener(RequestContextListener.class);

        //Spring字符集过滤器,用于处理项目中的乱码问题
        FilterRegistration.Dynamic characterEncoding = servletContext.addFilter("characterEncoding","org.springframework.web.filter.CharacterEncodingFilter");
        characterEncoding.setInitParameter("forceEncoding", "true");
        characterEncoding.setInitParameter("encoding", "UTF-8");
        characterEncoding.addMappingForUrlPatterns(null, true,new String[] { "/rest/*" });

        //jersey的相关配置
        ServletRegistration.Dynamic jerseyServlet = servletContext.addServlet("JerseyServlet","org.glassfish.jersey.servlet.ServletContainer");
        HashMap jerseyServletMap = new HashMap();
        jerseyServletMap.put("javax.ws.rs.Application","test.core.config.RestApplication");
        
        //返回数据过滤器,使用GZIP过滤器压缩
        jerseyServletMap.put("com.sun.jersey.spi.container.ContainerRequestFilters","com.sun.jersey.api.container.filter.GzipFilter");
        
        jerseyServlet.setInitParameters(jerseyServletMap);
        jerseyServlet.setLoadOnStartup(1);
        jerseyServlet.addMapping(new String[] { "/rest/*" });
        
        //跨域过滤器
        if(GlobalConfig.cross){
            FilterRegistration.Dynamic CorsFilter = servletContext.addFilter("CorsFilter","test.core.filters.CorsFilter");
            CorsFilter.addMappingForUrlPatterns(null, true,new String[] { "/rest/*" });
            CorsFilter.setInitParameter("cors.allowed.headers", "range,content-type");
            CorsFilter.setInitParameter("cors.exposed.headers", "Content-Range");
        }
        
        //druid monitor 监控
        if (GlobalConfig.druidMonitor) {
            FilterRegistration.Dynamic druidWebStatFilter = servletContext.addFilter("DruidWebStatFilter","com.alibaba.druid.support.http.WebStatFilter");
            druidWebStatFilter.setInitParameter("exclusions","*.html,*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
            druidWebStatFilter.addMappingForUrlPatterns(null, true,new String[] { "/*" });
            
            ServletRegistration.Dynamic druidStatViewServlet = servletContext.addServlet("DruidStatView","com.alibaba.druid.support.http.StatViewServlet");
            druidStatViewServlet.addMapping(new String[] { "/druid/*" });
            druidStatViewServlet.setInitParameter("loginUsername","ourfor");
            druidStatViewServlet.setInitParameter("loginPassword","rofruo");
        }
    }
}

累了。。。明天再写

你可能感兴趣的:(resetful项目搭建(四):项目开始的基本开发配置)