ssm分页增删改查,博主技术有限,暂时就这样啦....
如果觉得文章不错,对你有帮助,请作者喝杯咖啡,谢谢!如果对您有帮助 ,请多多支持.多少都是您的心意与支持,一分也是爱,再次感谢!!!打开支付宝首页搜“556723462”领红包,领到大红包的小伙伴赶紧使用哦!感谢大家的支持!您的支持,我会继续分享更多的文章,欢迎关注!
先看效果图如下:里面的人物都是博主一 个一个手敲的。三国迷一个...哈哈
原码下载地址:https://download.csdn.net/download/qq_30764991/11117980
项目结构图:
数据库表与数据:
CREATE TABLE `tb_user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`userName` varchar(40) DEFAULT NULL,
`password` varchar(100) DEFAULT NULL,
`email` varchar(40) DEFAULT NULL,
`phone` varchar(40) DEFAULT NULL,
`roleName` varchar(40) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=35 DEFAULT CHARSET=utf8;
INSERT INTO `tb_user` VALUES ('7', '张飞', '123456', '123456@qq.com', '10086', '将军');
INSERT INTO `tb_user` VALUES ('14', '赵云', '123456', '10086@qq.com', '2154', '将军');
INSERT INTO `tb_user` VALUES ('15', '刘备', '123456', '215454@qq.com', '213234554', '主公');
INSERT INTO `tb_user` VALUES ('16', '曹操', '123456', '21245454@qq.com', '2154587', '主公');
INSERT INTO `tb_user` VALUES ('17', '曹仁', '123456', '54578787@qq.com', '2145784', '大将');
INSERT INTO `tb_user` VALUES ('18', '许褚', '123456', '545484@qq.com', '54584@qq.com', '大将');
INSERT INTO `tb_user` VALUES ('19', '孙权', '123456', '2154545@qq.com', '2148454', '主公');
INSERT INTO `tb_user` VALUES ('20', '陆逊', '123456', '21547787@qq.com', '2124554', '主帅');
INSERT INTO `tb_user` VALUES ('21', '黄忠', '123456', '21454877878@qq.com', '12124548787', '将军');
INSERT INTO `tb_user` VALUES ('22', '周瑜', '123456', '1245787@qq.com', '2115457877', '主帅');
INSERT INTO `tb_user` VALUES ('23', '诸葛亮', '123456', '5454545@qq.com', '10086', '军师');
INSERT INTO `tb_user` VALUES ('25', '魏延', '123456', '15454545@qq.com', '145755454', '大将');
INSERT INTO `tb_user` VALUES ('26', '夏侯惇', '123456', '54578787@qq.com', '121454575', '将军');
INSERT INTO `tb_user` VALUES ('27', '张苞', '123456', '123456@qq.com', '25454', '大将');
INSERT INTO `tb_user` VALUES ('28', '关欣', '123456', '1215545@qq.com', '124545545', '大将');
INSERT INTO `tb_user` VALUES ('29', '曹植', '123456', '245454@qq.com', '545451', '主公');
INSERT INTO `tb_user` VALUES ('30', '曹丕', '123456', '21545454@qq.com', '2465446', '主公');
INSERT INTO `tb_user` VALUES ('31', '孙尚香', '123456', '545451@qq.com', '545452121', '主公');
INSERT INTO `tb_user` VALUES ('32', '刘婵', '123456', '454547454@qq.com', '11244541221', '主公');
INSERT INTO `tb_user` VALUES ('33', '张辽', '123456', '2144545@qq.com', '12154548', '大将');
INSERT INTO `tb_user` VALUES ('34', '马岱', '123456', '1211245454@qq.com', '12124548787', '大将');
ssm配置如下:
spring-dao.xml
<?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"
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.xsd">
<!-- 配置整合mybatis过程 -->
<!-- 1.配置数据库相关参数properties的属性:${url} -->
<context:property-placeholder location="classpath:jdbc.properties" />
<!-- 2.数据库连接池 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<!-- 配置连接池属性 -->
<property name="driverClass" value="${jdbc.driver}" />
<property name="jdbcUrl" value="${jdbc.url}" />
<property name="user" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<!-- c3p0连接池的私有属性 -->
<property name="maxPoolSize" value="30" />
<property name="minPoolSize" value="10" />
<!-- 关闭连接后不自动commit -->
<property name="autoCommitOnClose" value="false" />
<!-- 获取连接超时时间 -->
<property name="checkoutTimeout" value="10000" />
<!-- 当获取连接失败重试次数 -->
<property name="acquireRetryAttempts" value="2" />
</bean>
<!-- 3.配置SqlSessionFactory对象 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 注入数据库连接池 -->
<property name="dataSource" ref="dataSource" />
<!-- 配置MyBaties全局配置文件:mybatis-config.xml -->
<property name="configLocation" value="classpath:mybatis-config.xml" />
<!-- 扫描entity包 使用别名 -->
<property name="typeAliasesPackage" value="cn.com.entity" />
<!-- 扫描sql配置文件:mapper需要的xml文件 -->
<property name="mapperLocations" value="classpath:mapper/*.xml" />
</bean>
<!-- 4.配置扫描Dao接口包,动态实现Dao接口,注入到spring容器中 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 注入sqlSessionFactory -->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
<!-- 给出需要扫描Dao接口包 -->
<property name="basePackage" value="cn.com.dao" />
</bean>
</beans>
spring-service.xml
<?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: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.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- 扫描service包下所有使用注解的类型 -->
<context:component-scan base-package="cn.com.service" />
<!-- 配置事务管理器 -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 注入数据库连接池 -->
<property name="dataSource" ref="dataSource" />
</bean>
<!-- 配置基于注解的声明式事务 -->
<tx:annotation-driven transaction-manager="transactionManager" />
</beans>
spring-web.xml
<?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:mvc="http://www.springframework.org/schema/mvc"
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.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<!-- 配置SpringMVC -->
<!-- 1.开启SpringMVC注解模式 -->
<!-- 简化配置:
(1)自动注册DefaultAnootationHandlerMapping,AnotationMethodHandlerAdapter
(2)提供一些列:数据绑定,数字和日期的format @NumberFormat, @DateTimeFormat, xml,json默认读写支持
-->
<mvc:annotation-driven />
<!-- 2.静态资源默认servlet配置
(1)加入对静态资源的处理:js,gif,png
(2)允许使用"/"做整体映射
-->
<mvc:default-servlet-handler/>
<!-- 3.配置jsp 显示ViewResolver -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- 4.扫描web相关的bean -->
<context:component-scan base-package="cn.com.controller" />
</beans>
jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/ssmdemo
jdbc.username=root
jdbc.password=123456
logback.xml日志
<?xml version="1.0" encoding="UTF-8" ?>
<configuration debug="true">
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<!--开启debug日志模式,在控制台打印日志-->
<root level="debug">
<appender-ref ref="STDOUT" />
</root>
</configuration>
mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- 配置全局属性 -->
<settings>
<!-- 使用jdbc的getGeneratedKeys获取数据库自增主键值 -->
<setting name="useGeneratedKeys" value="true" />
<!-- 使用列别名替换列名 默认:true -->
<setting name="useColumnLabel" value="true" />
<!-- 开启驼峰命名转换:Table{create_time} -> Entity{createTime} -->
<setting name="mapUnderscoreToCamelCase" value="true" />
</settings>
</configuration>
web.xml配置如下:
<?xml version="1.0" encoding="UTF-8"?>
<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_2_5.xsd" version="2.5">
<display-name>ssm-demo</display-name>
<!-- 配置DispatcherServlet -->
<servlet>
<servlet-name>myspringmvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 配置springMVC需要加载的配置文件
spring-dao.xml,spring-service.xml,spring-web.xml
Mybatis - > spring -> springmvc
-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:Spring/spring-*.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>myspringmvc-dispatcher</servlet-name>
<!-- 默认匹配所有的请求 -->
<url-pattern>/</url-pattern>
</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>
</web-app>
Ok,至此,以上ssm框架就搭建好了,这边博主就不测试了,肯定是Ok的。
接下来就是写相应的代码:代码开发流程:entity-->dao--(对应的mapper映射sql语句)>service>serviceimpl-->controller。
entity实体类:
package cn.com.entity;
/**
* 用户实体类
*/
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分页实体类:
package cn.com.entity;
import java.util.List;
/**
* 分页实体类
*/
public class PageBean<T> {
private int currPage;//当前页数
private int pageSize;//每页显示的记录数
private int totalCount;//总记录数
private int totalPage;//总页数
private List<T> 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<T> getLists() {
return lists;
}
public void setLists(List<T> lists) {
this.lists = lists;
}
}
userDao
package cn.com.dao;
import java.util.HashMap;
import java.util.List;
import cn.com.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<User> selectUserList();
/**
* 查询用户记录总数
* @return
*/
int selectCount();
/**
* 分页操作,调用findByPage limit分页方法
* @param map
* @return
*/
List<User> findByPage(HashMap<String,Object> map);
}
UserMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="cn.com.dao.UserDao">
<!-- 先定义一个Interface,UserMapper,然后Mapper文件的namespace指向的就是这个Interface, UserInterface里定义的方法和UserMapper.xml文件中的一样,
然后代码里直接使用接口 -->
<resultMap id="BaseResultMap" type="cn.com.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="cn.com.entity.User">
select
<include refid="Base_Column_List" />
from tb_user
where
userName = #{username}
and password = #{password}
</select>
<!-- 根据分页数据start 和size查询数据 -->
<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="cn.com.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="cn.com.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="cn.com.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="cn.com.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="cn.com.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>
userSerevice
package cn.com.service;
import java.util.List;
import cn.com.entity.PageBean;
import cn.com.entity.User;
/**
* User类业务层接口
*/
public interface UserService {
int deleteByPrimaryKey(Integer id);
int insertSelective(User record);
User selectByPrimaryKey(Integer id);
User loginByUserNameAndPassword(User record);
List<User> selectUserList();
int selectCount();
int updateByPrimaryKeySelective(User record);
PageBean<User> findByPage(int currentPage);
}
userServiceImpl
package cn.com.service.impl;
import java.util.HashMap;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import cn.com.dao.UserDao;
import cn.com.entity.PageBean;
import cn.com.entity.User;
import cn.com.service.UserService;
/**
* User类业务层实现类
*/
@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<User> selectUserList() {
return userDao.selectUserList();
}
@Override
public int selectCount() {
return userDao.selectCount();
}
@Override
public User loginByUserNameAndPassword(User record) {
return userDao.loginByUserNameAndPassword(record);
}
@Override
public PageBean<User> findByPage(int currentPage) {//currPage当前页数
//创建HashMap对象封装
HashMap<String,Object> map = new HashMap<String,Object>();
//创建一个分页对象
PageBean<User> pageBean = new PageBean<User>();
//封装当前页数
pageBean.setCurrPage(currentPage);
//每页显示的数据
int pageSize=10;
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);//(当前页数-1)*每页显示数
map.put("size", pageBean.getPageSize());//每页显示的记录数
//封装每页显示的数据
List<User> lists = userDao.findByPage(map);
pageBean.setLists(lists);
return pageBean;
}
}
userController
package cn.com.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 cn.com.entity.User;
import cn.com.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<User> lists = userService.selectUserList();
//把查询到的所有结果回显给前端main.jsp
model.addAttribute("userLists", lists);//回显用户信息
//把获取的用户名传回给currentUser
model.addAttribute("currentUser", userresult.getUsername());
//重定向到main.jsp页面
return "redirect:main";
}
return "error";
}
/**
* @param currentPage
* @param model
* @return
*/
@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());
//如果获取的用户id为空
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" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Index.jsp</title>
<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>
main.jsp 主页展示页:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>ssm分页的主页</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}<!-- (只能在同一个页面中使用) --> <br>
当前用户:${requestScope.currentUser}-${roleName} 有重定向数据就访问不到<br>
当前用户:${sessionScope.currentUser}-${roleName} 可以使用<br> --%>
<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>修改</td>
<td>删除</td>
</tr>
</thead>
<!--lists是后端传回的所有的结果 -->
<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}">修改</a></th>
<th><a href="delete?id=${u.id}" onclick="return confirm('确定要删除吗')">删除</a></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 != 5}">
<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"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<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: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"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<a href="${pageContext.request.contextPath }/index.jsp">登录发生错误,请重新登录</a>
</body>
</html>
Ok,至此整个完整的ssm分页增删改查就全部写好了,亲测可用。如果自己写的还是不行的话,那么博主把自己代码上传至csdn提供大家参考!