EASYUI的增删改查

代码:

1

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>    
<!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">
<!-- 引入jQuery -->
<script src="${pageContext.request.contextPath}/jslib/jquery-1.9.1.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/jslib/jquery.cookie.js" charset="utf-8"></script>

<!-- 引入EasyUI -->
<link id="easyuiTheme" rel="stylesheet" href="${pageContext.request.contextPath}/jslib/jquery-easyui-1.5.1/themes/<c:out value="${cookie.easyuiThemeName.value}" default="default"/>/easyui.css" type="text/css">
<link rel="stylesheet" href="${pageContext.request.contextPath}/jslib/jquery-easyui-1.5.1/themes/icon.css" type="text/css">
<script type="text/javascript" src="${pageContext.request.contextPath}/jslib/jquery-easyui-1.5.1/jquery.easyui.min.js" charset="utf-8"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/jslib/jquery-easyui-1.5.1/locale/easyui-lang-zh_CN.js" charset="utf-8"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/jslib/jquery.edatagrid.js" charset="utf-8"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/jslib/utils.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/jslib/common.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/jslib/ajax.js"></script>
</head>
<body>
</body>
</html>

2

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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="head.jsp"></jsp:include>
<title>保单页面</title>
<script type="text/javascript">


var dataGrid;
 var searchForm;
$(function() {
searchForm = $('#searchForm').form();
dataGrid = $('#dg').edatagrid({
url : '${pageContext.request.contextPath}/premium/selectPremium',
saveUrl : '${pageContext.request.contextPath}/premium/insertPremium',
updateUrl : '${pageContext.request.contextPath}/premium/updatePremium',
destroyUrl : '${pageContext.request.contextPath}/premium/deletePremium',
fit : true,
fitColumns : true,
border : false,
pagination : true,
idField : 'chimtnum',
pageSize : 10,
pageList : [ 1,2,10, 20, 30, 40, 50 ],
/* sortName : 'typeNo',
sortOrder : 'asc', */
/* checkOnSelect : true,
selectOnCheck : false,
singleSelect:false, */
nowrap : false,
//rownumbers : true,
frozenColumns : [ [ {
field : '',
title : '保单编号',
width : 15,
checkbox : true
}, {
field : 'index',
title : '序号',
width : 30,
align : 'center',
formatter : function(val, row, index) {
return index + 1;
}
}, {
field : 'salesmannum',
title : '销售人员编号',
width : 100,
sortable : true,
editor : {
type : 'validatebox',
options : {
required : true
}
}
}, {
field : 'chimtnum',
title : '保单编号',
width : 100,
sortable : true,
editor : {
type : 'validatebox',
options : {
required : true
}
}
},  {
field : 'applicantname',
title : '投保人姓名',
width : 100,
sortable : true,
editor : {
type : 'validatebox',
options : {
required : true
}
}
} ] ],
columns : [ [ {
field : 'insuredate',
title : '投保日期',
width : 100,
sortable : true,
/* formatter:function(value,row,index){
return  new Date(value).format("yyyy-MM-dd");
}, */
editor : {
type : 'datebox',
options : {
required : true
}
}
}, {
field : 'productname',
title : '产品名称',
width : 100,
sortable : true,
editor : {
type : 'validatebox',
options : {
required : true
}
}
}] ],
toolbar : [
{
iconCls : 'icon-add',
text : '新增',
handler : function() {
dataGrid.edatagrid("unselectAll");
dataGrid.edatagrid('addRow', 0);
}
},
'-',
{
iconCls : 'icon-edit',
text : '修改',
handler : function() {
var row = $('#dg').edatagrid(
'getSelected');
var index = $('#dg').edatagrid(
'getRowIndex', row);
dataGrid
.edatagrid('editRow', index);
}
},
'-',
{
text : '删除',
iconCls : 'icon-del',
handler : function() {
var row = $('#dg').edatagrid(
'getSelected');
var index = $('#dg').edatagrid(
'getRowIndex', row);
$('#dg').edatagrid('destroyRow',
index);
}
},
'-',
{
iconCls : 'icon-save',
text : '保存',
handler : function() {
dataGrid.edatagrid('saveRow');
}
},
'-',
{
text : '取消',
iconCls : 'icon-redo',
handler : function() {
dataGrid.edatagrid('cancelRow');
}
}],
onSuccess : function(index, row) {
$.messager.show({
title : '保存',
msg : '数据【' + row.chimtnum + '】保存成功',
timeout : 1000,
showType : 'slide'
});
}
});
});


