注意:框架原因使用eclipse时需要先把jre改为jdk
使用一个框架首先要clean和install在强制更新
修改总框架的数据库用户和密码
然后更改mybatis.xml文件里的扫描dao的信息再改servlet.xml
里边的<context:component-scan base-package=””>
1.当网页请求不到地址时两种情况①页面地址写错②没有扫描到包
2.用注解是自动扫描扫描到的
3.分页的步骤:①在dao中继承GenericDao<T, Serializable>Serializable序列化ID意思在bean里边写 T是model给谁分页就写谁的model
②在bean中继承序列化 通过序列化ID知dao中的序列化为*
③写sql语句
<!--搜素查询 Servant 当前页结果列表-->
<select
id="searchPage" parameterType="com.eigpay.framework.student.webapp.searcher.StudentSearcherPage"
resultMap="StudentMap">
select *from Student
<where>
flag = 0
<if test="stuName != null" >
and name like CONCAT('%',#{stuName},'%')
</if>
</where>
</select>
注意: 如果mapper中代码写错的话会导致页面不能登录
④在searcher包里写一个*SearcherPage并继承Page<要分页的Model>并将parameterType的内容改为*SearcherPage地址 id不变
⑤在Service中写入Page<Student> studentSearcherPage(StudentSearcherPage studentSearcherPage);
在Service下的impl中写
@Override
public Page<Student> studentSearcherPage(StudentSearcherPage studentSearcherPage) {
// TODO Auto-generated method stub
studentSearcherPage.setPageSize(9);//表示每页存入几条
//返回的结果集
studentSearcherPage.setResult(stuDao.searchPage(studentSearcherPage));
return studentSearcherPage;
}
⑥在controller中写入代码
@RequestMapping("list")
public ModelAndView list(@ModelAttribute("studentSearcherPage")StudentSearcherPage studentSearcherPage){
return new ModelAndView("student/selectAll_list")
.addObject("studentSearcherPage", studentSearcherPage)//为了将页码、页数查询条件等返回给前台页面
.addObject("pageObj", stuService.studentSearcherPage(studentSearcherPage));//将查询的结果集返回给前台页面
}
⑦修改前台页面 items="${pageObj.result}" list存到了result里边
4.框架网页建菜单①新增资源②角色管理(给角色分配菜单)③配子菜单(路径:先写父级路径 URL:后台程序登录网页地址如(/StudentCol/list))④角色管理(给角色分配菜单)
5.实现修改新增一个jsp步骤:
①修改jsp页面
②后台
注意:由于前台页面用的是form:form表单action="${ctx}/*"所以后台不能随便跳页面
@RequestMapping("manage")
public ModelAndView manage(@ModelAttribute("Student")Student stu){
return new ModelAndView("student/student_manage")
.addObject("student", stu);
}
6.下拉框实现(死的下拉框):在需要下拉框的jsp写如
(<select name="sex" class="form-control" id="sex" validata-options="validType:'Require',msg:'不能为空'">
<option value="">----请选择----</option>
<option value="男">男</option>
<option value="女">女</option>
</select>)
7.下拉框实现(活的下拉框):
①新建一个表
②在mapper中写查询表的sql
③写代码
④前台
<label for="roleID" class="col-sm-2 control-label">院 系</label>
<div class="col-sm-10">
<select name="dept" value="${student.dept}" class="dept" id="dept" validata-options="validType:'Require',msg:'不能为空'">
<option value="">---请选择---</option>
<c:forEach items="${dept}" var="dept">
<option value="${dept.deptName}" <c:if test="${dept.deptName == student.dept}"> selected </c:if> >${dept.deptName}</option>
</c:forEach>
</select>
</div>
出现的错误:
一、Invalid bound statement (not found)错误
原因:1.<mapper namespace="me.tspace.pm.dao.UserDao">
mapper的namespace写的不对!!!注意系修改。
2.UserDao的方法在UserDao.xml中没有,然后执行UserDao的方法会报此(查询的名称与xml中的没有对上)
3. UserDao的方法返回值是List<User>,而select元素没有正确配置ResultMap,或者只配置ResultType!
4. 如果你确认没有以上问题,请任意修改下对应的xml文件,比如删除一个空行,保存.问题解决…
文件导出
一、 controller继承Basecontroller和admin的pom文件写
<dependency>
<groupId>eigpay-sdk</groupId>
<artifactId>excel</artifactId>
<version>1.4</version>
</dependency>
二、 Basecontroller中写
/**
* excel导出
*
* @param fileName 文件名称
* @param sheetName sheet页名称
* @param excelPojos excel数据
* @param request
* @param response
* @throws Exception
*/
public void downLoadExcel(String fileName, String sheetName, List<?> excelPojos,HttpServletRequest request,HttpServletResponse response) throws Exception {
ArrayList<List<?>> datas = new ArrayList<>();
datas.add(excelPojos);
Component component = ExcelComponentsFactory.produce();
ExcelExportSetting excelExportSetting = new ExcelExportSetting();
excelExportSetting.setData(datas);
excelExportSetting.setExcelFileType(ExcelFileType.XLSX);
excelExportSetting.setSheetName(new String[] { sheetName });
File path = new File("." + File.separator + "file");
if (!path.exists())
path.mkdirs();
String filePathAndName = "." + File.separator + "file" + File.separator + fileName;
File file = new File(filePathAndName);
if (file.exists())
file.delete();
excelExportSetting.setExcelFilePath(filePathAndName);
component.exportList2Excel(excelExportSetting);
response.setContentType("text/html;charset=utf-8");
request.setCharacterEncoding("UTF-8");
java.io.BufferedInputStream bis = null;
java.io.BufferedOutputStream bos = null;
try {
long fileLength = file.length();
response.setContentType("application/x-msdownload;");
response.setHeader("Content-disposition",
"attachment; filename=" + new String(fileName.getBytes("utf-8"), "ISO8859-1"));
response.setHeader("Content-Length", String.valueOf(fileLength));
bis = new BufferedInputStream(new FileInputStream(filePathAndName));
bos = new BufferedOutputStream(response.getOutputStream());
byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length)))
bos.write(buff, 0, bytesRead);
} catch (Exception e) {
throw new Exception(e);
} finally {
if (bis != null) {
bis.close();
bis = null;
}
if (bos != null) {
bos.flush();
bos.close();
bos = null;
}
}
}
包含日期的导出
三、写一个关于导出所需要的model类
四、 controller中写
/**
* 导出项目信息表
* @throws Exception
* @return /projectInfoManage/projectInfo/exportprojectBasicInfo
*/
@RequestMapping(value = "/exportprojectBasicInfo", method = RequestMethod.POST)
private void exportprojectBasicInfo(ProjectStaticManagePageSearcher seacher, HttpServletRequest request,HttpServletResponse response) throws Exception {
//1.查项目信息数据列表
List<ProjectInfo> ProjectInfoList = projectStaticInfoDao.getExcelData(seacher);
//2.data pojos to excel pojos
List<Object> ProjectInfo = projectStaticManage.downloadProjectInfo(ProjectInfoList);
//3.生成文件名
StringBuffer stringBuffer = new StringBuffer("项目信息-");
stringBuffer.append(new SimpleDateFormat("yyyyMMdd").format(new Date()));
stringBuffer.append(".xlsx");
String fileName = stringBuffer.toString();
//4.调方法
super.downLoadExcel(fileName, "项目信息", ProjectInfo, request, response);
}
五、ManageImpl中写
@Override
public void downloadExcel(HttpServletRequest request, HttpServletResponse response,ProjectStaticManagePageSearcher seacher) {
List<ProjectInfo> data = projectStaticInfoDao.getExcelData(seacher);
String[] title = { "项目编号", "项目名称", "开工日期", "状态"};
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFCellStyle cellStyle = workbook.createCellStyle();
cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
String filename = "项目信息表.xls";
response.setContentType("application/vnd.ms-excel");
try {
response.setHeader( "Content-Disposition", "attachment;filename=" + new String( filename.getBytes("GB2312"), "ISO-8859-1" ) );
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
//response.setHeader("Content-disposition", "attachment;filename=" + filename);
HSSFSheet sheet = workbook.createSheet(filename);
HSSFRow row = sheet.createRow(0);
HSSFCell cell = null;
int i = 0;
for (; i < title.length; i++) {
cell = row.createCell(i);
cell.setCellValue(title[i]);
}
i = 1;
for (ProjectInfo item : data)
{
row = sheet.createRow(i);
cell = row.createCell(0);
cell.setCellValue(item.getProjectCode());
cell = row.createCell(1);
cell.setCellValue(item.getProjectName());
cell = row.createCell(2);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd ");
if(item.getStartDate() !=null)
{
cell.setCellValue(sdf.format(item.getStartDate()));
} else {
cell.setCellValue(" ");
}
cell = row.createCell(3);
cell.setCellValue(item.getProjectStatus());
i++;
}
sheet.setColumnWidth(0, (short) 250 * 30);
sheet.setColumnWidth(1, (short) 250 * 40);
sheet.setColumnWidth(2, (short) 250 * 15);
try {
ServletOutputStream stream = response.getOutputStream();
workbook.write(stream);
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
六、分别在dao,mapper,service中写上相应代码mapper中用分页查询的就可以
七、在需要导出的jsp页面写
$("#export").click(
function(){
$("#pageForm").attr('action',"${ctx}/Controller/exportprojectBasicInfo");
$("#pageForm").submit();
$("#pageForm").attr('action',"${ctx}/Controller/list");} );
导出按钮那里用id=” export”触发
弹框:
1按钮
<a data-toggle="modal" data-target="#invoice_ajaxload" href="${ctx}/projectBidInfo/jumpMoreAction/ajaxLoad?bidCode=${bidInfo.bidCode}">更多操作</a>
2弹框代码(放在<form:from>之后)
<div class="modal fade" id="invoice_ajaxload">
<div class="modal-dialog">
<div class="modal-content"></div>
</div>
</div>
3js代码
$(function() {
$("#invoice_ajaxload").on("hidden.bs.modal", function(e) {
$(this).removeData();
})
});
3/**
* 跳转到更多操作显示页面
* @return
*/
@RequestMapping("jumpMoreAction/ajaxLoad")
public ModelAndView jumpMoreAction(HttpServletRequest request, String bidCode){
System.out.println(bidCode);
return new ModelAndView("projectInfoManage/moreAction_manage")
.addObject("bidCode", bidCode);}
正则表达式校验姓名
/* 姓名的校验 */
function checkcontact()
{
var checkContact= document.getElementById("contact");
var contactValue=$(".contact").val();
$(".contact").each(function(){
if($(this).val() != "") {
if (!iscontact(contactValue))
{
alert("请输入汉字或者字母!");
document.getElementById("contact").value = "";
throw SyntaxError();
}
}
});
return true;
}
function iscontact(str){
var reg = /^[a-zA-Z\u4e00-\u9fa5\s]{1,20}$/;
return reg.test(str);
}
用onchange触发
Ajax校验唯一性
<!-- 客户名称唯一校验 -->
一、前台
<script type="text/javascript">
$("#custName").change(function check() {
var custName = $("#custName").val();
var name = '${name}';
if (name == custName) {
$("#custName").val(name);
} else {
$.ajax({
type : 'post',
url : '${ctx}/SaleCustomorController/ajax/checkcustName',
dataType : 'json',
data : {
custName : custName
},
success : function(data) {
if (data.info == "repeat") {
alert("已存在客户名称!请重新填写!");
$("#custName").val("");
$("#custName").select();
}
}
})
}
});
</script>
custName是id里的
二、后台(走一个查询需校验的内容方法)
/**
* 查重 客户名称
*/
@RequestMapping(value="ajax/checkcustName",method = { RequestMethod.GET, RequestMethod.POST })
public void checkcustName(HttpServletResponse response,String custName){
Map<String, Object> map = new HashMap<String, Object>();
List<String> name = scManager.searchcustName();
String msg = "unrepeat";
for (int i = 0; i < name.size(); i++) {
if(custName!=null){
//如果存在,直接跳出循环,不再执行,减少时间
if(custName.contentEquals(name.get(i))){
msg = "repeat";
break;}}}ResponseUtil.renderJsonResult(response, new JsonResult(true, msg));}
sql中修改一个表数据另一个表数据同步更新
update 表一,表二 set 同步的数据(如sale_contact_costomor.contact_company = sale_customor.cust_name,)
where 两个表关联的数据
模糊查询
Sql语句加上<if test="custName != null" >
and cust_name like CONCAT('%',#{custName},'%')
</if>
查询角色
//查询登录人的id
id = getCurrentSessionObject().getUser().getId();
List<ServantRole> list = srDao.listRoleByUserId(id);//这是通过id查出来的list
//定义变量
String isHaveRole = "F";
for (ServantRole servantRole : list) {
if("销售leader".equals(servantRole.getDescription())
|| "销售Owner".equals(servantRole.getDescription())){
isHaveRole = "T";
break;
}
}
前台传后台中文出现乱码问题
中文 = new String(request.getParameter("中文").getBytes("ISO-8859-1"),
"utf-8");
可下拉可输入的输入框及内容拼接
<form:input cssClass="form-control" placeholder="请下拉选择或按照下拉格式输入" list="url_list" path="projectName" id="projectName" maxlength="60"/>
<datalist id="url_list">
<c:forEach items="${project}" var="list">
<option value="${list.projectCode}:${list.projectName}"></option>
</c:forEach>
</datalist>
再输入框中填入日历
一、 哪个jsp需要写入日历就在这个jsp引入的model中写入并填充get,set方法
private String startQueryDate;
private String endQueryDate;
代表输入框中的起止时间,在jsp页面中<from:from>下面填入
<form:hidden path="startQueryDate" id="startQueryDate"/>
<form:hidden path="endQueryDate" id="endQueryDate"/>
代表再输入狂显示出时间,接着再写
<div class="col-lg-3 col-md-3 col-sm-3 col-xs-3">
<div class="form-group ">
<div class="col-lg-12 col-sm-12">
<%-- <input class="form-control" value="${tQuitRecordPageSearcher.effectDate }" placeholder="离职日期"
onfocus="WdatePicker({isShowWeek:true})" name="effectDate"> --%>
<!-- 日历部分 -->
<div id="reportrange"
style="font-size: 12px; background: #fff; cursor: pointer; padding: 3px 8px;
border: 1px solid #e7e7eb;">
<i class="glyphicon glyphicon-calendar fa fa-calendar"> </i> <span>
</span> <b class="caret"> </b>
</div>
<!-- 日历部分 结束 -->
</div>
</div>
</div>
最后在js里面写,日历完成
$(function () {
var startQueryDate = $("#startQueryDate").val();
if (startQueryDate != "") {
daterangepicker_optionSet.startDate=startQueryDate;
daterangepicker_optionSet.endDate=$("#endQueryDate").val();
}
var cb = function(start, end, label) {
$('#reportrange span').html(start.format('YYYY-MM-DD') + ' - '+ end.format('YYYY-MM-DD'));
}
$('#reportrange span').html(daterangepicker_optionSet.startDate + ' - '+daterangepicker_optionSet.endDate);
$('#reportrange').daterangepicker(daterangepicker_optionSet, cb);
$('#reportrange').on('apply.daterangepicker',function(ev, picker) {
// 在这里进行业务查询操作
$("#startQueryDate").val(picker.startDate.format('YYYY-MM-DD'));
$("#endQueryDate").val(picker.endDate.format('YYYY-MM-DD'));
$("#pageNo").val(1);
$("#pageForm").submit();
});
$("#query").click(function () {
$("#pageNo").val(1);
$("#pageForm").submit();
});
$("#reset").click(function () {
$("input").val('');
$("select").val("-1");
})
});
在输入框显示时间(2)
在jsp页面写入
<div class="form-group">
<label class="col-sm-2 control-label" >提出日期</label>
<div class="col-sm-10">
<input class="form-control" name="proposedDate" id="proposedDate" value="<fmt:formatDate value='${tAppointManagerRecord.proposedDate}'
pattern="yyyy-MM-dd"/>" onfocus="WdatePicker({isShowWeek:true})" />
</div>
</div>
完成。