ssm框架整合(spring+spring mvc+mybatis)
开发步骤:
1.新建一个web工程
2.导入ssm框架的jar包
- 配置三大框架的的配置文件
web.xml 配置文件
index.jsp
org.springframework.web.context.ContextLoaderListener
contextConfigLocation
classpath:applicationContext.xml
mvc
org.springframework.web.servlet.DispatcherServlet
1
mvc
*.do
encodingFilter
org.springframework.web.filter.CharacterEncodingFilter
encoding
utf-8
encodingFilter
/*
applacitonContext.xml(置于src根目录下) (这里配置的是spring的配置文件)
${jdbc.driverClassName}
${jdbc.url}
${jdbc.username}
${jdbc.password}
com.hw.mapper
开发项目时,上面的配置文件一般都不用改变
需要改变的有1、
根据情况作出改变2、
对应的包根据情况改变
mvc-servlet.xml(置于WEB-INF文件夹下) (这里配置的spring mvc的配置文件)
因为我做的项目涉及到上传与下载所以配置的时候定义了文件上传解析器
上面的配置文件一般情况不改变,需要加功能可以往里面添加,比如上传下载需要用到文件上传解析器
4 与开发接口的关联的映射文件
userDaoMapper.xml
insert into tab_user values(null,#{userName},#{userPass})
注意返回类型是boolean,传入参数是map,在mybatis中select 涉及到传参的都是用map
controller层
UserAction
package com.hw.controller;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.hw.entity.User;
import com.hw.service.UserService;
import com.hw.utils.MD5Utils;
@Controller
@RequestMapping("user")
public class UserAction {
@Autowired
private UserService db;
@RequestMapping("add")
public String add(User user) throws Exception {
String ss=MD5Utils.MD5Src(user.getUserPass());//进行md5加密
user.setUserPass(ss);//加密后存进行去
db.add(user);
return "redirect:/index.jsp";
}
@RequestMapping("login")
public String login(User user) throws Exception {
//把密码通过md5加密后和数据库的表中的对应字段进行比较
Map map=new HashMap();
map.put("userName", user.getUserName());
map.put("userPass", MD5Utils.MD5Src(user.getUserPass()));
if(db.login(map)){
return "redirect:/per/listPerson.do";//重定向
}else{
return "redirect:/index.jsp";
}
}
}
上面要注意创建map集合存取对应的值
deptDaoMapper.xml
insert into tab_dept values(null,#{dname})
上面主要是注意1对多的关系,使用collection
personDaoMapper.xml
insert into tab_per
values(null,#{pname},#{psex},#{skilled},#{degree},#{jobtime},#{resume},
#{filepath},#{dept.did})
update tab_per set pname=#{pname},psex=#{psex},skilled=#{skilled},
degree=#{degree},jobtime=#{jobtime},resume=#{resume},
filepath=#{filepath},did=#{dept.did} where pid=#{pid}
delete from tab_per where pid=#{pid}
delete from tab_per where pid in
#{pid}
上面主要是注意多对一的关系,使用association 类与类之间的关联
controller层
PersonAction
package com.hw.controller;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.hw.entity.Dept;
import com.hw.entity.Person;
import com.hw.service.DeptService;
import com.hw.service.PersonService;
import com.hw.service.impl.DeptServiceImpl;
import com.hw.service.impl.PersonServiceImpl;
import com.hw.utils.ExportExcel;
import com.hw.utils.FileDownLoad;
import com.hw.utils.PageUtils;
@Controller
@RequestMapping("per")
public class PersonAction {
@Autowired
private PersonService ps;
@Autowired
private DeptService ds;
private List list=new ArrayList();//有set get方法
private File myfile;//有set get方法
private String myfileFileName;//有set get方法
private List perlist=new ArrayList();
private List source=new ArrayList();
@RequestMapping("dept")
@ResponseBody //生成json格式
public List dept(){//下载
List list=ds.list();
return list;
}
@RequestMapping("download") //下载,没有返回值
public void download(HttpServletRequest request,HttpServletResponse response,Person per) throws Exception{//下载
FileDownLoad.download("\\upload\\"+per.getFilepath(), request, response);
}
@RequestMapping("toadd")
public String toAdd() throws Exception {// 到添加
list=ds.list();//查询出所有部门表
return "add";
}
@RequestMapping("toupdate")
public String toUpdate(HttpServletRequest request,Person per) throws Exception {// 到修改
per=ps.getPerson(per.getPid());//获取单个对象
request.setAttribute("per",per);//存起来
String []aa=per.getSkilled().split(",");
for(int i=0;i0){
//解决文件同名问题
fileName = UUID.randomUUID().toString().replace("-", "")+fileName.substring(fileName.lastIndexOf("."));
File targetFile = new File(path, fileName);
if (!targetFile.exists()) {
targetFile.mkdirs();
}
// 保存
try {
file.transferTo(targetFile);
} catch (Exception e) {
e.printStackTrace();
}
request.setAttribute("fileUrl", request.getContextPath() + "/upload/"
+ fileName);
user.setFilepath(fileName);
}else{
user.setFilepath("");
}
/*如果不涉及上传则表单中不能设置enctype="multipart/form-data",
* 本方法中只需保留Person pe和以下2行代码即可
*/
ps.add(user);
return "redirect:listPerson.do";
}
@RequestMapping("update")
public String update(MultipartFile file,
HttpServletRequest request,Person per) {
String path = request.getSession().getServletContext()
.getRealPath("upload");
String fileName = file.getOriginalFilename();
if(fileName.length()>0){
//解决文件同名问题
fileName = UUID.randomUUID().toString().replace("-", "")+fileName.substring(fileName.lastIndexOf("."));
File targetFile = new File(path, fileName);
if (!targetFile.exists()) {
targetFile.mkdirs();
}
// 保存
try {
file.transferTo(targetFile);
} catch (Exception e) {
e.printStackTrace();
}
request.setAttribute("fileUrl", request.getContextPath() + "/upload/"
+ fileName);
per.setFilepath(fileName);
}else{
per.setFilepath(per.getFilepath());
System.out.println(per.getFilepath());
}
/*如果不涉及上传则表单中不能设置enctype="multipart/form-data",
*/
ps.updatePerson(per);
return "redirect:listPerson.do";
}
@RequestMapping("del")
public String del(Person per) throws Exception {// 删除
ps.del(per.getPid());//删除
return "redirect:listPerson.do";
}
@RequestMapping("delall")
public String delAll(HttpServletRequest request) throws Exception {// 批量删除
String id=request.getParameter("id");//取过来批量删除的id
System.out.println("ok批量删除:"+id);
String[] split = id.split(",");
ps.delSelectAll(split);//删除
return "redirect:listPerson.do";
}
@RequestMapping("listPerson")
public String listPerson(HttpServletRequest request) throws Exception {// 列表显示
String page = request.getParameter("currentPage") == null ? "1"
: request.getParameter("currentPage");// 如果是空则为1,或则取页数
int currentPage = Integer.parseInt(page);// 当前页
int pageSize = 3;// 当前页记录大小
int dataCount = ps.getCount();// 表记录多少
Map map=new HashMap();
map.put("pageIndex", (currentPage-1)*pageSize);
map.put("pageSize", pageSize);
source = ps.list(map);
request.setAttribute("list", source);
PageUtils.page(request, currentPage, pageSize, source, dataCount);
list=ds.list();//查询出所有部门表
System.out.println("perlistperson");
return "list";
}
@RequestMapping("listlikePerson")
public String listlikePerson(HttpServletRequest request){//模糊查询有分页
String page = request.getParameter("currentPage") == null ? "1"
: request.getParameter("currentPage");// 如果是空则为1,或则取页数
int currentPage = Integer.parseInt(page);// 当前页
String querypdept = request.getParameter("querypdept");
String querypname = request.getParameter("querypname");
System.out.println(querypdept+" ,"+querypname);
int pageSize = 3;// 当前页记录大小
Map map=new HashMap();
map.put("pageIndex", (currentPage-1)*pageSize);
map.put("pageSize", pageSize);
map.put("pname", querypname);
map.put("did", Integer.parseInt(querypdept));
int dataCount = ps.getLikeCount(map);// 表记录多少
source = ps.listLike(map);
// System.out.println("source:"+source.size()+","+dataCount);
request.setAttribute("list", source);
PageUtils.page(request, currentPage, pageSize, source, dataCount);
list=ds.list();//查询出所有部门表
return "list";
}
@RequestMapping("exportExcel") //导出excel
public void exportExcel(HttpServletResponse response) throws Exception {
// 初始化HttpServletResponse对象
// 定义表的标题
String title = "员工列表一览";
//定义表的列名
String[] rowsName = new String[] { "员工编号", "姓名", "性别", "特长", "学历",
"入职时间", "简历", "照片", "部门" };
//定义表的内容
List
上面主要注意的是图片路径的设置问题 add添加时加一个判断,如果路径为空时
设置一个空的字符串防止报错
if(fileName.length()>0){ }else{
user.setFilepath("");
}
同理,update修改也需要加一个判断,如果不修改路径则为原路径没修改则
改变路径
if(fileName.length()>0){ }else{
per.setFilepath(per.getFilepath());
}
另外,注意批量删除传入的参数是数组,按照上面做法即可
update.jsp修改页面部门回显
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
My JSP 's1.jsp' starting page
用户修改
上面主要加了
var aa = "${per.dept.did}";//将需要修改的部门id赋值给aa
if (msg[i].did == aa) {
//判断部门id是否相等,相等则默认选择对应部门
$("#querypdept option[value='" + msg[i].did + "']").attr('selected', 'selected');
}
注释也很清楚了,不多说
还有一个方法是利用c标签也可以实现部门回显
部门:
相关源码:
链接:http://pan.baidu.com/s/1hsmLf72 密码:2ujv