function queryUser() {
dataGrid.datagrid('load', zzt.serializeObject(searchForm));
};

</script>
</head>
<body class="easyui-layout">
<div region="north" border="false" title="过滤条件"
style="width: 100%; height: 100px; overflow: auto;" align="left">
<div id="p" class="easyui-panel" border="false">
<form id="searchForm" method="post" style="width: 100%">
<table cellspacing="8px" style="width: 100%">
<tr>
<td>销售人员编码:</td>
<td><input class="easyui-textbox" id="salesmannum"
name="salesmannum" /></td>
<td>投保日期:</td>
<td><input class="easyui-datebox" id="insuredate"
name="insuredate" /></td>
<td>投保人姓名</td>
<td><input type="text" id="applicantname" name="applicantname"
class="easyui-textbox" /></td>
<td><a href="javascript:queryUser()"
class="easyui-linkbutton" iconCls="icon-ok">查询</a>&nbsp;&nbsp;</td>
</tr>
</table>
</form>
</div>
</div>
<div region="center" border="false">
<table id="dg"></table>
</div>
</body>
</html>

页面效果:


后台代码:控制层

package com.rthd.controller;


import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.github.pagehelper.PageHelper;
import com.rthd.entity.Premium;
import com.rthd.service.PremiumService;
import com.rthd.uitl.JsonUtil;
import com.rthd.uitl.ResultDataGrid;
@Controller
@RequestMapping("/premium")
public class PremiumController {
@Autowired
private PremiumService service;
@RequestMapping("/insertPremium")

public void insertPremium(HttpServletResponse response,Premium premium) throws SQLException{
int flag=service.insertPremium(premium);
JsonUtil.toJson(response, flag);

}
@RequestMapping("/updatePremium")
public void updatePremium(HttpServletResponse response,Premium premium) throws SQLException{
int flag=service.updatePremium(premium);
JsonUtil.toJson(response, flag);
}
@RequestMapping("/selectPremium")
public void selectPremium(HttpServletResponse response,Premium premium,int page,int rows) throws SQLException{
PageHelper.startPage(page, rows);
List<Premium> list=service.selectPremium(premium);
Map<?, ?> map=(Map<?, ?>) ResultDataGrid.getResultDataGrid(list);
JsonUtil.toJson(response, map);
}
@RequestMapping("/deletePremium")
public void deletePremium(HttpServletResponse response,Premium premium) throws SQLException{
int flag=service.deletePremium(premium);
JsonUtil.toJson(response, flag);
}
}

DAO层和映射:

package com.rthd.dao;

import java.util.List;
import com.rthd.entity.Premium;


public interface PremiumDao {
public int insertPremium(Premium premium);
public int updatePremium(Premium premium);
public List<Premium> selectPremium(Premium premium);
public int deletePremium(Premium premium);
}

映射:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.rthd.dao.PremiumDao">
<resultMap type="premium" id="PremiumMap">
<id property="chimtnum" column="chimtnum" />
<result property="salesmannum" column="salesmannum" />
<result property="insuredate" column="insuredate" />
<result property="applicantname" column="applicantname" />
<result property="productname" column="productname" />
</resultMap>
<sql id="sql">salesmannum,chimtnum,insuredate,applicantname,productname</sql>

