20170314_ssm(spring+spring MVC +Mybatis)

最终效果:

 

源代码:

1、新建web工程

 

 

2、导入jar包

 

 

3、配置web.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
 3     <display-name></display-name>
 4     <welcome-file-list>
 5         <welcome-file>index.jsp</welcome-file>
 6     </welcome-file-list>
 7     
 8     <!-- spring 监听及配置文件路径 -->
 9     <listener>
10         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
11     </listener>
12     <context-param>
13         <param-name>contextConfigLocation</param-name>
14         <param-value>classpath:applicationContext.xml</param-value>
15     </context-param>
16     
17     <!-- spring MVC配置文件路径 及 配置拦截-->
18     <servlet>
19         <servlet-name>mvc</servlet-name>
20         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
21         <init-param>
22             <param-name>contextConfigLocation</param-name>
23             <param-value>classpath:config/mvc-servlet.xml</param-value>
24         </init-param>
25     </servlet>    
26     <servlet-mapping>
27         <servlet-name>mvc</servlet-name>
28         <url-pattern>*.do</url-pattern>
29     </servlet-mapping>
30     
31     
32     <!-- 编码配置 -->
33     <filter>
34         <filter-name>encodingFilter</filter-name>
35         <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
36         <init-param>
37             <param-name>encoding</param-name>
38             <param-value>utf-8</param-value>
39         </init-param>
40     </filter>
41     <filter-mapping>
42         <filter-name>encodingFilter</filter-name>
43         <url-pattern>/*</url-pattern>
44     </filter-mapping>
45     
46     
47 </web-app>
web.xml

 

 

4、配置mvc-servlet.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <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
 3         http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
 4         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
 5         http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
 6         http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
 7     
 8     
 9     <!-- 让spring 去扫描类 建立关联 -->
10     <!-- 是对包进行扫描,实现注释驱动Bean定义,同时将bean自动注入容器中使用。即解决了@Controller标识的类的bean的注入和使用 -->
11     <mvc:annotation-driven />
12     
13     
14     <!-- 扫描controller包即下面的控制器 -->
15     <context:component-scan base-package="com.hw.controller"></context:component-scan>
16     
17     
18     <!-- 试图解析器 -->
19     <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
20         <!-- 前缀 -->
21         <property name="prefix" value="/WEB-INF/per/"></property>
22         <!-- 后缀 -->
23         <property name="suffix" value=".jsp"></property>
24     </bean>
25     
26     
27     <!-- 文件上传解析器 -->
28     <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
29         <!-- one of the properties available; the maximum file size in bytes -->
30         <property name="defaultEncoding" value="utf-8" />
31         <property name="maxUploadSize" value="104857600" />
32         <property name="maxInMemorySize" value="4096" />
33     </bean>
34 </beans>
mvc-servlet.xml

 

 

5、配置applicationContext.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <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
 3 http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
 4 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
 5 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
 6 
 7     <!-- 自动扫描 -->
 8     <context:component-scan base-package="com.hw"></context:component-scan>
 9     
10     
11     <!-- 加载属性文件 -->    
12     <context:property-placeholder location="classpath:jdbc.properties" />
13     
14     
15     <!-- 配置c3p0 -->
16     <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
17         <property name="driverClassName">
18             <value>${jdbc.driverClassName}</value>
19         </property>
20         <property name="url">
21             <value>${jdbc.url}</value>
22         </property>
23         <property name="username">
24             <value>${jdbc.username}</value>
25         </property>
26         <property name="password">
27             <value>${jdbc.password}</value>
28         </property>
29         <!--连接池中保留的最小连接数。 -->
30         <property name="initialSize" value="3" />
31         <!-- 连接池的最大值 -->
32         <property name="maxActive" value="300" />
33         <!-- 最大空闲值.当经过一个高峰时间后,连接池可以慢慢将已经用不到的连接慢慢释放一部分,一直减少到maxIdle为止 -->
34         <property name="maxIdle" value="2" />
35         <!-- 最小空闲值.当空闲的连接数少于阀值时,连接池就会预申请去一些连接,以免洪峰来时来不及申请 -->
36         <property name="minIdle" value="1" />
37     </bean>
38     
39     
40     <!--配置 mybaties -->
41     <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
42         <!--dataSource属性指定要用到的连接池 -->
43         <property name="dataSource" ref="dataSource" />
44         <!-- 所有配置的mapper文件 -->
45         <property name="mapperLocations" value="classpath*:com/hw/mapper/*Mapper.xml" />
46     </bean>
47     
48     
49     <!-- 配置bean 自动扫描所有mapper 自动给Mapper接口产生代理类对象 并且给代理对象注入SqlSessionFactory -->
50     <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
51         <property name="basePackage">
52             <value>com.hw.mapper</value><!-- 即原来框架整合时的dao包 -->
53         </property>
54         <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
55     </bean>
56 
57     
58     <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx -->
59     <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
60         <property name="dataSource" ref="dataSource" />
61     </bean>
62     
63     
64     <!-- 纯注解方式,只需要所需类前加上 @Transactional -->
65     <tx:annotation-driven transaction-manager="transactionManager" />
66 </beans>
applicationContext.xml

 

 

6、配置jdbc.properties

1 jdbc.driverClassName=com.mysql.jdbc.Driver
2 jdbc.url=jdbc:mysql://localhost:3306/cc3?useUnicode=true&amp;characterEncoding=utf8
3 jdbc.username=root
4 jdbc.password=root
jdbc.properties

 

 

7、com.hw.entity中的代码:

1)Person.java中代码:

  1 package com.hw.entity;
  2 
  3 import java.util.Date;
  4 
  5 public class Person {
  6     private int pid;
  7     private String pname;
  8     private String psex;
  9     private String skilled;
 10     private String degree;
 11     private Date jobtime;// 要和数据库中表的字段类型一致
 12     private String resume;
 13     private String filepath;// 上传图片,名要为filepath
 14     private Dept dept;
 15 
 16     public int getPid() {
 17         return pid;
 18     }
 19 
 20     public void setPid(int pid) {
 21         this.pid = pid;
 22     }
 23 
 24     public String getPname() {
 25         return pname;
 26     }
 27 
 28     public void setPname(String pname) {
 29         this.pname = pname;
 30     }
 31 
 32     public String getPsex() {
 33         return psex;
 34     }
 35 
 36     public void setPsex(String psex) {
 37         this.psex = psex;
 38     }
 39 
 40     public String getSkilled() {
 41         return skilled;
 42     }
 43 
 44     public void setSkilled(String skilled) {
 45         this.skilled = skilled;
 46     }
 47 
 48     public String getDegree() {
 49         return degree;
 50     }
 51 
 52     public void setDegree(String degree) {
 53         this.degree = degree;
 54     }
 55 
 56     public Date getJobtime() {
 57         return jobtime;
 58     }
 59 
 60     public void setJobtime(Date jobtime) {
 61         this.jobtime = jobtime;
 62     }
 63 
 64     public String getResume() {
 65         return resume;
 66     }
 67 
 68     public void setResume(String resume) {
 69         this.resume = resume;
 70     }
 71 
 72     public String getFilepath() {
 73         return filepath;
 74     }
 75 
 76     public void setFilepath(String filepath) {
 77         this.filepath = filepath;
 78     }
 79 
 80     public Dept getDept() {
 81         return dept;
 82     }
 83 
 84     public void setDept(Dept dept) {
 85         this.dept = dept;
 86     }
 87 
 88     public Person(int pid, String pname, String psex, String skilled,
 89             String degree, Date jobtime, String resume, String filepath,
 90             Dept dept) {
 91         super();
 92         this.pid = pid;
 93         this.pname = pname;
 94         this.psex = psex;
 95         this.skilled = skilled;
 96         this.degree = degree;
 97         this.jobtime = jobtime;
 98         this.resume = resume;
 99         this.filepath = filepath;
100         this.dept = dept;
101     }
102 
103     public Person(String pname, String psex, String skilled, String degree,
104             Date jobtime, String resume, String filepath, Dept dept) {
105         super();
106         this.pname = pname;
107         this.psex = psex;
108         this.skilled = skilled;
109         this.degree = degree;
110         this.jobtime = jobtime;
111         this.resume = resume;
112         this.filepath = filepath;
113         this.dept = dept;
114     }
115 
116     public Person() {
117         super();
118     }
119 
120 }
Person.java

2) Dept.java中代码:

 1 package com.hw.entity;
 2 
 3 import java.util.HashSet;
 4 import java.util.Set;
 5 
 6 import org.hibernate.annotations.Entity;
 7 
 8 import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
 9 public class Dept implements java.io.Serializable{
10     private int did;
11     private String dname;
12     private Set<Person> per = new HashSet<Person>();
13 //都有set get方法,全参、无参、除id外的构造方法
14     public Dept() {
15         super();
16     }
17 
18     public Dept(String dname, Set<Person> per) {
19         super();
20         this.dname = dname;
21         this.per = per;
22     }
23 
24     public Dept(int did, String dname, Set<Person> per) {
25         super();
26         this.did = did;
27         this.dname = dname;
28         this.per = per;
29     }
30 
31     public int getDid() {
32         return did;
33     }
34 
35     public void setDid(int did) {
36         this.did = did;
37     }
38 
39     public String getDname() {
40         return dname;
41     }
42 
43     public void setDname(String dname) {
44         this.dname = dname;
45     }
46 
47     public Set<Person> getPer() {
48         return per;
49     }
50 
51     public void setPer(Set<Person> per) {
52         this.per = per;
53     }
54 
55 }
Dept.java

3) User.java中代码:

 1 package com.hw.entity;
 2 
 3 import com.hw.utils.HibernateXMLAutoCreateUtils;
 4 
 5 public class User {
 6     private int uid;
 7     private String userName, userPass;
 8 
 9     public int getUid() {
10         return uid;
11     }
12 
13     public void setUid(int uid) {
14         this.uid = uid;
15     }
16 
17     public String getUserName() {
18         return userName;
19     }
20 
21     public void setUserName(String userName) {
22         this.userName = userName;
23     }
24 
25     public String getUserPass() {
26         return userPass;
27     }
28 
29     public void setUserPass(String userPass) {
30         this.userPass = userPass;
31     }
32 
33     public User(int uid, String userName, String userPass) {
34         super();
35         this.uid = uid;
36         this.userName = userName;
37         this.userPass = userPass;
38     }
39 
40     public User(String userName, String userPass) {
41         super();
42         this.userName = userName;
43         this.userPass = userPass;
44     }
45 
46     public User() {
47         super();
48     }
49 public static void main(String[] args) {
50     HibernateXMLAutoCreateUtils.createHibernatePOJOXML(User.class, "uid", "tab_user");
51 }
52 }
User.java

4) Test.java中代码: 

1 package com.hw.entity;
2 
3 import com.hw.utils.HibernateXMLAutoCreateUtils;
4 
5 public class Test {
6 public static void main(String[] args) {
7     HibernateXMLAutoCreateUtils.createHibernatePOJOMappingManyToOne(Person.class, "pid", "tab_per", Dept.class, "did", "tab_dept");
8 }
9 }
Test.java

 

 

8、com.hw.mapper中的代码:

1)DeptDao.java中的代码:

 1 package com.hw.mapper;
 2 
 3 import java.util.List;
 4 
 5 import com.hw.entity.Dept;
 6 
 7 public interface DeptDao {
 8     public void add(Dept dept);
 9 
10     public List<Dept> list();
11 }
DeptDao.java

2)PersonDao.java中的代码:

 1 package com.hw.mapper;
 2 
 3 import java.util.List;
 4 import java.util.Map;
 5 
 6 import com.hw.entity.Person;
 7 
 8 public interface PersonDao {
 9     public int getCount();// 统计总记录
10 
11     public void add(Person per);// 添加
12 
13     public void updatePerson(Person per);// 修改
14 
15     public void del(int id);// 删除
16 
17     public void delSelectAll(String id[]);// 批量删除,要用数组
18 
19     public Person getPerson(int id);
20 
21     public List<Person> list(Map<String, Object> map);// 查询有分页
22 
23     public List<Person> listLike(Map<String, Object> map);// 模糊查询有分页
24 
25     public int getLikeCount(Map<String, Object> map);
26 
27     public List<Person> listAll();// 查询所有有
28 }
PersonDao.java

3) UserDao.java中的代码:

 1 package com.hw.mapper;
 2 
 3 import java.util.Map;
 4 
 5 import com.hw.entity.User;
 6 
 7 public interface UserDao {
 8     void add(User user);// 用户注册
 9 
10     boolean login(Map<String, Object> map);// 用户登录
11 }
UserDao.java

4) deptDaoMapper.xml中的代码:

 1 <?xml version="1.0" encoding="UTF-8" ?><!-- 相当于实现dao中的接口 -->
 2 <!DOCTYPE mapper
 3 PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
 4 "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 5 <!-- namespace如果和spring整合时要用接口全类名,不整合任意名,id要用接口中的方法名 -->
 6 <mapper namespace="com.hw.mapper.DeptDao">
 7 
 8     <resultMap type="com.hw.entity.Dept" id="deptinfo"><!-- 如果不用resultMap则不写 -->
 9         <result column="did" property="did" />
10         <result column="dname" property="dname" />
11 
12 
13         <!-- mybatis中 1方配置多方 -->
14         <collection property="per" ofType="com.hw.entity.Person">
15             <result column="pid" property="pid" />
16             <result column="pname" property="pname" />
17             <result column="psex" property="psex" />
18             <result column="skilled" property="skilled" />
19             <result column="degree" property="degree" />
20             <result column="jobtime" property="jobtime" javaType="java.sql.Date" jdbcType="DATE" />
21             <result column="resume" property="resume" />
22             <result column="filepath" property="filepath" />
23         </collection>
24     </resultMap>
25 
26 
27     <!-- parameterType参数类型,parameterMap参数集合,id要用接口中的方法名 -->
28     <select id="list" resultMap="deptinfo"><!-- 用户登录 -->
29         select * from tab_dept
30     </select>
31 
32 
33     <insert id="add" parameterType="com.hw.entity.Dept">
34         insert into tab_dept values(null,#{dname})
35     </insert>
36 
37 </mapper>
deptDaoMapper.xml

5) personDaoMapper.xml中的代码

 1 <?xml version="1.0" encoding="UTF-8" ?><!-- 相当于实现dao中的接口 -->
 2 <!DOCTYPE mapper
 3 PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
 4 "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 5 <!-- namespace如果和spring整合时要用接口全类名,不整合任意名,id要用接口中的方法名 -->
 6 <mapper namespace="com.hw.mapper.PersonDao">
 7 
 8     <resultMap type="com.hw.entity.Person" id="personinfo"><!-- 如果不用resultMap则不写 -->
 9         <result column="pid" property="pid" />
10         <result column="pname" property="pname" />
11         <result column="psex" property="psex" />
12         <result column="skilled" property="skilled" />
13         <result column="degree" property="degree" />
14         <result column="jobtime" property="jobtime" javaType="java.sql.Date" jdbcType="DATE" />
15         <result column="resume" property="resume" />
16         <result column="filepath" property="filepath" />
17 
18 
19         <!--多对一的关系, property: 指的是属性的值, javaType:指的是属性的类型 -->
20         <association property="dept" javaType="com.hw.entity.Dept">
21             <result column="did" property="did" />
22             <result column="dname" property="dname" />
23         </association>
24     </resultMap>
25 
26 
27     <!-- parameterType参数类型,parameterMap参数集合,id要用接口中的方法名 -->
28     <insert id="add" parameterType="com.hw.entity.Person">
29         insert into tab_per
30         values(null,#{pname},#{psex},#{skilled},#{degree},#{jobtime},#{resume},
31         #{filepath},#{dept.did})
32     </insert>
33 
34 
35     <update id="updatePerson" parameterType="com.hw.entity.Person">
36         update tab_per set pname=#{pname},psex=#{psex},skilled=#{skilled},
37         degree=#{degree},jobtime=#{jobtime},resume=#{resume},
38         filepath=#{filepath},did=#{dept.did} where pid=#{pid}
39     </update>
40 
41 
42     <delete id="del" parameterType="int">
43         delete from tab_per where pid=#{pid}
44     </delete>
45 
46 
47     <!-- 批量删除 -->
48     <delete id="delSelectAll" parameterType="string">
49         delete from tab_per where pid in
50         <foreach collection="array" item="pid" open="(" separator="," close=")">
51             #{pid}
52         </foreach>
53     </delete>
54 
55 
56     <select id="getPerson" parameterType="int" resultMap="personinfo">
57         select * from tab_per where pid=#{pid}
58     </select>
59 
60 
61     <select id="list" parameterType="map" resultMap="personinfo">
62         select p.*,d.dname from tab_per p,tab_dept d where p.did=d.did order by p.pid desc
63         limit #{pageIndex},#{pageSize}
64     </select>
65 
66 
67     <select id="listLike" parameterType="map" resultMap="personinfo">
68         select p.*,d.dname from tab_per p,tab_dept d where p.did=d.did and p.pname like
69         '%${value}%' and p.did=#{did} order by p.pid desc
70         limit #{pageIndex},#{pageSize}
71     </select>
72 
73 
74     <select id="getLikeCount" resultType="int" parameterType="map">
75         select count(pid) from tab_per where pname like '%${value}%' and did=#{did}
76     </select>
77 
78 
79     <select id="listAll" resultMap="personinfo">
80         select p.*,d.dname from tab_per p,tab_dept d where p.did=d.did order by p.pid desc
81     </select>
82 
83 
84     <select id="getCount" resultType="int">
85         select count(pid) from tab_per
86     </select>
87 
88 </mapper>
personDaoMapper.xml

6) userDaoMapper.xml

 1 <?xml version="1.0" encoding="UTF-8" ?><!-- 相当于实现dao中的接口 -->
 2 <!DOCTYPE mapper
 3 PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
 4 "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 5 <!-- namespace如果和spring整合时要用接口全类名,不整合任意名,id要用接口中的方法名 -->
 6 <mapper namespace="com.hw.mapper.UserDao">
 7     
 8     
 9     <resultMap type="com.hw.entity.User" id="userinfo"><!-- 如果不用resultMap则不写 -->
10         <result column="uid" property="uid" />
11         <result column="userName" property="userName" />
12         <result column="userPass" property="userPass" />
13     </resultMap>
14     
15     
16     <!-- parameterType参数类型,parameterMap参数集合,id要用接口中的方法名 -->
17     <select id="login" parameterType="map" resultType="boolean"><!-- 用户登录 -->
18         select * from tab_user where userName=#{userName} and userPass=#{userPass}
19     </select>
20     
21     
22     <insert id="add" parameterType="com.hw.entity.User">
23         insert into tab_user values(null,#{userName},#{userPass})
24     </insert>
25     
26 </mapper>
userDaoMapper.xml

 

 

9、com.hw.service

a) com.hw.service

    (1)DeptService.java中的代码:

 1 package com.hw.service;
 2 
 3 import java.util.List;
 4 
 5 import com.hw.entity.Dept;
 6 
 7 public interface DeptService {
 8     public void add(Dept dept);
 9 
10     public List<Dept> list();
11 }
DeptService.java

   (2)PersonService.java中的代码:

 1 package com.hw.service;
 2 
 3 import java.util.List;
 4 import java.util.Map;
 5 
 6 import com.hw.entity.Person;
 7 
 8 public interface PersonService {
 9     public int getCount();// 统计总记录
10 
11     public void add(Person per);// 添加
12 
13     public void updatePerson(Person per);// 修改
14 
15     public void del(int id);// 删除
16 
17     public void delSelectAll(String id[]);// 批量删除
18 
19     public Person getPerson(int id);// 根据id查询用户
20 
21     public List<Person> list(Map<String, Object> map);// 查询有分页
22 
23     public List<Person> listLike(Map<String, Object> map);// 模糊查询有分页
24 
25     public int getLikeCount(Map<String, Object> map);// 统计模糊查询总记录
26 
27     public List<Person> listAll();// 查询所有有
28 }
PersonService.java

  (3)UserService.java中的代码:

 1 package com.hw.service;
 2 
 3 import java.util.Map;
 4 
 5 import com.hw.entity.User;
 6 
 7 public interface UserService {
 8     void add(User user);// 用户注册
 9 
10     boolean login(Map<String, Object> map);// 用户登录
11 }
UserService.java

 

b) com.hw.service.impl

  (1)DeptServiceImpl.java中的代码:

 1 package com.hw.service.impl;
 2 
 3 import java.util.List;
 4 
 5 import org.springframework.beans.factory.annotation.Autowired;
 6 import org.springframework.stereotype.Service;
 7 import org.springframework.transaction.annotation.Transactional;
 8 
 9 import com.hw.entity.Dept;
10 import com.hw.mapper.DeptDao;
11 import com.hw.service.DeptService;
12 
13 @Service
14 @Transactional
15 public class DeptServiceImpl implements DeptService {
16     @Autowired
17     private DeptDao db;
18 
19     public void add(Dept dept) {
20         db.add(dept);
21     }
22 
23     public List<Dept> list() {
24         return db.list();
25     }
26 
27 }
DeptServiceImpl.java

 (2)PersonServiceImpl.java中的代码:

 1 package com.hw.service.impl;
 2 
 3 import java.util.List;
 4 import java.util.Map;
 5 
 6 import org.springframework.beans.factory.annotation.Autowired;
 7 import org.springframework.stereotype.Service;
 8 import org.springframework.transaction.annotation.Transactional;
 9 
10 import com.hw.entity.Person;
11 import com.hw.mapper.PersonDao;
12 import com.hw.service.PersonService;
13 
14 @Service
15 @Transactional
16 public class PersonServiceImpl implements PersonService {
17     @Autowired
18     private PersonDao ds;
19 
20     public int getCount() {
21         return ds.getCount();
22     }
23 
24     public void add(Person per) {
25         ds.add(per);
26     }
27 
28     public void updatePerson(Person per) {
29         ds.updatePerson(per);
30     }
31 
32     public void del(int id) {
33         ds.del(id);
34 
35     }
36 
37     public void delSelectAll(String id[]) {
38         ds.delSelectAll(id);
39     }
40 
41     public List<Person> list(Map<String, Object> map) {
42         return ds.list(map);
43     }
44 
45     public Person getPerson(int id) {
46         // TODO Auto-generated method stub
47         return ds.getPerson(id);
48     }
49 
50     public List<Person> listLike(Map<String, Object> map) {
51         // TODO Auto-generated method stub
52         return ds.listLike(map);
53     }
54 
55     public int getLikeCount(Map<String, Object> map) {
56         // TODO Auto-generated method stub
57         return ds.getLikeCount(map);
58     }
59 
60     public List<Person> listAll() {
61         // TODO Auto-generated method stub
62         return ds.listAll();
63     }
64 
65 }
PersonServiceImpl.java

 (3)UserServiceImpl.java中的代码:

 1 package com.hw.service.impl;
 2 
 3 import java.util.Map;
 4 
 5 import org.springframework.beans.factory.annotation.Autowired;
 6 import org.springframework.stereotype.Service;
 7 import org.springframework.transaction.annotation.Transactional;
 8 
 9 import com.hw.entity.User;
10 import com.hw.mapper.UserDao;
11 import com.hw.service.UserService;
12 
13 @Service
14 @Transactional
15 public class UserServiceImpl implements UserService {
16     @Autowired
17     private UserDao dao;
18 
19     public void add(User user) {
20         dao.add(user);
21     }
22 
23     public boolean login(Map<String, Object> map) {
24         return dao.login(map);
25     }
26 
27 }
UserServiceImpl.java

 

  

 

 10、com.hw.utils

1) ExportExcel.java中的代码:

  1 package com.hw.utils;
  2 
  3 import java.io.OutputStream;
  4 import java.util.ArrayList;
  5 import java.util.List;
  6 
  7 import javax.servlet.http.HttpServletResponse;
  8 
  9 import org.apache.poi.hssf.usermodel.HSSFCell;
 10 import org.apache.poi.hssf.usermodel.HSSFCellStyle;
 11 import org.apache.poi.hssf.usermodel.HSSFFont;
 12 import org.apache.poi.hssf.usermodel.HSSFRichTextString;
 13 import org.apache.poi.hssf.usermodel.HSSFRow;
 14 import org.apache.poi.hssf.usermodel.HSSFSheet;
 15 import org.apache.poi.hssf.usermodel.HSSFWorkbook;
 16 import org.apache.poi.hssf.util.HSSFColor;
 17 import org.apache.poi.ss.util.CellRangeAddress;
 18 
 19 /**
 20  * 导出Excel公共方法
 21  */
 22 public class ExportExcel {
 23 
 24     // 显示的导出表的标题
 25     private String title;
 26     // 导出表的列名
 27     private String[] rowName;
 28 
 29     private List<Object[]> dataList = new ArrayList<Object[]>();
 30 
 31     HttpServletResponse response;
 32 
 33     // 构造方法,传入要导出的数据
 34     public ExportExcel(String title, String[] rowName, List<Object[]> dataList) {
 35         this.dataList = dataList;
 36         this.rowName = rowName;
 37         this.title = title;
 38     }
 39 
 40     /*
 41      * 导出数据
 42      */
 43     public void export(OutputStream out) throws Exception {
 44         try {
 45             HSSFWorkbook workbook = new HSSFWorkbook(); // 创建工作簿对象
 46             HSSFSheet sheet = workbook.createSheet(title); // 创建工作表
 47 
 48             // 产生表格标题行
 49             HSSFRow rowm = sheet.createRow(0);
 50             HSSFCell cellTiltle = rowm.createCell(0);
 51 
 52             // sheet样式定义【getColumnTopStyle()/getStyle()均为自定义方法 - 在下面 - 可扩展】
 53             HSSFCellStyle columnTopStyle = this.getColumnTopStyle(workbook);// 获取列头样式对象
 54             HSSFCellStyle style = this.getStyle(workbook); // 单元格样式对象
 55 
 56             sheet.addMergedRegion(new CellRangeAddress(0, 1, 0,
 57                     (rowName.length - 1)));
 58             cellTiltle.setCellStyle(columnTopStyle);
 59             cellTiltle.setCellValue(title);
 60 
 61             // 定义所需列数
 62             int columnNum = rowName.length;
 63             HSSFRow rowRowName = sheet.createRow(2); // 在索引2的位置创建行(最顶端的行开始的第二行)
 64 
 65             // 将列头设置到sheet的单元格中
 66             for (int n = 0; n < columnNum; n++) {
 67                 HSSFCell cellRowName = rowRowName.createCell(n); // 创建列头对应个数的单元格
 68                 cellRowName.setCellType(HSSFCell.CELL_TYPE_STRING); // 设置列头单元格的数据类型
 69                 HSSFRichTextString text = new HSSFRichTextString(rowName[n]);
 70                 cellRowName.setCellValue(text); // 设置列头单元格的值
 71                 cellRowName.setCellStyle(columnTopStyle); // 设置列头单元格样式
 72             }
 73 
 74             // 将查询出的数据设置到sheet对应的单元格中
 75             for (int i = 0; i < dataList.size(); i++) {
 76 
 77                 Object[] obj = dataList.get(i);// 遍历每个对象
 78                 HSSFRow row = sheet.createRow(i + 3);// 创建所需的行数
 79 
 80                 for (int j = 0; j < obj.length; j++) {
 81                     HSSFCell cell = null; // 设置单元格的数据类型
 82                     if (j == 0) {
 83                         cell = row.createCell(j, HSSFCell.CELL_TYPE_NUMERIC);
 84                         cell.setCellValue(i + 1);
 85                     } else {
 86                         cell = row.createCell(j, HSSFCell.CELL_TYPE_STRING);
 87                         if (!"".equals(obj[j]) && obj[j] != null) {
 88                             cell.setCellValue(obj[j].toString()); // 设置单元格的值
 89                         }
 90                     }
 91                     cell.setCellStyle(style); // 设置单元格样式
 92                 }
 93             }
 94             // 让列宽随着导出的列长自动适应
 95             for (int colNum = 0; colNum < columnNum; colNum++) {
 96                 int columnWidth = sheet.getColumnWidth(colNum) / 256;
 97                 for (int rowNum = 0; rowNum < sheet.getLastRowNum(); rowNum++) {
 98                     HSSFRow currentRow;
 99                     // 当前行未被使用过
100                     if (sheet.getRow(rowNum) == null) {
101                         currentRow = sheet.createRow(rowNum);
102                     } else {
103                         currentRow = sheet.getRow(rowNum);
104                     }
105                     if (currentRow.getCell(colNum) != null) {
106                         HSSFCell currentCell = currentRow.getCell(colNum);
107                         if (currentCell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
108                             int length = currentCell.getStringCellValue()
109                                     .getBytes().length;
110                             if (columnWidth < length) {
111                                 columnWidth = length;
112                             }
113                         }
114                     }
115                 }
116                 if (colNum == 0) {
117                     sheet.setColumnWidth(colNum, (columnWidth - 2) * 256);
118                 } else {
119                     sheet.setColumnWidth(colNum, (columnWidth + 4) * 256);
120                 }
121             }
122             workbook.write(out);
123         } catch (Exception e) {
124             e.printStackTrace();
125         }
126 
127     }
128 
129     /*
130      * 列头单元格样式
131      */
132     public HSSFCellStyle getColumnTopStyle(HSSFWorkbook workbook) {
133 
134         // 设置字体
135         HSSFFont font = workbook.createFont();
136         // 设置字体大小
137         font.setFontHeightInPoints((short) 11);
138         // 字体加粗
139         font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
140         // 设置字体名字
141         font.setFontName("Courier New");
142         // 设置样式;
143         HSSFCellStyle style = workbook.createCellStyle();
144         // 设置底边框;
145         style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
146         // 设置底边框颜色;
147         style.setBottomBorderColor(HSSFColor.BLACK.index);
148         // 设置左边框;
149         style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
150         // 设置左边框颜色;
151         style.setLeftBorderColor(HSSFColor.BLACK.index);
152         // 设置右边框;
153         style.setBorderRight(HSSFCellStyle.BORDER_THIN);
154         // 设置右边框颜色;
155         style.setRightBorderColor(HSSFColor.BLACK.index);
156         // 设置顶边框;
157         style.setBorderTop(HSSFCellStyle.BORDER_THIN);
158         // 设置顶边框颜色;
159         style.setTopBorderColor(HSSFColor.BLACK.index);
160         // 在样式用应用设置的字体;
161         style.setFont(font);
162         // 设置自动换行;
163         style.setWrapText(false);
164         // 设置水平对齐的样式为居中对齐;
165         style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
166         // 设置垂直对齐的样式为居中对齐;
167         style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
168          style.setBorderBottom(HSSFCellStyle.BORDER_DOTTED);//下边框        
169          style.setBorderLeft(HSSFCellStyle.BORDER_DOTTED);//左边框        
170          style.setBorderRight(HSSFCellStyle.BORDER_THIN);//右边框        
171          style.setBorderTop(HSSFCellStyle.BORDER_THIN);//上边框    
172          style.setFillForegroundColor(HSSFColor.LIME.index);     
173          style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);     
174         return style;
175 
176     }
177 
178     /*
179      * 列数据信息单元格样式
180      */
181     public HSSFCellStyle getStyle(HSSFWorkbook workbook) {
182         // 设置字体
183         HSSFFont font = workbook.createFont();
184         // 设置字体大小
185         // font.setFontHeightInPoints((short)10);
186         // 字体加粗
187         // font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
188         // 设置字体名字
189         font.setFontName("Courier New");
190         // 设置样式;
191         HSSFCellStyle style = workbook.createCellStyle();
192         // 设置底边框;
193         style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
194         // 设置底边框颜色;
195         style.setBottomBorderColor(HSSFColor.BLACK.index);
196         // 设置左边框;
197         style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
198         // 设置左边框颜色;
199         style.setLeftBorderColor(HSSFColor.BLACK.index);
200         // 设置右边框;
201         style.setBorderRight(HSSFCellStyle.BORDER_THIN);
202         // 设置右边框颜色;
203         style.setRightBorderColor(HSSFColor.BLACK.index);
204         // 设置顶边框;
205         style.setBorderTop(HSSFCellStyle.BORDER_THIN);
206         // 设置顶边框颜色;
207         style.setTopBorderColor(HSSFColor.BLACK.index);
208         // 在样式用应用设置的字体;
209         style.setFont(font);
210         // 设置自动换行;
211         style.setWrapText(false);
212         // 设置水平对齐的样式为居中对齐;
213         style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
214         // 设置垂直对齐的样式为居中对齐;
215         style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
216          style.setFillForegroundColor(HSSFColor.LIME.index);     
217          style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);     
218          font.setColor(HSSFColor.BLUE.index);     
219          style.setFont(font);     
220         return style;
221 
222     }
223 }
ExportExcel.java

