ssm框架整合(spring+spring mvc+mybatis)
開發(fā)步驟:
1.新建一個web工程
2.導入ssm框架的jar包
- 配置三大框架的的配置文件
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>
<!-- 上下文環(huán)境 配置文件位置 -->
<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開發(fā)一般只攔.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的關(guān)閉與開啟問題
<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>
<!-- 加載屬性文件 -->
<context:property-placeholder location="classpath:jdbc.properties" />
<!-- 配置c3p0 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName">
<value>${jdbc.driverClassName}</value>
</property>
<property name="url">
<value>${jdbc.url}</value>
</property>
<property name="username">
<value>${jdbc.username}</value>
</property>
<property name="password">
<value>${jdbc.password}</value>
</property>
<!--連接池中保留的最小連接數(shù)揪惦。 -->
<property name="initialSize" value="3" />
<!-- 連接池的最大值 -->
<property name="maxActive" value="300" />
<!-- 最大空閑值.當經(jīng)過一個高峰時間后惨远,連接池可以慢慢將已經(jīng)用不到的連接慢慢釋放一部分兑牡,一直減少到maxIdle為止 -->
<property name="maxIdle" value="2" />
<!-- 最小空閑值.當空閑的連接數(shù)少于閥值時拴清,連接池就會預申請去一些連接檩小,以免洪峰來時來不及申請 -->
<property name="minIdle" value="1" />
</bean>
<!--配置 mybaties -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--dataSource屬性指定要用到的連接池 -->
<property name="dataSource" ref="dataSource" />
<!-- 所有配置的mapper文件 -->
<property name="mapperLocations" value="classpath*:com/hw/mapper/*Mapper.xml" /><!-- 相當于實現(xiàn)接口 -->
</bean>
<!-- 配置bean 自動掃描所有mapper 自動給Mapper接口產(chǎn)生代理類對象 并且給代理對象注入SqlSessionFactory -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage">
<value>com.hw.mapper</value><!-- 即原來框架整合時的dao包 -->
</property>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
</bean>
<!-- (事務(wù)管理)transaction manager, use JtaTransactionManager for global tx -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- 純注解方式,只需要所需類前加上 @Transactional -->
<tx:annotation-driven transaction-manager="transactionManager" />
</beans>
開發(fā)項目時次泽,上面的配置文件一般都不用改變
需要改變的有1望迎、<property name="mapperLocations" value="classpath:com/hw/mapper/Mapper.xml" /> 這里面
根據(jù)情況作出改變2、<value>com.hw.mapper</value>
對應的包根據(jù)情況改變
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 去掃描類 建立關(guān)聯(lián) -->
<!-- 是對包進行掃描桐智,實現(xiàn)注釋驅(qū)動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>
上面的配置文件一般情況不改變,需要加功能可以往里面添加然磷,比如上傳下載需要用到文件上傳解析器
4 與開發(fā)接口的關(guān)聯(lián)的映射文件
userDaoMapper.xml
<?xml version="1.0" encoding="UTF-8" ?><!-- 相當于實現(xiàn)dao中的接口 -->
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- namespace如果和spring整合時要用接口全類名,不整合任意名,id要用接口中的方法名 -->
<mapper namespace="com.hw.mapper.UserDao">
<resultMap type="com.hw.entity.User" id="userinfo"><!-- 如果不用resultMap則不寫 -->
<result column="uid" property="uid" />
<result column="userName" property="userName" />
<result column="userPass" property="userPass" />
</resultMap>
<!-- parameterType參數(shù)類型,parameterMap參數(shù)集合郑趁,id要用接口中的方法名 -->
<select id="login" parameterType="map" resultType="boolean"><!-- 用戶登錄 -->
select * from tab_user where userName=#{userName} and userPass=#{userPass}
</select>
<insert id="add" parameterType="com.hw.entity.User">
insert into tab_user values(null,#{userName},#{userPass})
</insert>
</mapper>
注意返回類型是boolean,傳入?yún)?shù)是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加密后和數(shù)據(jù)庫的表中的對應字段進行比較
Map<String,Object> map=new HashMap<String,Object>();
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";
}
}
}
上面要注意創(chuàng)建map集合存取對應的值
deptDaoMapper.xml
<?xml version="1.0" encoding="UTF-8" ?><!-- 相當于實現(xiàn)dao中的接口 -->
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- namespace如果和spring整合時要用接口全類名,不整合任意名,id要用接口中的方法名 -->
<mapper namespace="com.hw.mapper.DeptDao">
<resultMap type="com.hw.entity.Dept" id="deptinfo"><!-- 如果不用resultMap則不寫 -->
<result column="did" property="did" />
<result column="dname" property="dname" />
<!-- mybatis中 1方配置多方 --><!-- 對一個屬性的類型是集合,就使用collection
對于一個屬性的類型是一個類,就使用association
-->
<collection property="per" ofType="com.hw.entity.Person">
<result column="pid" property="pid" />
<result column="pname" property="pname" />
<result column="psex" property="psex" />
<result column="skilled" property="skilled" />
<result column="degree" property="degree" />
<result column="jobtime" property="jobtime" javaType="java.sql.Date" jdbcType="DATE" />
<result column="resume" property="resume" />
<result column="filepath" property="filepath" />
</collection>
</resultMap>
<!-- parameterType參數(shù)類型,parameterMap參數(shù)集合寡润,id要用接口中的方法名 -->
<select id="list" resultMap="deptinfo"><!-- 用戶登錄 -->
select * from tab_dept
</select>
<insert id="add" parameterType="com.hw.entity.Dept">
insert into tab_dept values(null,#{dname})
</insert>
</mapper>
上面主要是注意1對多的關(guān)系,使用collection
personDaoMapper.xml
<?xml version="1.0" encoding="UTF-8" ?><!-- 相當于實現(xiàn)dao中的接口 -->
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- namespace如果和spring整合時要用接口全類名,不整合任意名,id要用接口中的方法名 -->
<mapper namespace="com.hw.mapper.PersonDao">
<resultMap type="com.hw.entity.Person" id="personinfo"><!-- 如果不用resultMap則不寫 -->
<result column="pid" property="pid" />
<result column="pname" property="pname" />
<result column="psex" property="psex" />
<result column="skilled" property="skilled" />
<result column="degree" property="degree" />
<result column="jobtime" property="jobtime" javaType="java.sql.Date"
jdbcType="DATE" />
<result column="resume" property="resume" />
<result column="filepath" property="filepath" />
<!-- mybatis中 多方配置1方 --><!-- 對一個屬性的類型是集合,就使用collection
對于一個屬性的類型是一個類,就使用association
-->
<!--多對一的關(guān)系, property: 指的是屬性的值, javaType:指的是屬性的類型 -->
<association property="dept" javaType="com.hw.entity.Dept">
<result column="did" property="did" />
<result column="dname" property="dname" />
</association>
</resultMap>
<!-- parameterType參數(shù)類型,parameterMap參數(shù)集合痪欲,id要用接口中的方法名 -->
<insert id="add" parameterType="com.hw.entity.Person">
insert into tab_per
values(null,#{pname},#{psex},#{skilled},#{degree},#{jobtime},#{resume},
#{filepath},#{dept.did})
</insert>
<update id="updatePerson" parameterType="com.hw.entity.Person">
update tab_per set pname=#{pname},psex=#{psex},skilled=#{skilled},
degree=#{degree},jobtime=#{jobtime},resume=#{resume},
filepath=#{filepath},did=#{dept.did} where pid=#{pid}
</update>
<delete id="del" parameterType="int" >
delete from tab_per where pid=#{pid}
</delete>
<!-- 批量刪除 -->
<delete id="delSelectAll" parameterType="string">
delete from tab_per where pid in
<foreach collection="array" item="pid" open="(" separator="," close=")">
#{pid}
</foreach>
</delete>
<select id="getPerson" parameterType="int" resultMap="personinfo">
select * from tab_per where pid=#{pid}
</select>
<select id="list" parameterType="map" resultMap="personinfo">
select p.*,d.dname from tab_per p,tab_dept d where p.did=d.did order by p.pid desc
limit #{pageIndex},#{pageSize}
</select>
<select id="listLike" parameterType="map" resultMap="personinfo">
select p.*,d.dname from tab_per p,tab_dept d where p.did=d.did and p.pname like
'%${pname}%' and p.did=#{did} order by p.pid desc
limit #{pageIndex},#{pageSize}
</select>
<select id="getLikeCount" resultType="int" parameterType="map">
select count(pid) from tab_per where pname like '%${pname}%' and did=#{did}
</select>
<select id="listAll" resultMap="personinfo">
select p.*,d.dname from tab_per p,tab_dept d where p.did=d.did order by p.pid desc
</select>
<select id="getCount" resultType="int">
select count(pid) from tab_per
</select>
</mapper>
上面主要是注意多對一的關(guān)系,使用association 類與類之間的關(guān)聯(lián)
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<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());//獲取單個對象
request.setAttribute("per",per);//存起來
String []aa=per.getSkilled().split(",");
for(int i=0;i<aa.length;i++){
if(aa[i].equals("武術(shù)")){
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(MultipartFile file,HttpServletRequest request,Person user) throws Exception {// 添加
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);
user.setFilepath(fileName);
}else{
user.setFilepath("");
}
/*如果不涉及上傳則表單中不能設(shè)置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());
}
/*如果不涉及上傳則表單中不能設(shè)置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攻礼,或則取頁數(shù)
int currentPage = Integer.parseInt(page);// 當前頁
int pageSize = 3;// 當前頁記錄大小
int dataCount = ps.getCount();// 表記錄多少
Map<String,Object> map=new HashMap<String, Object>();
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业踢,或則取頁數(shù)
int currentPage = Integer.parseInt(page);// 當前頁
String querypdept = request.getParameter("querypdept");
String querypname = request.getParameter("querypname");
System.out.println(querypdept+" ,"+querypname);
int pageSize = 3;// 當前頁記錄大小
Map<String,Object> map=new HashMap<String, Object>();
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[] { "員工編號", "姓名", "性別", "特長", "學歷",
"入職時間", "簡歷", "照片", "部門" };
//定義表的內(nèi)容
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);
}
// 創(chuàng)建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") //spring mvc導入excel
public String importExcel(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();
}
// 獲取服務(wù)器中文件的路徑
String paths =request.getSession().getServletContext().getRealPath("")
+ "/upload/" + fileName;
// 上傳文件到服務(wù)器中
// 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);
// 循環(huán)工作表Sheet
for (int numSheet = 0; numSheet < hssfWorkbook.getNumberOfSheets(); numSheet++) {
HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(numSheet);
if (hssfSheet == null) {
continue;
}
// 循環(huán)行Row
for (int rowNum = 3; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
HSSFRow hssfRow = hssfSheet.getRow(rowNum);
if (hssfRow == null) {
continue;
}
// 循環(huán)列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();// 得到數(shù)據(jù)庫中的部門列表
for (Dept dd : list) {// 增強for循環(huán)
if (dd.getDname().equals(dname)) {// 如果兩者匹配
dept.setDid(dd.getDid());// 則得到對應的did知举,并設(shè)置dept對象的did
per.setDept(dept);// 再把dept對象設(shè)置到user對象中
}
}
ps.add(per);// 寫入到數(shù)據(jù)中
}
}
} 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) {
// 返回數(shù)值類型的值
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 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));
}
}
上面主要注意的是圖片路徑的設(shè)置問題 add添加時加一個判斷,如果路徑為空時
設(shè)置一個空的字符串防止報錯
if(fileName.length()>0){ }else{
user.setFilepath("");
}
同理太伊,update修改也需要加一個判斷雇锡,如果不修改路徑則為原路徑?jīng)]修改則
改變路徑
if(fileName.length()>0){ }else{
per.setFilepath(per.getFilepath());
}
另外,注意批量刪除傳入的參數(shù)是數(shù)組僚焦,按照上面做法即可
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) {
var aa = "${per.dept.did}";//將需要修改的部門id賦值給aa
for (i = 0; i < msg.length; i++) {
$("#querypdept").append(
"<option value="+msg[i].did+">" + msg[i].dname
+ "</option>");
if (msg[i].did == aa) {//判斷部門id是否相等,相等則默認選擇對應部門
$("#querypdept option[value='" + msg[i].did + "']").attr(
'selected', 'selected');
}
}
});
});
</script>
<body>
<center>
<h2>用戶修改</h2>
<form action="per/update.do" method="post" name="kk"
enctype="multipart/form-data">
<table border=0 width=460 >
<tr>
<td>
員工編號:<input type="text" readonly="readonly" name="pid" value="${per.pid }" /><br>
姓名:<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="武術(shù)" ${a=='武術(shù)'?"checked='checked'":"" }>武術(shù)<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>
上面主要加了
var aa = "${per.dept.did}";//將需要修改的部門id賦值給aa
if (msg[i].did == aa) {
//判斷部門id是否相等,相等則默認選擇對應部門
$("#querypdept option[value='" + msg[i].did + "']").attr('selected', 'selected');
}
注釋也很清楚了芳悲,不多說
還有一個方法是利用c標簽也可以實現(xiàn)部門回顯
部門:<select name="dept.deid">
<c:forEach items="${list}" var="dept" >
<c:choose>
<c:when test="${doctor.dept.deid==dept.deid}">
<option value="${dept.deid }" selected="selected" >${dept.dname }</option>
</c:when>
<c:otherwise><option value="${dept.deid }" >
${dept.dname }</option>
</c:otherwise>
</c:choose>
</c:forEach>
</select>
相關(guān)源碼:
鏈接:http://pan.baidu.com/s/1hsmLf72 密碼:2ujv