<!-- 模糊查询-->
<select id="selectPremium" resultMap="PremiumMap">
select <include refid="sql"/> from limit_premium
<where>
<if test="chimtnum!=null and chimtnum!=''">
and chimtnum like '%${chimtnum}%'
</if>
<if test="salesmannum!=null and salesmannum!=''">
and salesmannum like '%${salesmannum}%'
</if>
<if test="insuredate!=null and insuredate!=''">
and insuredate like '%${insuredate}%'
</if>
<if test="applicantname!=null and applicantname!=''">
and applicantname like '%${applicantname}%'
</if>
<if test="productname!=null and productname!=''">
and productname like '%${productname}%'
</if>
</where>
</select>
<!-- 添加 -->
<insert id="insertPremium" parameterType="premium" >
insert into limit_premium (<include refid="sql"/>)
values (#{salesmannum},#{chimtnum},#{insuredate},#{applicantname},#{productname})
</insert>
<!-- 删除 -->
<delete id="deletePremium" parameterType="premium">
delete from limit_premium where chimtnum=#{chimtnum}
</delete>
<!-- 更新 -->
<update id="updatePremium" parameterType="premium">
update limit_premium 
set salesmannum=#{salesmannum},insuredate=#{insuredate},applicantname=#{applicantname},productname=#{productname} where chimtnum =#{chimtnum}
</update>
</mapper>

实体类:对应字段

package com.rthd.entity;


import java.io.Serializable;


public class Premium implements Serializable {
/**
* 实体类
*/
private static final long serialVersionUID = 1L;
private String salesmannum;
private String chimtnum;
private String insuredate;
private String applicantname;
private String productname;
public Premium() {
}
public Premium(String salesmannum, String chimtnum, String insuredate,
String applicantname, String productname) {
this.salesmannum = salesmannum;
this.chimtnum = chimtnum;
this.insuredate = insuredate;
this.applicantname = applicantname;
this.productname = productname;
}
public String getSalesmannum() {
return salesmannum;
}
public void setSalesmannum(String salesmannum) {
this.salesmannum = salesmannum;
}
public String getChimtnum() {
return chimtnum;
}
public void setChimtnum(String chimtnum) {
this.chimtnum = chimtnum;
}
public String getInsuredate() {
return insuredate;
}
public void setInsuredate(String insuredate) {
this.insuredate = insuredate;
}
public String getApplicantname() {
return applicantname;
}
public void setApplicantname(String applicantname) {
this.applicantname = applicantname;
}
public String getProductname() {
return productname;
}
public void setProductname(String productname) {
this.productname = productname;
}
}

过滤器,解决乱码

《1》

package com.rthd.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;
/**
 * <br>
 * <b>功能:</b>通过过滤器解决项目中的get或post请求乱码问题<br>
 * <b>作者:</b>admin<br>
 * <b>日期:</b> 2017.09.01 <br>
 * <b>时间:</b>16:56<br>
 * <b>更新者:</b><br>
 * <b>更新内容:</b><br>
   <filter>
<filter-name>EncodeFilter</filter-name>
<filter-class>com.hengdait.filter.EncodeFilter</filter-class>
<init-param>
<param-name>charset</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>EncodeFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
 */


public class EncodeFilter implements Filter {
/**
* 默认字符集
*/
public String charset = "UTF-8";


/**
* 过滤器销毁方法
*/
public void destroy() {


}
    /**
     * 处理请求字符集的核心方法
     */
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse resp = (HttpServletResponse) response;
if ("GET".equals(req.getMethod())) {
EncodeRequestWrapper wrapper = new EncodeRequestWrapper(req,
charset);
chain.doFilter(wrapper, response);
} else {
req.setCharacterEncoding(charset);// POST
resp.setContentType("text/html;charset=" + charset);
chain.doFilter(req, response);
}
}
/**
* 过滤器初始化方法
*/
public void init(FilterConfig fConfig) throws ServletException {
String initCharset = fConfig.getInitParameter("charset");
if (initCharset != null && initCharset != "") {
charset = initCharset;
}
}
}

《2》

package com.rthd.filter;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
public class EncodeRequestWrapper extends HttpServletRequestWrapper {
private HttpServletRequest request;
private String charset;
public EncodeRequestWrapper(HttpServletRequest request,String charset) {
super(request);
this.request = request;
this.charset=charset;
}
@Override
public String getParameter(String name) {
String value = request.getParameter(name);
try{
if(value!=null)
return new String(value.getBytes("ISO-8859-1"), charset);
}catch (Exception e) {
}
return super.getParameter(name);
}
}

异常拦截器,解决全局异常

《1》

package com.rthd.interceptor;


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


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


import org.apache.log4j.Logger;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;


import com.rthd.uitl.JsonUtil;


