框架第十五天

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


poi的jar包.png

用到的jar包过多不方便截图(其实有些jar包是没用到的),可到我的工程里面看
2 配置三大框架的的配置文件
web.xml 配置文件

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
    xmlns="http://java.sun.com/xml/ns/javaee" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <display-name></display-name> 
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  <!-- 以下为配置spring  -->
  <!-- 配置spring listener -->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
      <!-- 上下文环境 配置文件位置 -->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
  </context-param>
  
  <!-- 以下为配置spring mvc -->
  <servlet>
  <servlet-name>mvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
      <load-on-startup>1</load-on-startup>
</servlet>
  <servlet-mapping>
  <servlet-name>mvc</servlet-name>
  <url-pattern>*.do</url-pattern><!-- springmvc开发一般只拦.do文件 -->
  </servlet-mapping>
  <!-- 配置编码控制器 -->
  <filter>
    <filter-name>encodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
        <param-name>encoding</param-name>
        <param-value>utf-8</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
<!-- 配置OpenSessionInViewFilter,解决Hibernate的Session的关闭与开启问题-->
<filter>
    <filter-name>openSessionInView</filter-name>
    <filter-class>
    org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
               </filter-class>
        <init-param>
        <param-name>sessionFactoryBeanName</param-name>
        <param-value>sessionFactory</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>openSessionInView</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

</web-app>