2) FileDownLoad.java中的代码:

 1 package com.hw.utils;
 2 
 3 
 4 import java.io.BufferedInputStream;
 5 import java.io.BufferedOutputStream;
 6 import java.io.File;
 7 import java.io.FileInputStream;
 8 import java.io.FileNotFoundException;
 9 import java.io.IOException;
10 import java.io.InputStream;
11 import java.io.OutputStream;
12 import java.net.URLEncoder;
13 
14 import javax.servlet.http.HttpServletRequest;
15 import javax.servlet.http.HttpServletResponse;
16 
17 public class FileDownLoad {
18 
19     public static String download(String filepath,HttpServletRequest request, HttpServletResponse response) throws Exception{
20         
21         BufferedInputStream bis = null;
22         BufferedOutputStream bos = null;
23         OutputStream fos = null;
24         InputStream fis = null;
25 
26         try {
27         // 如果是从服务器上取就用这个获得系统的绝对路径方法。
28         //String filepath = request.getRealPath(filepatha);//方法过时了
29         String filepathall = request.getSession().getServletContext().getRealPath(filepath);
30 
31         File uploadFile = new File(filepathall);
32 
33         fis = new FileInputStream(uploadFile);
34         bis = new BufferedInputStream(fis);
35         fos = response.getOutputStream();
36         bos = new BufferedOutputStream(fos);
37         
38         //得到文件名
39         String filename = filepath.substring(filepath.lastIndexOf("\\")+1);
40 
41         // 这个就就是弹出下载对话框的关键代码
42         response.setHeader("Content-disposition", "attachment;filename="+ URLEncoder.encode(filename, "utf-8"));
43         
44         int bytesRead = 0;
45         // 用输出流去写,缓冲输入输出流
46         byte[] buffer = new byte[8192];
47         while ((bytesRead = bis.read(buffer, 0, 8192)) != -1) {
48         bos.write(buffer, 0, bytesRead);
49         }
50 
51         } catch (FileNotFoundException e) {
52         e.printStackTrace();
53         } catch (IOException e) {
54         e.printStackTrace();
55         } catch (NumberFormatException e) {
56         e.printStackTrace();
57         } finally {
58         try {
59         if (bos != null) {
60         bos.flush();
61         }
62         if (fis != null) {
63         fis.close();
64         }
65         if (bis != null) {
66         bis.close();
67         }
68         if (fos != null) {
69         fos.close();
70         }
71         if (bos != null) {
72         bos.close();
73         }
74         } catch (IOException e) {
75         e.printStackTrace();
76         }
77         }
78         return null;
79     }
80 }
FileDownLoad.java

