当前位置:首页 > 资讯 > info6 > 正文

spring+mybatis

发表于: 2015-02-12 ? 作者:chelsi916 ? 来源:转载 ? 浏览:
摘要: DisableUrlSessionFilter.java packagecom.sf.hkbw.context.filter; importjava.io.IOException; importjavax.servlet.Filter; importjavax.servlet.FilterChain; importjavax.servlet.FilterConfig; importjavax
DisableUrlSessionFilter.java
package com.sf.hkbw.context.filter;

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;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import javax.servlet.http.HttpSession;

public class DisableUrlSessionFilter implements Filter {
	
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		if (!(request instanceof HttpServletRequest)) {
			chain.doFilter(request, response);
			return;
		}

		HttpServletRequest httpRequest = (HttpServletRequest) request;
		HttpServletResponse httpResponse = (HttpServletResponse) response;

		if (httpRequest.isRequestedSessionIdFromURL()) {
			HttpSession session = httpRequest.getSession();
			if (session != null) {
				session.invalidate();
			}
		}
		
		// wrap response to remove URL encoding
		HttpServletResponseWrapper wrappedResponse = new HttpServletResponseWrapper(httpResponse) {
			
			@Override
			public String encodeRedirectUrl(String url) {
				return url;
			}

			public String encodeRedirectURL(String url) {
				return url;
			}

			public String encodeUrl(String url) {
				return url;
			}

			public String encodeURL(String url) {
				return url;
			}
		};
		chain.doFilter(request, wrappedResponse);
	}

	public void init(FilterConfig config) throws ServletException {
		
	}

	public void destroy() {
		
	}
}

LoginInterceptor.java

package com.sf.hkbw.context.interceptor;

import java.net.URLEncoder;
import java.util.List;

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

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.sf.hkbw.entity.Address;
import com.sf.hkbw.entity.ResultVO;
import com.sf.hkbw.utils.Constants;
import com.sf.hkbw.utils.CookieUtil;
import com.sf.hkbw.utils.LbsUtil;
import com.sf.hkbw.utils.StringUtils;


/**
 * 拦截器
 * @author 674045
 *
 */
public class LoginInterceptor implements HandlerInterceptor {


    /**
     * 不需要登录的url(完整)
     */
    private List excludeUris;
    /**
     * 不需要登录的url(开头)
     */
    private List excludeStartsUris;
    
    public List getExcludeUris() {
		return excludeUris;
	}

	public void setExcludeUris(List excludeUris) {
		this.excludeUris = excludeUris;
	}

	public List getExcludeStartsUris() {
		return excludeStartsUris;
	}

	public void setExcludeStartsUris(List excludeStartsUris) {
		this.excludeStartsUris = excludeStartsUris;
	}

	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3) throws Exception {
    }

    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3) throws Exception {
    }

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
//        request.setCharacterEncoding("UTF-8");
//        response.setCharacterEncoding("UTF-8");
//        response.setContentType("text/html;charset=UTF-8");
//        String url = request.getRequestURI();
//        if (excludeUris.contains(url)) {
//            return true;
//        }
//        for (String startsUrl : excludeStartsUris) {
//            if (url.startsWith(startsUrl)) {
//                return true;
//            }
//        }
//        if(request.getCookies()!=null){
//        	 return true;
//        }
//        
//        String postIp =LbsUtil.getIpAddr(request);
//        /**
//         * 通过IP判断用户地址
//         */
//        ResultVO addressOfIp = LbsUtil.getAddress("ip=220.198.192.12", "utf-8");	
//        if(addressOfIp !=null){
//	        Address address = addressOfIp.getData();
//	        if(StringUtils.isBlank(address.getCity())){
//	        	redirectUrl(request,response,url);
//	    		return false;
//	        }else{	        	 
//	    		CookieUtil.setCookie(request, response,Constants.CITY ,URLEncoder.encode(address.getCity(), "utf-8"));
//	    		CookieUtil.setCookie(request, response,Constants.CITY_ID ,address.getCity_id());  
//	        	return true;
//	        }  
//        }else{
//        	redirectUrl(request,response,url);
//    		return false;
//        }
    	return true;
        
    }

//    private void redirectUrl(HttpServletRequest request,HttpServletResponse response, String url ) throws Exception{
//    	String param = request.getQueryString();
//		if (param == null) {
//			param = "";
//        } else {
//        	param = "?" + param;
//        }
//		String redirect_url = StringUtils.getEncoder(url + param);
//		response.sendRedirect("/ip/resetCity?url=" + redirect_url);
//    }
  
}

BaseController.java

package com.sf.hkbw.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;

import com.sf.hkbw.config.LogAppender;
import com.sf.hkbw.entity.AdminFunctions;
import com.sf.hkbw.entity.AdminUsers;
import com.sf.hkbw.entity.ErrorLog;
import com.sf.hkbw.entity.vo.ResultDTO;
import com.sf.hkbw.service.AdminFunctionsService;
import com.sf.hkbw.service.ErrorLogService;
import com.sf.hkbw.utils.CommonHelper;
import com.sf.hkbw.utils.PrimaryKeyGen;