applacitonContext.xml(置于src根目录下) (这里配置的是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:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
    <!-- 自动扫描 -->
    <context:component-scan base-package="com.hw"></context:component-scan>
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        <property name="url"
            value="jdbc:mysql://localhost:3306/cc?useUnicode=true&characterEncoding=utf8"></property>
        <property name="username" value="root"></property>
        <property name="password" value="huayu123" />

        <!-- 连接池启动时的初始值 -->
        <property name="initialSize" value="3" />
        <!-- 连接池的最大值 -->
        <property name="maxActive" value="300" />
        <!-- 最大空闲值.当经过一个高峰时间后,连接池可以慢慢将已经用不到的连接慢慢释放一部分,一直减少到maxIdle为止 -->
        <property name="maxIdle" value="2" />
        <!-- 最小空闲值.当空闲的连接数少于阀值时,连接池就会预申请去一些连接,以免洪峰来时来不及申请 -->
        <property name="minIdle" value="1" />
    </bean>

    <!-- 配置sessionFactory -->
    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <!-- 分开整合<property name="configLocation" value="classpath:hibernate.cfg.xml"> 
            </property> -->
        <property name="dataSource" ref="dataSource"></property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.format_sql">true</prop>
            </props>
        </property>
        <property name="mappingResources"><!-- hibernate映射文件 -->
            <list>
                <value>com/hw/entity/Dept.hbm.xml</value>
                <value>com/hw/entity/Person.hbm.xml</value>
                <value>com/hw/entity/User.hbm.xml</value>
            </list>
        </property>

    </bean>

    <!-- xml方式配置 -->

    <bean id="transactionManager"
        class=" org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>

    <!-- 激活自动代理功能 -->
    <aop:aspectj-autoproxy proxy-target-class="true" />

    <aop:config><!-- 定义一个切面,并将事务通知和切面组合 -->
        <aop:pointcut expression="execution(* com.hw.service.impl.*.*(..))"
            id="trPointcut" />
        <aop:advisor advice-ref="trcut" pointcut-ref="trPointcut" />
    </aop:config>

    <!-- 定义事务通知 -->
    <tx:advice id="trcut" transaction-manager="transactionManager">
        <!-- 定义事务传播规则 -->
        <tx:attributes>
            <tx:method name="add*" propagation="REQUIRED" />
            <tx:method name="update*" propagation="REQUIRED" />
            <tx:method name="del*" propagation="REQUIRED" />
            <tx:method name="*" propagation="REQUIRED" read-only="true" />
            <!-- 也可以对所有方法都应用REQUIRED事务规则 <tx:method name="*" propagation="REQUIRED"/> -->
        </tx:attributes>
    </tx:advice>
    <!-- 配置spring事务 基于全注解开发,只需在所需类前加上:@Transactional 
              不需要事务的方法前加上: @Transactional(propagation = Propagation.NOT_SUPPORTED) 
        <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate"> 
        <property name="sessionFactory" ref="sessionFactory"></property> </bean> 
        
        <bean id="transactionManager" class=" org.springframework.orm.hibernate3.HibernateTransactionManager"> 
        <property name="sessionFactory" ref="sessionFactory"></property> </bean> 
        
        <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/> -->
</beans>

mvc-servlet.xml(置于WEB-INF文件夹下) (这里配置的spring 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.1.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
    <!-- 让spring 去扫描类  建立关联 -->
    <!-- 是对包进行扫描,实现注释驱动Bean定义,同时将bean自动注入容器中使用。即解决了@Controller标识的类的bean的注入和使用 -->
    <mvc:annotation-driven/>
<!-- 扫苗controll包即下面的控制器 -->
<context:component-scan base-package="com.hw.controller"></context:component-scan>
<!-- 试图解析器 -->
<bean
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">
 <!-- 前缀 -->
 <property name="prefix" value="/WEB-INF/per/"></property>
 <!-- 后缀-->
 <property name="suffix" value=".jsp"></property>
</bean>
<!-- 文件上传解析器 -->
    <bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- one of the properties available; the maximum file size in bytes -->
       <property name="defaultEncoding" value="utf-8" />
        <property name="maxUploadSize" value="104857600"/>
        <property name="maxInMemorySize" value="4096"/>
    </bean>
</beans>

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<Dept> list=new ArrayList<Dept>();//有set get方法
    private File myfile;//有set get方法
    private String myfileFileName;//有set get方法
    private List<String> perlist=new ArrayList<String>();
    private List<Person> source=new ArrayList<Person>();
    @RequestMapping("dept")
    @ResponseBody  //生成json格式
    public List<Dept> dept(){//下载
        List<Dept> 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<aa.length;i++){
         if(aa[i].equals("武术")){
             request.setAttribute("a",aa[i]);    
         }else if(aa[i].equals("足球")){
             request.setAttribute("b",aa[i]);    
         }else if(aa[i].equals("唱歌")){
             request.setAttribute("c",aa[i]);    
         }else if(aa[i].equals("篮球")){
             request.setAttribute("d",aa[i]);    
         }
         }
        return "update";
    }
    @RequestMapping("add")
    public String add(@RequestParam(value = "file", required = false) MultipartFile file,
            HttpServletRequest request,Person user) throws Exception {// 添加
        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();
        }
        request.setAttribute("fileUrl", request.getContextPath() + "/upload/"
                + fileName);
        user.setFilepath(fileName);
        /*如果不涉及上传则表单中不能设置enctype="multipart/form-data",
         * 本方法中只需保留Person pe和以下2行代码即可
         */
        ps.add(user);
        return "redirect:listPerson.do";
    }
