利用 SQL 语句中的 limit 实现分页。
<select id="findByPage" parameterType="Map" resultMap="BaseResultMap">
select
id, userName, password, email, phone, roleName
from tb_user
<if test="start!=null and size!=null">
limit #{start},#{size}
if>
select>
Eclipse版本 Neon.1a Release (4.6.1)
apache-maven-3.3.9
数据库 MySQL5.7.12
maven 配置的中央仓库阿里云地址
setting.xml
.
.
<mirrors>
<mirror>
<id>alimavenid>
<name>aliyun mavenname>
<url>http://maven.aliyun.com/nexus/content/groups/public/url>
<mirrorOf>centralmirrorOf>
mirror>
mirrors>
.
.
如何创建 maven web工程:http://blog.csdn.net/peng_hong_fu/article/details/53584104
源代码下载
pom.xml
spring版本号 4.3.3.RELEASE
mybatis版本号 3.4.0
最新的版本 maven 中央仓库还没更新
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0modelVersion>
<groupId>com.testgroupId>
<artifactId>TestMaven4artifactId>
<packaging>warpackaging>
<version>0.0.1-SNAPSHOTversion>
<name>TestMaven4 Maven Webappname>
<url>http://maven.apache.orgurl>
<properties>
<spring.version>4.3.3.RELEASEspring.version>
<mybatis.version>3.4.0mybatis.version>
<slf4j.version>1.7.7slf4j.version>
<log4j.version>1.2.17log4j.version>
properties>
<dependencies>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.12version>
<scope>testscope>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-coreartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-oxmartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-txartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-jdbcartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-aopartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-context-supportartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-testartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>${mybatis.version}version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatis-springartifactId>
<version>1.3.0version>
dependency>
<dependency>
<groupId>javaxgroupId>
<artifactId>javaee-apiartifactId>
<version>7.0version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.25version>
dependency>
<dependency>
<groupId>commons-dbcpgroupId>
<artifactId>commons-dbcpartifactId>
<version>1.2.2version>
dependency>
<dependency>
<groupId>jstlgroupId>
<artifactId>jstlartifactId>
<version>1.2version>
dependency>
<dependency>
<groupId>log4jgroupId>
<artifactId>log4jartifactId>
<version>${log4j.version}version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>fastjsonartifactId>
<version>1.1.41version>
dependency>
<dependency>
<groupId>org.slf4jgroupId>
<artifactId>slf4j-apiartifactId>
<version>${slf4j.version}version>
dependency>
<dependency>
<groupId>org.slf4jgroupId>
<artifactId>slf4j-log4j12artifactId>
<version>${slf4j.version}version>
dependency>
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-databindartifactId>
<version>2.7.5version>
dependency>
<dependency>
<groupId>commons-fileuploadgroupId>
<artifactId>commons-fileuploadartifactId>
<version>1.3.1version>
dependency>
<dependency>
<groupId>commons-iogroupId>
<artifactId>commons-ioartifactId>
<version>2.4version>
dependency>
<dependency>
<groupId>commons-codecgroupId>
<artifactId>commons-codecartifactId>
<version>1.9version>
dependency>
<dependency>
<groupId>aspectjgroupId>
<artifactId>aspectjweaverartifactId>
<version>1.5.4version>
dependency>
dependencies>
<build>
<finalName>SSM-ProjectfinalName>
<plugins>
<plugin>
<groupId>org.apache.maven.pluginsgroupId>
<artifactId>maven-compiler-pluginartifactId>
<configuration>
<source>1.8source>
<target>1.8target>
configuration>
plugin>
plugins>
build>
project>
web.xml
web.xml
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<filter>
<filter-name>encodingFilterfilter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
<async-supported>trueasync-supported>
<init-param>
<param-name>encodingparam-name>
<param-value>UTF-8param-value>
init-param>
filter>
<filter-mapping>
<filter-name>encodingFilterfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
<context-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:applicationContext.xmlparam-value>
context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
listener>
<servlet>
<servlet-name>springDispatcherServletservlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
<init-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:springmvc.xmlparam-value>
init-param>
<load-on-startup>1load-on-startup>
servlet>
<servlet-mapping>
<servlet-name>springDispatcherServletservlet-name>
<url-pattern>/url-pattern>
servlet-mapping>
web-app>
建表语句和部分数据
DROP TABLE IF EXISTS tb_user;
CREATE TABLE tb_user (
id INT NOT NULL AUTO_INCREMENT,
userName VARCHAR(40),
password VARCHAR(100),
email VARCHAR(40),
phone VARCHAR(40),
roleName VARCHAR(40),
PRIMARY KEY(id)
)ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
-----------------------------------------
mysql> use db_ssm2;
Database changed
mysql> desc tb_user;
+----------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| userName | varchar(40) | YES | | NULL | |
| password | varchar(100) | YES | | NULL | |
| email | varchar(40) | YES | | NULL | |
| phone | varchar(40) | YES | | NULL | |
| roleName | varchar(40) | YES | | NULL | |
+----------+--------------+------+-----+---------+----------------+
6 rows in set (0.03 sec)
mysql> select *from tb_user;
+----+----------+----------+--------------------+-------+------------+
| id | userName | password | email | phone | roleName |
+----+----------+----------+--------------------+-------+------------+
| 1 | 李白 | 1234 | [email protected] | 10086 | 客户经理 |
| 2 | 李清照 | 1234 | [email protected] | 10087 | 高管 |
| 3 | 杜甫 | 1234 | [email protected] | 10088 | 销售主管 |
| 4 | 岑参 | 1234 | [email protected] | 10088 | 系统管理员 |
| 5 | 陈子昂 | 1234 | [email protected] | 10099 | 高管 |
+----+----------+----------+--------------------+-------+------------+
5 rows in set (0.05 sec)
jdbc.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/db_ssm2
username=root
password=root
initialSize=0
maxActive=20
maxIdle=20
minIdle=1
maxWait=60000
log4j.properties
log4j.rootLogger=INFO,Console,File
#\u5B9A\u4E49\u65E5\u5FD7\u8F93\u51FA\u76EE\u7684\u5730\u4E3A\u63A7\u5236\u53F0
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.Target=System.out
#\u53EF\u4EE5\u7075\u6D3B\u5730\u6307\u5B9A\u65E5\u5FD7\u8F93\u51FA\u683C\u5F0F\uFF0C\u4E0B\u9762\u4E00\u884C\u662F\u6307\u5B9A\u5177\u4F53\u7684\u683C\u5F0F
log4j.appender.Console.layout = org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=[%c] - %m%n
#\u6587\u4EF6\u5927\u5C0F\u5230\u8FBE\u6307\u5B9A\u5C3A\u5BF8\u7684\u65F6\u5019\u4EA7\u751F\u4E00\u4E2A\u65B0\u7684\u6587\u4EF6
log4j.appender.File = org.apache.log4j.RollingFileAppender
#\u6307\u5B9A\u8F93\u51FA\u76EE\u5F55
log4j.appender.File.File = logs/ssm.log
#\u5B9A\u4E49\u6587\u4EF6\u6700\u5927\u5927\u5C0F
log4j.appender.File.MaxFileSize = 10MB
# \u8F93\u51FA\u6240\u4EE5\u65E5\u5FD7\uFF0C\u5982\u679C\u6362\u6210DEBUG\u8868\u793A\u8F93\u51FADEBUG\u4EE5\u4E0A\u7EA7\u522B\u65E5\u5FD7
log4j.appender.File.Threshold = ALL
log4j.appender.File.layout = org.apache.log4j.PatternLayout
log4j.appender.File.layout.ConversionPattern =[%p] [%d{yyyy-MM-dd HH\:mm\:ss}][%c]%m%n
applicationContext.xml
<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:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
<context:component-scan base-package="com.ssmtest">
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Controller"/>
context:component-scan>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://127.0.0.1:3306/db_ssm2"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource">property>
<property name="mapperLocations" value="classpath:com/ssmtest/mappers/*.xml">property>
bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.ssmtest.dao">property>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory">property>
bean>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource">property>
bean>
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="insert*" propagation="REQUIRED"/>
<tx:method name="update*" propagation="REQUIRED" />
<tx:method name="edit*" propagation="REQUIRED" />
<tx:method name="save*" propagation="REQUIRED" />
<tx:method name="add*" propagation="REQUIRED" />
<tx:method name="new*" propagation="REQUIRED" />
<tx:method name="set*" propagation="REQUIRED" />
<tx:method name="remove*" propagation="REQUIRED" />
<tx:method name="delete*" propagation="REQUIRED" />
<tx:method name="change*" propagation="REQUIRED" />
<tx:method name="check*" propagation="REQUIRED" />
<tx:method name="get*" propagation="REQUIRED" read-only="true" />
<tx:method name="find*" propagation="REQUIRED" read-only="true" />
<tx:method name="load*" propagation="REQUIRED" read-only="true" />
<tx:method name="*" propagation="REQUIRED" read-only="true" />
tx:attributes>
tx:advice>
<aop:config>
<aop:pointcut id="serviceOperation" expression="execution(* com.ssmtest.service.*.*(..))" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="serviceOperation"/>
aop:config>
beans>
你也可以使用事务注解
,service层就要使用 @Transactional 注解
springmvc.xml
<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:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
<context:component-scan base-package="com.ssmtest.controller">context:component-scan>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="WEB-INF/views/">property>
<property name="suffix" value=".jsp">property>
bean>
<mvc:default-servlet-handler/>
<mvc:annotation-driven>mvc:annotation-driven>
beans>
可以考虑使用
MyBatis Generator
自动创建数据表相关代码
该工具可根据MySQL中的表(这里是tb_user)自动创建实体类、MyBatis映射文件以及Dao接口
参考教程:http://blog.csdn.net/zhshulin/article/details/23912615
User
和PageBean
User.java
package com.ssmtest.entity;
/**
* 用户实体类
* 对应数据表tb_user
* @author Peng
* @Date2016年12月13日上午9:36:23
*/
public class User {
private Integer id;
private String username;
private String password;
private String email;
private String phone;
private String rolename;
//角色名称 系统管理员、销售主管、客户经理、高管
public Integer getId() {
return id;
}
public User() {
super();
}
public User(String username, String password, String email, String phone, String rolename) {
super();
this.username = username;
this.password = password;
this.email = email;
this.phone = phone;
this.rolename = rolename;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username == null ? null : username.trim();
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password == null ? null : password.trim();
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email == null ? null : email.trim();
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone == null ? null : phone.trim();
}
public String getRolename() {
return rolename;
}
public void setRolename(String rolename) {
this.rolename = rolename == null ? null : rolename.trim();
}
@Override
public String toString() {
return "User [id=" + id + ", username=" + username + ", password=" + password + ", email=" + email + ", phone="
+ phone + ", rolename=" + rolename + "]";
}
}
PageBean.java
package com.ssmtest.entity;
import java.util.List;
/**
* 分页实体类
* @author Peng
* @Date2016年12月13日 上午9:40:10
*/
public class PageBean {
private int currPage;//当前页数
private int pageSize;//每页显示的记录数
private int totalCount;//总记录数
private int totalPage;//总页数
private List lists;//每页的显示的数据
public PageBean() {
super();
}
public int getCurrPage() {
return currPage;
}
public void setCurrPage(int currPage) {
this.currPage = currPage;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public int getTotalCount() {
return totalCount;
}
public void setTotalCount(int totalCount) {
this.totalCount = totalCount;
}
public int getTotalPage() {
return totalPage;
}
public void setTotalPage(int totalPage) {
this.totalPage = totalPage;
}
public List getLists() {
return lists;
}
public void setLists(List lists) {
this.lists = lists;
}
}
UserMapper.xml
<mapper namespace="com.ssmtest.dao.UserDao">
<resultMap id="BaseResultMap" type="com.ssmtest.entity.User">
<id column="id" property="id" jdbcType="INTEGER" />
<result column="userName" property="username" jdbcType="VARCHAR" />
<result column="password" property="password" jdbcType="VARCHAR" />
<result column="email" property="email" jdbcType="VARCHAR" />
<result column="phone" property="phone" jdbcType="VARCHAR" />
<result column="roleName" property="rolename" jdbcType="VARCHAR" />
resultMap>
<sql id="Base_Column_List">
id, userName, password, email, phone, roleName
sql>
<select id="selectByPrimaryKey" resultMap="BaseResultMap"
parameterType="java.lang.Integer">
select
<include refid="Base_Column_List" />
from tb_user
where id = #{id,jdbcType=INTEGER}
select>
<select id="loginByUserNameAndPassword" resultMap="BaseResultMap" parameterType="com.ssmtest.entity.User">
select
<include refid="Base_Column_List" />
from tb_user
where
userName = #{username}
and password = #{password}
select>
<select id="findByPage" parameterType="Map" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from tb_user
<if test="start!=null and size!=null">
limit #{start},#{size}
if>
select>
<select id="selectUserList" resultType="com.ssmtest.entity.User">
select
<include refid="Base_Column_List" />
from tb_user
select>
<select id="selectCount" resultType="int">
select count(*) from tb_user
select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
delete from tb_user
where id = #{id,jdbcType=INTEGER}
delete>
<insert id="insert" parameterType="com.ssmtest.entity.User">
insert into tb_user (id, userName, password,
email, phone, roleName
)
values (#{id,jdbcType=INTEGER}, #{username,jdbcType=VARCHAR},
#{password,jdbcType=VARCHAR},
#{email,jdbcType=VARCHAR}, #{phone,jdbcType=VARCHAR}, #{rolename,jdbcType=VARCHAR}
)
insert>
<insert id="insertSelective" parameterType="com.ssmtest.entity.User">
insert into tb_user
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="id != null">
id,
if>
<if test="username != null">
userName,
if>
<if test="password != null">
password,
if>
<if test="email != null">
email,
if>
<if test="phone != null">
phone,
if>
<if test="rolename != null">
roleName,
if>
trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="id != null">
#{id,jdbcType=INTEGER},
if>
<if test="username != null">
#{username,jdbcType=VARCHAR},
if>
<if test="password != null">
#{password,jdbcType=VARCHAR},
if>
<if test="email != null">
#{email,jdbcType=VARCHAR},
if>
<if test="phone != null">
#{phone,jdbcType=VARCHAR},
if>
<if test="rolename != null">
#{rolename,jdbcType=VARCHAR},
if>
trim>
insert>
<update id="updateByPrimaryKeySelective" parameterType="com.ssmtest.entity.User">
update tb_user
<set>
<if test="username != null">
userName = #{username,jdbcType=VARCHAR},
if>
<if test="password != null">
password = #{password,jdbcType=VARCHAR},
if>
<if test="email != null">
email = #{email,jdbcType=VARCHAR},
if>
<if test="phone != null">
phone = #{phone,jdbcType=VARCHAR},
if>
<if test="rolename != null">
roleName = #{rolename,jdbcType=VARCHAR},
if>
set>
where id = #{id,jdbcType=INTEGER}
update>
<update id="updateByPrimaryKey" parameterType="com.ssmtest.entity.User">
update tb_user
set userName = #{username,jdbcType=VARCHAR},
password = #{password,jdbcType=VARCHAR},
email = #{email,jdbcType=VARCHAR},
phone = #{phone,jdbcType=VARCHAR},
roleName = #{rolename,jdbcType=VARCHAR}
where id = #{id,jdbcType=INTEGER}
update>
mapper>
UserDAO
中的方法名和UserMapper
中SQL语句的方法名相同
service 层可直接调用Dao中的方法,执行SQL语句,实现增删改查方法
UserDao.java
package com.ssmtest.dao;
import java.util.HashMap;
import java.util.List;
import com.ssmtest.entity.User;
public interface UserDao {
/**
* 根据主键删除一条用户数据
* @param id
* @return
*/
int deleteByPrimaryKey(Integer id);
/**
* 插入一条用户数据 ,可以不完整
* @param record
* @return
*/
int insertSelective(User record);
/**
* 根据主键查询一条用户数据
* @param id
* @return
*/
User selectByPrimaryKey(Integer id);
/**
* 用户登录
* @param record
* @return
*/
User loginByUserNameAndPassword(User record);
/**
* 根据主键更新一条用户数据,可以不完整 -
* @param record
* @return
*/
int updateByPrimaryKeySelective(User record);
/**
* 查询所有用户数据
* @return
*/
List selectUserList();
/**
* 查询用户记录总数
* @return
*/
int selectCount();
/**
* 分页操作,调用findByPage limit分页方法
* @param map
* @return
*/
List findByPage(HashMap map);
}
UserService.java
package com.ssmtest.service;
import java.util.List;
import com.ssmtest.entity.PageBean;
import com.ssmtest.entity.User;
/**
* User类业务层接口
* @author Peng
* @Date2016年12月13日上午9:54:40
*/
public interface UserService {
int deleteByPrimaryKey(Integer id);
int insertSelective(User record);
User selectByPrimaryKey(Integer id);
User loginByUserNameAndPassword(User record);
List selectUserList();
int selectCount();
int updateByPrimaryKeySelective(User record);
PageBean findByPage(int currentPage);
}
UserServiceImpl.java
package com.ssmtest.service.impl;
import java.util.HashMap;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.ssmtest.dao.UserDao;
import com.ssmtest.entity.PageBean;
import com.ssmtest.entity.User;
import com.ssmtest.service.UserService;
/**
* User类业务层实现类
* @author Peng
* @Date2016年12月13日上午9:54:56
*/
@Service("userService")
public class UserServiceImpl implements UserService {
@Resource
private UserDao userDao;
@Override
public int deleteByPrimaryKey(Integer id) {
return userDao.deleteByPrimaryKey(id);
}
@Override
public int insertSelective(User record) {
return userDao.insertSelective(record);
}
@Override
public User selectByPrimaryKey(Integer id) {
return userDao.selectByPrimaryKey(id);
}
@Override
public int updateByPrimaryKeySelective(User record) {
return userDao.updateByPrimaryKeySelective(record);
}
@Override
public List selectUserList() {
return userDao.selectUserList();
}
@Override
public int selectCount() {
return userDao.selectCount();
}
@Override
public User loginByUserNameAndPassword(User record) {
return userDao.loginByUserNameAndPassword(record);
}
@Override
public PageBean findByPage(int currentPage) {
HashMap map = new HashMap();
PageBean pageBean = new PageBean();
//封装当前页数
pageBean.setCurrPage(currentPage);
//每页显示的数据
int pageSize=2;
pageBean.setPageSize(pageSize);
//封装总记录数
int totalCount = userDao.selectCount();
pageBean.setTotalCount(totalCount);
//封装总页数
double tc = totalCount;
Double num =Math.ceil(tc/pageSize);//向上取整
pageBean.setTotalPage(num.intValue());
map.put("start",(currentPage-1)*pageSize);
map.put("size", pageBean.getPageSize());
//封装每页显示的数据
List lists = userDao.findByPage(map);
pageBean.setLists(lists);
return pageBean;
}
}
TestMybatis.java
package com.test;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.annotation.Resource;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.ssmtest.entity.User;
import com.ssmtest.service.UserService;
public class TestMybatis {
private ApplicationContext ac = null;
@Resource
private UserService userService = null;
@Before
public void before() {
ac = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
userService = (UserService) ac.getBean("userService");
}
@Test
public void testinsertSelective(){
//User user = new User("李白","1234","[email protected]","10086","销售主管");
//User user = new User("李清照","1234","[email protected]","10087","高管");
//User user = new User("杜甫","1234","[email protected]","10088","客户经理");
//User user = new User("岑参","1234","[email protected]","10089","系统管理员");
User user = new User("温庭筠","1234","[email protected]","10090","销售主管");
userService.insertSelective(user);
}
@Test
public void testselectByPrimaryKey(){
int id = 1;
User user = userService.selectByPrimaryKey(id);
System.out.println(user.toString());
}
@Test
public void testselectUserList(){
List lists = new ArrayList<>();
lists = userService.selectUserList();
Iterator< User> it = lists.iterator();
System.out.println("总记录数:"+userService.selectCount());
while(it.hasNext()){
User user = it.next();
System.out.println(user.toString());
}
}
}
TestMybatis2.java
package com.test;
import javax.annotation.Resource;
import org.apache.log4j.Logger;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.alibaba.fastjson.JSON;
import com.ssmtest.entity.User;
import com.ssmtest.service.UserService;
@RunWith(SpringJUnit4ClassRunner.class) // 表示继承了SpringJUnit4ClassRunner类
@ContextConfiguration(locations = { "classpath:applicationContext.xml" })
/**
* spring测试
*
* @author Peng
* @Date2016年12月13日上午11:52:56
*/
public class TestMyBatis2 {
//TestMyBatis2类定义的日志信息就能够显示出来了
private static Logger logger = Logger.getLogger(TestMyBatis2.class);
@Resource
private UserService userService = null;
@Test
public void testselectByPrimaryKey() {
User user = userService.selectByPrimaryKey(1);
//logger.info("值:" + user.toString());
logger.info(JSON.toJSONString(user));//JSon格式的内容
}
}
package com.ssmtest.controller;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import com.ssmtest.entity.User;
import com.ssmtest.service.UserService;
@SessionAttributes("currentUser")
@Controller
public class UserController {
@Resource
private UserService userService;
/**
* 用户登录
* @param user
* @param request
* @return
* @throws Exception
*/
@RequestMapping("/login")
public String login(@RequestParam("userName")String userName,
@RequestParam("password")String password,Model model) throws Exception{
User user = new User();
user.setUsername(userName);
user.setPassword(password);
User userresult = userService.loginByUserNameAndPassword(user);
if(userresult!=null){
//登录成功
List lists = userService.selectUserList();
model.addAttribute("userLists", lists);//回显用户信息
model.addAttribute("currentUser", userresult.getUsername());
return "redirect:main";
}
return "error";
}
@RequestMapping("/main")
public String main(@RequestParam(value="currentPage",defaultValue="1",required=false)int currentPage,Model model){
model.addAttribute("pagemsg", userService.findByPage(currentPage));//回显分页数据
return "main";
}
/**
* 跳到编辑页面
* @param currentPage
* @param model
* @return
*/
@RequestMapping("/edit")
public String editpage(@RequestParam("id") int id,
Model model){
User user =userService.selectByPrimaryKey(id);
model.addAttribute("returnUser", user);
return "edit";
}
/**
* 保存用户数据
* @return
*/
@RequestMapping("/save")
public String save(User user){
System.out.println(user.toString());
if(user.getId()==null){
//id为null是保存
userService.insertSelective(user);
}else{
//有id值为修改
userService.updateByPrimaryKeySelective(user);
}
return "redirect:main";
}
/**
* 删除用户数据
* @param id
* @return
*/
@RequestMapping("/delete")
public String delete(@RequestParam("id") int id){
userService.deleteByPrimaryKey(id);
return "redirect:main";
}
/**
* 添加一个用户数据
* @return
*/
@RequestMapping("/add")
public String add(Model model){
model.addAttribute("returnUser", new User());
return "edit";
}
}
index.jsp
<%@ page language="java" import="java.util.*" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Index.jsptitle>
<body>
<h2>欢迎登陆h2>
<form action="login" method="post">
用户名:<input type="text" name="userName"/><br>
密 码:<input type="password" name="password"/><br>
<input type="submit" value="登录"/>
form>
body>
html>
mian.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>主页title>
<style type="text/css">
td{text-align: center;}
.td2{text-align: right;}
.table1{
border:1px solid #ddd;
width:900px;
}
thead{
background-color:lightblue;
}
style>
head>
<body>
欢迎你:${currentUser}
<br>
<%-- 当前用户:${pageScope.currentUser}
当前用户:${requestScope.currentUser}-${roleName} 有重定向数据就访问不到
当前用户:${sessionScope.currentUser}-${roleName} 可以使用
--%>
<hr>
<a href="add"> 添加用户a><br>
<c:if test="${empty requestScope.pagemsg}">
没有任何用户信息!
c:if>
<c:if test="${!empty requestScope.pagemsg}">
<table border="1" cellpadding="10" cellspacing="0" class="table1">
<thead>
<tr>
<td>编号td>
<td>用户名td>
<td>密码td>
<td>邮件td>
<td>联系电话td>
<td>职位td>
<td>Edittd>
<td>Deletetd>
tr>
thead>
<c:forEach items="${requestScope.pagemsg.lists}" var="u">
<tr>
<th>${u.id }th>
<th>${u.username }th>
<th>${u.password }th>
<th>${u.email }th>
<th>${u.phone }th>
<th>${u.rolename }th>
<th><a href="edit?id=${u.id}">Edita>th>
<th><a href="delete?id=${u.id}" onclick="return confirm('确定要删除吗')">Deletea>th>
tr>
c:forEach>
table>
c:if>
<table border="0" cellspacing="0" cellpadding="0" width="900px">
<tr>
<td class="td2">
<span>第${requestScope.pagemsg.currPage }/ ${requestScope.pagemsg.totalPage}页span>
<span>总记录数:${requestScope.pagemsg.totalCount } 每页显示:${requestScope.pagemsg.pageSize}span>
<span>
<c:if test="${requestScope.pagemsg.currPage != 1}">
<a href="${pageContext.request.contextPath }/main?currentPage=1">[首页]a>
<a href="${pageContext.request.contextPath }/main?currentPage=${requestScope.pagemsg.currPage-1}">[上一页]a>
c:if>
<c:if test="${requestScope.pagemsg.currPage != requestScope.pagemsg.totalPage}">
<a href="${pageContext.request.contextPath }/main?currentPage=${requestScope.pagemsg.currPage+1}">[下一页]a>
<a href="${pageContext.request.contextPath }/main?currentPage=${requestScope.pagemsg.totalPage}">[尾页]a>
c:if>
span>
td>
tr>
table>
body>
html>
edit.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>编辑页面title>
head>
<body>
欢迎你:${currentUser}
<hr>
<form:form action="save" method="post" modelAttribute="returnUser">
<form:hidden path="id"/>
用户名:<form:input path="username" /><br>
密码:<form:input path="password" /><br>
邮件:<form:input path="email" /><br>
联系电话:<form:input path="phone" /><br>
职位:<form:select path="rolename">
<form:option value="">请选择职位form:option>
<form:option value="客户经理">客户经理form:option>
<form:option value="高管">高管form:option>
<form:option value="销售主管">销售主管form:option>
<form:option value="系统管理员">系统管理员form:option>
form:select><br>
<input type="submit" value="提交"/>
form:form>
body>
html>
error.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title heretitle>
head>
<body>
<a href="${pageContext.request.contextPath }/index.jsp">登录发生错误,请重新登录a>
body>
html>
http://download.csdn.net/detail/peng_hong_fu/9711731