public class ExceptionInterceptor extends HandlerInterceptorAdapter{
private static final Logger log=Logger.getLogger(ExceptionInterceptor.class);
public void afterCompletion(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex)
throws Exception {
if(ex!=null){
//记录日志
Logger(request,handler,ex);
Map<String,Object> map=new HashMap<String,Object>(); 
map.put("success",false);
// map.put("msg", ex.getMessage());
JsonUtil.toJson(response, map);
}else{
super.afterCompletion(request, response, handler, ex);
}
}
private void Logger(HttpServletRequest request, Object handler, Exception ex) {
StringBuffer msg=new StringBuffer();
msg.append("异常拦截日志");
msg.append("[uri=").append(request.getRequestURI()).append("]");
Enumeration<String>  enumer= request.getParameterNames();
while (enumer.hasMoreElements()) {
String name = (String) enumer.nextElement();
String[] values = request.getParameterValues(name);
msg.append("[").append(name).append("=");
if(values != null){
int i=0;
for(String value: values){
i++;
msg.append(value);
if(i < values.length){
msg.append("|");
}
}
}
msg.append("]");
}
log.error(msg,ex);
}
}

《2》

package com.rthd.interceptor;


import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import com.rthd.annotation.LogAnnotation;
import com.rthd.uitl.ActionEnum;


/**
 * <br>
 * <b>功能:</b>拦截器:拦截delete*,update*操作。范围:删除 修改<br>
 * <b>作者:</b>admin<br>
 * <b>日期:</b> 2017.09.01 <br>
 * <b>时间:</b>16:56<br>
 * <b>更新者:</b><br>
 * <b>更新内容:</b><br>
 */
public class LogInterceptor extends HandlerInterceptorAdapter {
private static Logger logger = Logger.getLogger(LogInterceptor.class);


@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
// 处理请求的方法
HandlerMethod method = (HandlerMethod) handler;


Method m = method.getMethod();
LogAnnotation logAnno = m.getAnnotation(LogAnnotation.class);
if (logAnno.log()) {// 需要记录日志
String name = (String) request.getSession().getAttribute("user");
String msg = logAnno.msg();
Date date = new Date();
ActionEnum action = logAnno.action();
switch (action) {
case DELETE: {// 获取uid
String uid = request.getParameter("uid");
// 根据uid查询被删除的数据
System.out.println("删除:" + uid);
break;
}
case UPDATE: {// 获取 UserModel user
String nameUpdate = request.getParameter("name");
System.out.println("更新为:" + nameUpdate);
break;
}
}


System.out.println(name + "-" + msg + "-" + date.toString() + "-"
+ getIpAddress(request));
}


// System.out.println(m.getName());
return super.preHandle(request, response, handler);
}


/**
* 获取请求主机IP地址,如果通过代理进来,则透过防火墙获取真实IP地址;

* @param request
* @return
* @throws IOException
*/
public final static String getIpAddress(HttpServletRequest request)
throws IOException {
// 获取请求主机IP地址,如果通过代理进来,则透过防火墙获取真实IP地址


String ip = request.getHeader("X-Forwarded-For");
if (logger.isInfoEnabled()) {
logger.info("getIpAddress(HttpServletRequest) - X-Forwarded-For - String ip="
+ ip);
}


if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
if (ip == null || ip.length() == 0
|| "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
if (logger.isInfoEnabled()) {
logger.debug("getIpAddress(HttpServletRequest) - Proxy-Client-IP - String ip="
+ ip);
}
}
if (ip == null || ip.length() == 0
|| "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
if (logger.isInfoEnabled()) {
logger.debug("getIpAddress(HttpServletRequest) - WL-Proxy-Client-IP - String ip="
+ ip);
}
}
if (ip == null || ip.length() == 0
|| "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_CLIENT_IP");
if (logger.isInfoEnabled()) {
logger.debug("getIpAddress(HttpServletRequest) - HTTP_CLIENT_IP - String ip="
+ ip);
}
}
if (ip == null || ip.length() == 0
|| "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
if (logger.isInfoEnabled()) {
logger.debug("getIpAddress(HttpServletRequest) - HTTP_X_FORWARDED_FOR - String ip="
+ ip);
}
}
if (ip == null || ip.length() == 0
|| "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
if (logger.isInfoEnabled()) {
logger.debug("getIpAddress(HttpServletRequest) - getRemoteAddr - String ip="
+ ip);
}
}
} else if (ip.length() > 15) {
String[] ips = ip.split(",");
for (int index = 0; index < ips.length; index++) {
String strIp = (String) ips[index];
if (!("unknown".equalsIgnoreCase(strIp))) {
ip = strIp;
break;
}
}
}
return ip;
}
}

工具类

《1》

手动转json格式并返回给页面ajax