@RequestMapping("update")
    public String update(@RequestParam(value = "file", required = false) MultipartFile file,
            HttpServletRequest request,Person per) {    
        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();
        }
        request.setAttribute("fileUrl", request.getContextPath() + "/upload/"
                + fileName);
        per.setFilepath(fileName);
        /*如果不涉及上传则表单中不能设置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);
        ps.delSelectAll(id);//删除
        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();// 表记录多少
        source = ps.list(currentPage, pageSize);
        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;// 当前页记录大小
        int dataCount = ps.getLikeCount("did:"+querypdept,"pname:"+querypname);// 表记录多少
        source = ps.listLike(currentPage, pageSize,"did:"+querypdept,"pname:"+querypname);
//      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") 
   public String exportExcel(HttpServletResponse response) throws Exception {
        
        // 初始化HttpServletResponse对象
        
        // 定义表的标题
        String title = "员工列表一览";
        
        //定义表的列名
        String[] rowsName = new String[] { "员工编号", "姓名", "性别", "特长", "学历",
                "入职时间", "简历", "照片", "部门" };
        
        //定义表的内容
        List<Object[]> dataList = new ArrayList<Object[]>();
        Object[] objs = null;
        List<Person> 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<Dept> getList() {
        return list;
    }

    public void setList(List<Dept> 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<String> getPerlist() {
        return perlist;
    }

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

    public List<Person> getSource() {
        return source;
    }

    public void setSource(List<Person> 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.length;i++){
 $("#querypdept").append("<option value="+msg[i].did+">"+msg[i].dname+"</option>");
 }
 });
 });
 </script>

修改页面update.jsp回显按如下代码实现

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 's1.jsp' starting page</title>
    
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
  <script type="text/javascript" src="js/My97DatePicker/WdatePicker.js"></script></head>
  <script type="text/javascript"
    src="<%=request.getContextPath()%>/js/jquery-1.8.2.js"></script>
<script type="text/javascript"
    src="<%=request.getContextPath()%>/js/my.js" charset="gbk"></script>
<script type="text/javascript">
    $(function() {
        $.post("per/dept.do", function(msg) {
            for (i = 0; i < msg.length; i++) {
                $("#querypdept").append(
                        "<option value="+msg[i].did+">" + msg[i].dname
                                + "</option>");
            }
        });
    });
</script>
  <body>
  <center>
  <h2>用户修改</h2>
        <form action="per/update.do" method="post" name="kk"
            enctype="multipart/form-data">
            <input type="hidden" name="pid" value="${per.pid }" />
            <table border=0 width=460 >
                <tr>
                    <td>姓名:<input type="text" name="pname" value="${per.pname }" /><br>
                        性别:<input type="radio" name="psex" value="男" ${per.psex=='男'?"checked='checked'":"" }>男<input
                        type="radio" name="psex" value="女"  ${per.psex=='女'?"checked='checked'":"" }>女<br> 个人特长:<input
                        type="checkbox" name="skilled" value="足球" ${b=='足球'?"checked='checked'":"" } >足球 <input
                        type="checkbox" name="skilled" value="篮球" ${d=='篮球'?"checked='checked'":"" } >篮球 <input
                        type="checkbox" name="skilled" value="唱歌" ${c=='唱歌'?"checked='checked'":"" } >唱歌
                        <input type="checkbox" name="skilled" value="武术" ${a=='武术'?"checked='checked'":"" }>武${a}术<br>
                        学历:<select name="degree">
                            <option ${per.degree== "博士"?"selected='selected'":""}>博士</option>
                            <option ${per.degree== "研究生"?"selected='selected'":""}>研究生</option>
                            <option ${per.degree== "本科"?"selected='selected'":""}>本科</option>
                            <option ${per.degree== "专科"?"selected='selected'":""}>专科</option>
                    </select><br> 入职时间: <input type="text" name="jobtime"
                        onclick="WdatePicker()" value="${per.jobtime }"><br>
                        上传修改照片: <input type="file" name="file"><img src="<%=request.getContextPath()%>/upload/${per.filepath}" 
   width="85" height="100"><br> 部门: <select
                        name="dept.did" id="querypdept"></select><br> 简历: <textarea
                            name="resume" cols="20" rows="6">${per.resume }</textarea>
                    </td>
                </tr>
                <tr>
                    <td align="center" colspan="10"><input type=submit value="修改">
                        <input type=reset value="清空"></td>
                </tr>
            </table>
        </form>
    </center>
   
   
   
  </body>
</html>

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<aa.length;i++){
         if(aa[i].equals("武术")){
             request.setAttribute("a",aa[i]);    
         }else if(aa[i].equals("足球")){
             request.setAttribute("b",aa[i]);    
         }else if(aa[i].equals("唱歌")){
             request.setAttribute("c",aa[i]);    
         }else if(aa[i].equals("篮球")){
             request.setAttribute("d",aa[i]);    
         }
         }
        return "update";
    }
链接:http://pan.baidu.com/s/1c10P9PA 密码:clew
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 205,033评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 87,725评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,473评论 0 338
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,846评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,848评论 5 368
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,691评论 1 282
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,053评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,700评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 42,856评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,676评论 2 323
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,787评论 1 333
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,430评论 4 321
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,034评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,990评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,218评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,174评论 2 352
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,526评论 2 343

推荐阅读更多精彩内容