3)MD5Utils.java中的代码:

 1 package com.hw.utils;
 2 
 3 import java.security.MessageDigest;
 4 import java.security.NoSuchAlgorithmException;
 5 
 6 public class MD5Utils {
 7 
 8     public static String MD5Src(String src){//加密
 9         char[] chars = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
10         StringBuilder sb = new StringBuilder();
11         // 定义数据源,将数据源转换成字节数组
12         byte[] bytes = src.getBytes();
13         // 获取摘要
14         try {
15             MessageDigest digest = MessageDigest.getInstance("md5");
16             // 对字节数组进行加密运算,得到新的字节数组
17             byte[] bytes1 = digest.digest(bytes);
18             
19             for (byte b : bytes1) {
20                 sb.append(chars[b&0x0f]);
21                 sb.append(chars[(b>>4)&0x0f]);
22             }
23         } catch (NoSuchAlgorithmException e) {
24             e.printStackTrace();
25         }
26         return sb.toString();
27     }
28      public static String convertMD5(String inStr){  //解密前提是只能密码,所以作用不大
29           
30             char[] a = inStr.toCharArray();  
31             for (int i = 0; i < a.length; i++){  
32                 a[i] = (char) (a[i] ^ 'q');  
33             }  
34             String s = new String(a);  
35             return s;  
36       
37         }  
38     public static void main(String[] args) {
39         System.out.println(MD5Utils.MD5Src("qw2"));
40         System.out.println("qw2".equals(MD5Utils.MD5Src("qw2")));
41         //b3dac247c7363d6f9cfd358957875cd8
42          System.out.println("qw".equals(convertMD5(convertMD5("qw"))));
43     }
44 }
MD5Utils.java