1.

package com.rthd.uitl;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
/**
 * <br>
 * <b>功能�?/b>可以把java对象、集合对象转换成json<br>
 * <b>作�?�?/b>admin<br>
 * <b>日期�?/b> 2017.09.01 <br>
 * <b>时间�?/b>16:56<br>
 * <b>更新者:</b><br>
 * <b>更新内容�?/b><br>
 */
public class JsonUtil {
protected static Logger log = Logger.getLogger(JsonUtil.class);
/**

* <br>
* <b>功能�?/b>json转对�?br>
* <b>作�?�?/b>北峰<br>
* <b>日期�?/b> Dec 14, 2016 <br>
* @param response
* @param jsonStr
* @throws Exception
*/
public static <T> T parseObject(String str, Class<T> t){
return JsonHelper.parseObject(str, t);
}
 
 
public static <T> List<T> parseArray(String str, Class<T> t) {
return JsonHelper.parseArray(str, t);
}
/**

* <br>
* <b>功能�?/b>转换json并输出到前端<br>
* <b>作�?�?/b>admin<br>
* <b>日期�?/b> Dec 14, 2016 <br>
* @param response:响应对象
* @param object:源对�?
* @throws Exception
*/
public static void toJson(HttpServletResponse response,Object object){
writer(response,JsonHelper.toJson(object));
}
private static void writer(HttpServletResponse response,String str){
try {
//设置响应类型
response.setContentType("application/json; charset=utf-8");
//设置页面不缓�?
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
PrintWriter out = response.getWriter();
log.debug("json--------------------------------------------------strat");
log.debug("向页面输出的JSON数据:"+str);
log.debug("json--------------------------------------------------end");
out.print(str);
out.flush();
out.close();
} catch (IOException e) {
log.error("输出json格式数据异常:" + e.getMessage());
}

}

2.

package com.rthd.uitl;

import java.util.List;
import org.apache.log4j.Logger;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
public class JsonHelper {
 protected static Logger log = Logger.getLogger(JsonHelper.class);
    /**
     * 把json string 转化成类对象
     *
     * @param str:json字符�?
     * @param t:目标类的类型
     * @return t:目标类对�?
     */
    public static <T> T parseObject(String str, Class<T> t) {
        try {
            if (str != null && !"".equals(str.trim())) {
                T res = JSONArray.parseObject(str.trim(), t);
                return res;
            }
        } catch (Exception e) {
        log.error("json数据转换对象出错:" + e.getMessage());
       
        }
        return null;
    }
    /**
     * 把json string 转化成类对象
     * @param str
     * @param t
     * @return
     */
    public static <T> List<T> parseArray(String str, Class<T> t) {
        try {
            if (str != null && !"".equals(str.trim())) {
                List<T> res = JSONArray.parseArray(str.trim(), t);
                log.info("");
                return res;
            }
        } catch (Exception e) {
        log.error("json数据转换List对象出错:" + e.getMessage());
        }
        return null;
    }
    /**
     * 把类对象转化成json string
     *
     * @param t
     * @return
     */
    public static <T> String toJson(T t) {
        try {
            return JSONObject.toJSONString(t);
        } catch (Exception e) {
        log.error("对象数据转换json出错:" + e.getMessage());
        }
        return "";
    }
}

自定义注解

package com.rthd.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import com.rthd.uitl.ActionEnum;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface LogAnnotation {
/**
* false:不记录日志 true:记录日志

* @return
*/
public boolean log() default true;

public String msg() default "";

public ActionEnum action();
}

log4j日志记录源码:文件命名log4j.properties

#log4j's properties
log4j.rootCategory=debug,stdout,file
#log4j.rootCategory=debug,stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=[log4j] %d %p [%t] %C.%M(%L) | %m%n
##log file
log4j.appender.file=org.apache.log4j.DailyRollingFileAppender
log4j.appender.file.File=${catalina.home}\\logs\\crm.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d-[TS] %p %t %c - %m%n

# SqlMap logging configuration...
log4j.logger.com.ibatis=debug
log4j.logger.com.ibatis.db=debug
log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=debug
log4j.logger.com.ibatis.sqlmap.engine.cache.CacheModel=debug
log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientImpl=debug
log4j.logger.com.ibatis.sqlmap.engine.builder.xml.SqlMapParser=debug
log4j.logger.com.ibatis.common.util.StopWatch=debug

log4j.logger.java.sql.Connection=debug
log4j.logger.java.sql.Statement=error
log4j.logger.java.sql.PreparedStatement=debug
log4j.logger.java.sql.ResultSet=error

配置文件:

web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>1009premium</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  <!-- spring -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:application-*.xml</param-value>
</context-param>
<!-- 加载spring配置文件的监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 处理请求乱码的过滤器 -->
<filter>
<filter-name>EncodeFilter</filter-name>
<filter-class>com.rthd.filter.EncodeFilter</filter-class>
<init-param>
<param-name>charset</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>EncodeFilter</filter-name>
<url-pattern>*.do</url-pattern>
</filter-mapping>
<!-- spring mvc -->
<servlet>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>

mvc配置文件:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/aop 
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/tx 
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
<!-- 启动注解扫描器 -->
<context:component-scan base-package="com.rthd.controller"></context:component-scan>
<!-- 不拦截的资源 -->
<mvc:resources location="/jslib/" mapping="/jslib/**"/>
<!-- 全局异常拦截器 -->
<mvc:interceptors>
<bean class="com.rthd.interceptor.ExceptionInterceptor"></bean>
<mvc:interceptor>
<mvc:mapping path="/delete*" />
<mvc:mapping path="/update*" />
<bean class="com.rthd.interceptor.LogInterceptor"></bean>
</mvc:interceptor>
</mvc:interceptors>
<mvc:annotation-driven></mvc:annotation-driven>

<!-- 视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>

spring底层及数据库配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/aop 
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/tx 
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
<!-- 配置数据源 -->
<bean id="dataSource" destroy-method="close"
class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url"
value="jdbc:mysql://localhost:3304/school?useUnicode=true&amp;characterEncoding=utf-8" />
<property name="username" value="root" />
<property name="password" value="123456" />
<!-- 配置初始化大小、最小、最大 -->
<property name="initialSize" value="1" />
<property name="minIdle" value="1" />
<property name="maxActive" value="10" />
<!-- 配置获取连接等待超时的时间 -->
<property name="maxWait" value="10000" />
<!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
<property name="timeBetweenEvictionRunsMillis" value="60000" />
<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
<property name="minEvictableIdleTimeMillis" value="300000" />
<property name="testWhileIdle" value="true" />
<!-- 这里建议配置为TRUE,防止取到的连接不可用 -->
<property name="testOnBorrow" value="true" />
<property name="testOnReturn" value="false" />
<!-- 打开PSCache,并且指定每个连接上PSCache的大小 -->
<property name="poolPreparedStatements" value="true" />
<property name="maxPoolPreparedStatementPerConnectionSize" value="20" />
<!-- 这里配置提交方式,默认就是TRUE,可以不用配置 -->
<property name="defaultAutoCommit" value="true" />
</bean>
<!-- sqlsessionFactory工厂 -->
<bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!-- 加载mybatis配置文件 -->
<property name="configLocation" value="classpath:mybatis-config.xml" />
<!-- 加载mybatis映射文件-->
<property name="mapperLocations" value="classpath:com/rthd/dao/PremiumDao.xml"/> 

<!-- 配置分页插件 -->
<property name="plugins">
<array>
<bean class="com.github.pagehelper.PageHelper">
<property name="properties">
<!-- config params as the following -->
<value>
dialect=Mysql
</value>
</property>
</bean>
</array>
</property>
</bean>
<!-- ******************************配置事务开始************************************* -->
<!-- 事务管理器 -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- 启用事务注解 -->
<tx:annotation-driven transaction-manager="transactionManager"/>
<!-- ********************************配置事务结束************************************* -->
<!-- 扫描mybatis接口(dao层) -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.rthd.dao"/>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactoryBean"  />
</bean>
</beans>
  上下文的配置文件:文件名mybatis_config

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- 实体类别名 -->
<typeAliases>
<!-- 部门实体类 -->
<typeAlias type="com.rthd.entity.Premium" alias="premium" />
</typeAliases>
<!-- 加载映射文件 
<mappers>
<mapper resource="classpath:com/rthd/dao/PremiumDao.xml" />
</mappers>
-->
</configuration>

猜你喜欢

转载自blog.csdn.net/rocrunwang/article/details/78188934
今日推荐