框架第十五天

Spring + SpringMVC + Hibernate3框架整合
开发步骤
首先导入jar包(我做的项目中涉及文件和图片的导入与导出,所以加入了poi的jar包,poi的版本是3.1的)


框架第十五天_第1张图片
poi的jar包.png

用到的jar包过多不方便截图(其实有些jar包是没用到的),可到我的工程里面看
2 配置三大框架的的配置文件
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
    /*
  


    openSessionInView
    
    org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
               
        
        sessionFactoryBeanName
        sessionFactory
        
    
    
        openSessionInView
        /*
    


applacitonContext.xml(置于src根目录下) (这里配置的是spring的配置文件)



    
    
    
        
        
        
        

        
        
        
        
        
        
        
        
    

    
    
        
        
        
            
                org.hibernate.dialect.MySQLDialect
                update
                true
                true
            
        
        
            
                com/hw/entity/Dept.hbm.xml
                com/hw/entity/Person.hbm.xml
                com/hw/entity/User.hbm.xml
            
        

    

    

    
        
    

    
    

    
        
        
    

    
    
        
        
            
            
            
            
            
        
    
    

mvc-servlet.xml(置于WEB-INF文件夹下) (这里配置的spring mvc的配置文件)
因为我做的项目涉及到上传与下载所以配置的时候定义了文件上传解析器



    
    
    




 
 
 
 


    
        
       
        
        
    

3 Controller(控制器)
UserAction(用户登录与注册)

package com.hw.controller;

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.service.impl.UserServiceImpl;
import com.hw.utils.MD5Utils;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
@Controller
@RequestMapping("user")
public class UserAction {
   private UserService db=new UserServiceImpl();
   @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加密后和数据库的表中的对应字段进行比较
        if(db.login(user.getUserName(), MD5Utils.MD5Src(user.getUserPass()))){
            return "redirect:/per/listPerson.do";//重定向
        }else{
            return "redirect:/index.jsp";
        }
    }
}

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.List;
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.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  {
    private Person per = new Person();//有set get方法
    private PersonService ps = new PersonServiceImpl();
    private DeptService ds=new DeptServiceImpl();
    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());//获取单个对象
        System.out.println(per.getFilepath());
        request.setAttribute("per",per);//存起来
        
        String []aa=per.getSkilled().split(",");
        for(int i=0;i dataList = new ArrayList();
        Object[] objs = null;
        List listPerson = ps.listAll();
        for (int i = 0; i < listPerson.size(); i++) {
            Person per = listPerson.get(i);
            objs = new Object[rowsName.length];
            objs[0] = per.getPid();
            objs[1] = per.getPname();
            objs[2] = per.getPsex();
            objs[3] = per.getSkilled();
            objs[4] = per.getDegree();
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            String date = df.format(per.getJobtime());
            objs[5] = date;
            objs[6] = per.getResume();
            objs[7] = per.getFilepath();
            objs[8] = per.getDept().getDname();
            dataList.add(objs);
        }
        
        // 创建ExportExcel对象
        ExportExcel ex = new ExportExcel(title, rowsName, dataList);

        // 输出Excel文件
        try {
            OutputStream output = response.getOutputStream();
            response.reset();
            response.setHeader("Content-disposition",
                    "attachment; filename=personList.xls");
            response.setContentType("application/msexcel");
            ex.export(output);
            output.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return "tolist";// 返回列表显示
    }
    @RequestMapping("importExcel") 
    public String importExcel(@RequestParam(value = "file", required = false) MultipartFile file,
            HttpServletRequest request) throws Exception {

        // 初始化HttpServletRequest对象
                String path = request.getSession().getServletContext()
                        .getRealPath("upload");
                String fileName = file.getOriginalFilename();
                //解决文件同名问题
                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();
                }
                // 获取服务器中文件的路径
                //把上传文件保存在当前路径的 upload 文件夹中(服务器)
                String paths =request.getSession().getServletContext().getRealPath("")
                        + "/upload/" + fileName;

                // 上传文件到服务器中
//              filename = FileUpload2.upload(filename, myfile);

                Person per = new Person();// 新建一个user对象
                Dept dept = new Dept();// 新建一个dept对象

                SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");


                try {
                    InputStream is = new FileInputStream(paths);
                    HSSFWorkbook hssfWorkbook = new HSSFWorkbook(is);

                    // 循环工作表Sheet
                    for (int numSheet = 0; numSheet < hssfWorkbook.getNumberOfSheets(); numSheet++) {
                        HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(numSheet);
                        if (hssfSheet == null) {
                            continue;
                        }

                        // 循环行Row
                        for (int rowNum = 3; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
                            HSSFRow hssfRow = hssfSheet.getRow(rowNum);
                            if (hssfRow == null) {
                                continue;
                            }

                            // 循环列Cell
                            // "姓名","密码","性别","爱好","简介","部门did"};
                            per.setPname(getValue(hssfRow.getCell(1)));
                            per.setPsex(getValue(hssfRow.getCell(2)));
                            per.setSkilled(getValue(hssfRow.getCell(3)));
                            per.setDegree(getValue(hssfRow.getCell(4)));
                            per.setJobtime(sd.parse(getValue(hssfRow.getCell(5))));
                            per.setResume(getValue(hssfRow.getCell(6)));
                            per.setFilepath(getValue(hssfRow.getCell(7)));

                            // 这里很重要,通过部门列表然后与excel中的部门字段进行对比,匹配后获取对应的did
                            String dname = getValue(hssfRow.getCell(8));// 获取excel中的部门字段
                            list = ds.list();// 得到数据库中的部门列表
                            for (Dept dd : list) {// 增强for循环
                                if (dd.getDname().equals(dname)) {// 如果两者匹配
                                    dept.setDid(dd.getDid());// 则得到对应的did,并设置dept对象的did
                                    per.setDept(dept);// 再把dept对象设置到user对象中
                                }
                            }

                            ps.add(per);// 写入到数据中
                        }
                    }
                } catch (Exception e) {
                    // TODO: handle exception
                    e.printStackTrace();
                }

                return "redirect:listPerson.do";// 返回列表显示
    }

    /**
     * 得到Excel表中的值
     * 
     * @param hssfCell
     *            Excel中的每一个格子
     * @return Excel中每一个格子中的值
     */
    @SuppressWarnings("static-access")
    private static String getValue(HSSFCell hssfCell) {
        if (hssfCell.getCellType() == hssfCell.CELL_TYPE_BOOLEAN) {
            // 返回布尔类型的值
            return String.valueOf(hssfCell.getBooleanCellValue());
        } else if (hssfCell.getCellType() == hssfCell.CELL_TYPE_NUMERIC) {
            // 返回数值类型的值
            return String.valueOf(hssfCell.getNumericCellValue());
        } else {
            // 返回字符串类型的值
            return String.valueOf(hssfCell.getStringCellValue());
        }

    }
    public List getList() {
        return list;
    }

    public void setList(List list) {
        this.list = list;
    }

    public Person getPer() {
        return per;
    }

    public void setPer(Person per) {
        this.per = per;
    }

    public File getMyfile() {
        return myfile;
    }

    public void setMyfile(File myfile) {
        this.myfile = myfile;
    }

    public String getMyfileFileName() {
        return myfileFileName;
    }

    public void setMyfileFileName(String myfileFileName) {
        this.myfileFileName = myfileFileName;
    }

    public List getPerlist() {
        return perlist;
    }

    public void setPerlist(List perlist) {
        this.perlist = perlist;
    }

    public List getSource() {
        return source;
    }

    public void setSource(List source) {
        this.source = source;
    }
    @InitBinder// spring mvc中对时间进行处理
    private void InitBinder(HttpServletRequest request,
            ServletRequestDataBinder binder) {
        // spring mvc中对时间进行处理
    binder.registerCustomEditor(Date.class, new CustomDateEditor(
    new SimpleDateFormat("yyyy-MM-dd"), true));
    }
}

部门显示是用ajax异步处理的

script type="text/javascript">
 $(function(){
 $.post("per/dept.do",function(msg){
 for(i=0;i"+msg[i].dname+"");
 }
 });
 });
 

修改页面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
    
    
    
        
    
    
    
  
  


  
  

用户修改

姓名:
性别:
个人特长:足球 篮球 唱歌 武${a}术
学历:
入职时间:
上传修改照片:
部门:
简历:

controller toupdate代码如下

    @RequestMapping("toupdate")
    public String toUpdate(HttpServletRequest request,Person per) throws Exception {// 到修改
        per=ps.getPerson(per.getPid());//获取单个对象
        System.out.println(per.getFilepath());
        request.setAttribute("per",per);//存起来
        
        String []aa=per.getSkilled().split(",");
        for(int i=0;i
链接:http://pan.baidu.com/s/1c10P9PA 密码:clew

你可能感兴趣的:(框架第十五天)