/**
 * 
 * @author sfit0709
 *
 */
@Controller
public class BaseController {
	//日志对象
	protected final transient Logger log = Logger.getLogger(LogAppender.DEFAULT);
	protected HttpServletRequest request;
	protected HttpServletResponse response;
	protected HttpSession session;
	
	//菜单
	@Autowired private AdminFunctionsService adminFunctionsService;	
    //异常处理
	@Autowired private ErrorLogService errorLogService;
	
	@ModelAttribute
	public void setRequestAndResponse(HttpServletRequest request, HttpServletResponse response) {
		this.request = request;
		this.response = response;
		this.session = request.getSession(true);
	}
	
	public void writeJSON(String status, String message) {
		try {
			response.setContentType("text/html; charset=utf-8");
			if (null == status) status = "";
			if (null == message) message = "";
			Map map = new HashMap();
			map.put("status", status);
			map.put("message", message);
			response.getWriter().print(JSONObject.fromObject(map));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void writeJSON(String status) {
		try {
			response.setContentType("text/html; charset=utf-8");
			if (null == status) status = "";
			Map map = new HashMap();
			map.put("status", status);
			response.getWriter().print(JSONObject.fromObject(map));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	public void writeJSON(String status, String message, HttpServletResponse response) {
		try {
			response.setContentType("text/html; charset=utf-8");
			
			if (null == status) status = "";
			if (null == message) message = "";
			
			Map map = new HashMap();
			map.put("status", status);
			map.put("message", message);
			
			response.getWriter().print(JSONObject.fromObject(map));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void writeJSON(Object status, Object message, HttpServletResponse response) {
		try {
			response.setContentType("text/html; charset=utf-8");
			
			if (null == status) status = "";
			if (null == message) message = "";
			
			Map map = new HashMap();
			map.put("status", status);
			map.put("message", message);
			
			response.getWriter().print(JSONObject.fromObject(map));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 输出到页??
	 * @param str 输出参数
	 * @param charset 编码格式
	 */
	protected void writeAjaxResult(String str, String charset, HttpServletResponse response) {
		try {
			response.getOutputStream().write(str.getBytes(charset));
		} catch (Exception e) {
			log.error("ajax output exception", e);
		}
	}

	/**
	 * 输出到页??默认编码格式UTF-8
	 * @param str 输出参数
	 */
	protected void writeAjaxResult(String str, HttpServletResponse response) {
		try {
			this.writeAjaxResult(str, "UTF-8", response);
		} catch (Exception e) {
			log.error("ajax output exception", e);
		}
	}
	
	public void responseResult(Object result, HttpServletResponse response){
		try {
			response.setContentType("text/html;charset=utf-8");
			response.getWriter().print(result);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void responseJson(Object obj, HttpServletResponse response){
		try {
			response.setContentType("application/json;charset=utf-8");
			response.getWriter().print(JSONObject.fromObject(obj));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public  void resultString (int status, String msg, Object data, HttpServletResponse response) {
		ResultDTO result = setResultDTO(status, msg);
		result.setData(data);
		responseJson(result, response);
	}
	
	public  void resultList (int status, String msg, List list, HttpServletResponse response) {
		ResultDTO result = setResultDTO(status, msg);
		result.setList(list);
		responseJson(result, response);
	}
	
	public  void resultMap (int status, String msg, Map map, HttpServletResponse response) {
		ResultDTO result = setResultDTO(status, msg);
		result.setMap(map);
		responseJson(result, response);
	}
	
	private  ResultDTO setResultDTO(int status, String msg) {
		ResultDTO result = new ResultDTO();
		result.setStatus(status);
		result.setMsg(msg);
		return result;
	}
	
	public List getBtns(AdminUsers adminUser,String url){
		System.out.println(url);
		Map params = new HashMap();
		params.put("userId", adminUser.getId());
		params.put("jspUrl", url);
		return adminFunctionsService.getJspButtonList(params);	
	}
	
	/**
	 * TODO  记录抛出异常信息
	 * @author WangFei 681487
	 * @date   2015-2-6下午5:35:20
	 */
	
	
	/**
	 * TODO  记录异常信息
	 * @param adminUser
	 * @param className
	 * @param methodName
	 * @param serverIp
	 * @param ex
	 * @author WangFei 681487
	 * @date   2015-2-6下午5:45:13
	 */
	public void addErrorLog(AdminUsers adminUser,String className,String methodName,Exception ex){
		ErrorLog errorLog= new ErrorLog();
		errorLog.setId(PrimaryKeyGen.genPrimaryKey());
		errorLog.setClassName(className);
		errorLog.setMethodName(methodName);
		errorLog.setServerIp(CommonHelper.getServerId());
		errorLog.setStatus("0");
		errorLog.setLogText(ex.toString());
		errorLog.setCreateBy(adminUser.getUserName());
		errorLogService.addErrorLog(errorLog);
	}
}

applicationContext.xml




	
	
		
			
				
			
		
	
	
	

	
	
		
		
		
	
	
	
	  
          
     

	
	
		
			
			
				
					
					     /login
					
				
				
					
					    /api/index
					
				
			
		
	

	
	
		
			10000000
		
		
			4096
		
	

	


jdbc.properties

#jdbc2 mysql wf127.0.0.1
#jdbc.driver=com.mysql.jdbc.Driver
#jdbc.url=jdbc:mysql://127.0.0.1:3306/oma
#jdbc.username=root
#jdbc.password=123456

#jdbc2 mysql 10.118.46.20
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://10.118.46.20:3306/OMA?useUnicode=true&characterEncoding=utf8
jdbc.username=mysql
jdbc.password=

jdbc.maxActive=100
jdbc.maxIdle=30
jdbc.maxWait=10000


log4j.properties:

log4j.logger.com.springframework=DEBUG
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  
log4j.logger.java.sql.ResultSet=DEBUG

log4j.rootLogger = INFO,default
log4j.additivity.org.apache=false

log4j.logger.register = INFO, register
log4j.logger.login = INFO, login
log4j.logger.role = INFO, role
log4j.logger.menu = INFO, menu
log4j.logger.api = INFO, api
log4j.logger.orders = INFO, orders
log4j.logger.adminuser = INFO, adminuser
log4j.logger.apiLog = INFO, apiLog
log4j.logger.propertyValueSet = INFO, propertyValueSet
log4j.logger.accountDetail = INFO, accountDetail

# ConsoleAppender DailyRollingFileAppender#
### set default appender ###
log4j.appender.default = org.apache.log4j.ConsoleAppender
log4j.appender.default.layout=org.apache.log4j.PatternLayout
log4j.appender.default.layout.ConversionPattern=[%-5p] [%c] [%d{yyyy-MM-dd HH:mm:ss,SSS}] [%t] [%l] - [%m]%n

### register ###
log4j.appender.register = org.apache.log4j.DailyRollingFileAppender
log4j.appender.register.file = /app/applogs/HBMS-OMA/register/register.log
log4j.appender.register.DatePattern='.'yyyy-MM-dd
log4j.appender.register.layout=org.apache.log4j.PatternLayout
log4j.appender.register.layout.ConversionPattern=[%-5p] [%c] [%d{yyyy-MM-dd HH:mm:ss,SSS}] [%t] [%l] - [%m]%n\

### login ###
log4j.appender.login = org.apache.log4j.DailyRollingFileAppender
log4j.appender.login.file = /app/applogs/HBMS-OMA/login/login.log
log4j.appender.login.DatePattern='.'yyyy-MM-dd
log4j.appender.login.layout=org.apache.log4j.PatternLayout
log4j.appender.login.layout.ConversionPattern=[%-5p] [%c] [%d{yyyy-MM-dd HH:mm:ss,SSS}] [%t] [%l] - [%m]%n\

WebContent/WEB-INF/spring-servlet.xml



    
    
	
	
	
	
	
	
		
		
		
		
	

	
		
		
	
		
	
		
	

 	
		
		
		
		
	

	
	
		
	

	

	
	
		
			
			
			
			
			
			
			
			
			
			
		
	

	
	
		
		
	

	
		
	

	
		
	
	
	
	    
	    
	

web.xml



  
    characterEncodingFilter
    org.springframework.web.filter.CharacterEncodingFilter
    
      encoding
      UTF-8
    
  
  
    characterEncodingFilter
    /*
  
  
    jsessionid
    com.sf.hkbw.context.filter.DisableUrlSessionFilter
  
  
    jsessionid
    /*
  
  
    contextConfigLocation
    classpath:applicationContext.xml,WEB-INF/spring-servlet.xml
  
  
    org.springframework.web.context.ContextLoaderListener
  
  
    org.springframework.web.context.request.RequestContextListener
  
  
    spring
    org.springframework.web.servlet.DispatcherServlet
    1
  
  
    spring
    /
  
  
    default
    *.jpg
  
  
    default
    *.swf
  
  
    default
    *.JPG
  
  
    default
    *.png
  
  
    default
    *.gif
  
  
    default
    *.jpeg
  
  
    default
    *.js
  
  
    default
    *.css
  
  
    default
    *.xml
  
  
    default
    *.html
  
  
    default
    *.htm
  
  
    default
    *.exe
  
  
    default
    *.ico
  
  
    default
    *.properties
  
  
    default
    *.txt
  
  
    default
    *.pdf
  
  
    404
    /error/404.html
  
  
    500
    /error/500.html
  
  
    /index.jsp
  
  
    VerifyCodeServlet
    com.sf.hkbw.utils.VerifyCodeServlet
    
      num
      4
    
    
      content
      abcdefghijklmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ23456789
    
  
  
    VerifyCodeServlet
    /security/random
  
  
    omaDS
    javax.sql.DataSource
    Container
  
  
  
	


spring+mybatis

版权所有 IT知识库 CopyRight ? 2009-2015 IT知识库 IT610.com , All Rights Reserved. 京ICP备09083238号