4)PageUtils.java中的代码:

  1 package com.hw.utils;
  2 
  3 import java.util.HashMap;
  4 import java.util.List;
  5 import java.util.Map;
  6 import java.util.Set;
  7 
  8 import javax.servlet.http.HttpServletRequest;
  9 
 10 public class PageUtils {
 11 
 12     /**
 13      * 
 14      *@author Anon
 15      *
 16      *@param request request对象,用于传入属性
 17      *@param pageNo 当前的页数
 18      *@param pageSize 每页设定的行数
 19      *@param source 存放了相应数据的集合
 20      *@param dataCount 数据库中共存在多少条数据
 21      *
 22      * <br/>
 23      * <br/>
 24      * <br/><b>note:</b> 该方法只是将jsp中的页面代码进行简化,jsp页面中使用如下el表达式可取出相应的模块
 25      * <br/><b>${list}:</b> 数据列表
 26      * <br/><b>${first}:</b> 首页 超链接
 27      * <br/><b>${prev}:</b> 上一页 超链接
 28      * <br/><b>${next}:</b> 下一页 超链接
 29      * <br/><b>${End}:</b> 尾页 超链接
 30      * <br/><b>${pageNo}:</b> 当前页数
 31      * <br/><b>${pageCount}:</b> 总页数
 32      * <br/><b>${dataInfo}:</b> 共有?条信息提示
 33      * <br/><b>${pageInfo}:</b> 当前处于?/?页信息提示
 34      * <br/><b>${group}:</b> 以上六条组合
 35      * 
 36      * <br/>
 37      * <br/>
 38      * <b>note:</b> 因耦合性问题,使用该方法进行简化分页代码时,必须遵循以下命名规范
 39      * <br/><b>method:</b> 在JSP中进行功能定义时必须有method参数作为接受和传输功能选择的标识。
 40      * <br/><b>list:</b> 在JSP页面取出列表数据时必须使用${list},并且在调用列表功能时必须以list作为标识。
 41      * <br/><b>pageSize:</b> 取出每页的数据条数
 42      * <br/><b>pageNo:</b> 必须在JSP中使用pageNo作为分页的页码选择标识
 43      * <br/>
 44      * <br/><b>example-> student.do?method=list&pageNo=1;</b>
 45      * <br/>
 46      * <br/>
 47      * <br/>可在struts2框架下使用
 48      * <br/>
 49      * <br/>模糊查询时查询字段可以是以query开头的任意词组,可以有任意个查询字段,取出该字段值时使用之前设置的query开头的任意词组作为标识
 50      **/
 51 
 52     @SuppressWarnings("unchecked")
 53     public static void page(HttpServletRequest request,Integer currentPage,Integer pageSize,List<?> source,Integer dataCount){
 54 
 55 
 56         String url = request.getRequestURI();
 57 
 58         HashMap<String, String> queryMap = new HashMap<String, String>();
 59         Map parameterMap = request.getParameterMap();
 60         Set keySet = parameterMap.keySet();
 61         for (Object object : keySet) {
 62             String parameterName = object.toString();
 63             String queryValue = request.getParameterValues(parameterName)[0];
 64             //System.out.println(queryValue);
 65             if(parameterName.startsWith("query")&&queryValue!=null&&!queryValue.equals("")){
 66                 queryMap.put(parameterName,queryValue);
 67             }
 68             
 69         }
 70         String queryStr = "";
 71         Set<String> queryNames = queryMap.keySet();
 72         for (String queryName : queryNames) {
 73             queryStr +=("&"+queryName+"="+queryMap.get(queryName));
 74             
 75         }
 76         //System.out.println(queryStr);
 77         
 78         boolean flag = false;
 79         if(url.contains("!")){
 80             flag = true;
 81         }
 82         int pageCount = dataCount/pageSize + (dataCount%pageSize==0?0:1);
 83 
 84         String first = "<a href='"+url+"?"+(flag?"":"method=list&")+"currentPage=1"+queryStr+"'> 首页   </a>";
 85         String prev = "<a href='"+url+"?"+(flag?"":"method=list&")+"currentPage=1"+queryStr+"'> 上一页  </a>";
 86         String next = "<a href='"+url+"?"+(flag?"":"method=list&")+"currentPage="+pageCount+queryStr+"'> 下一页  </a>";
 87         String End = "<a href='"+url+"?"+(flag?"":"method=list&")+"currentPage="+pageCount+queryStr+"'> 尾页  </a>";
 88         String dataInfo = "<span>共有"+dataCount+"条数据        </span>";
 89         String pageInfo = "<span>   当前处于第"+currentPage+"/"+pageCount+"页</span>";
 90 
 91         if(currentPage>1){
 92 
 93             prev="<a href='"+url+"?"+(flag?"":"method=list&")+"currentPage="+(currentPage-1)+queryStr+"'> 上一页  </a>";
 94         }
 95 
 96         if(currentPage<pageCount){
 97 
 98             next = "<a href='"+url+"?"+(flag?"":"method=list&")+"currentPage="+(currentPage+1)+queryStr+"'> 下一页  </a>";
 99         }
100         request.setAttribute("pageCount", pageCount);
101         request.setAttribute("currentPage", currentPage.toString());
102         for (String string : queryNames) {
103             request.setAttribute(string, queryMap.get(string));
104         }
105         request.setAttribute("pageSize", pageSize);
106         request.setAttribute("list",source);
107         request.setAttribute("first", first);
108         request.setAttribute("prev", prev);
109         request.setAttribute("next", next);
110         request.setAttribute("End", End);
111         request.setAttribute("dataInfo", dataInfo);
112         request.setAttribute("pageInfo", pageInfo);
113         request.setAttribute("group", dataInfo+""+first+""+prev+""+next+""+End+""+pageInfo);
114     }
115 
116 }
PageUtils.java

 

代码链接:http://pan.baidu.com/s/1hsqmGpI

END!!!

 

posted @ 2017-03-14 18:11  壹毫米的距离  阅读(228)  评论(0编辑  收藏  举报