Spring+Struts2+MyBatis+分页(mybatis无代理)增删改查
1、创建如下项目结构
2、在src下的com.entity包下创建Dept.java
package com.entity; /** * 部门表 * @author CHIL * */ public class Dept { private Integer deptno; //部门编号 private String dname; //部门名称 private String loc; //位置 public Dept() { } public Dept(Integer deptno, String dname, String loc) { this.deptno = deptno; this.dname = dname; this.loc = loc; } public Integer getDeptno() { return deptno; } public void setDeptno(Integer deptno) { this.deptno = deptno; } public String getDname() { return dname; } public void setDname(String dname) { this.dname = dname; } public String getLoc() { return loc; } public void setLoc(String loc) { this.loc = loc; } } Dept.java
3、在src下的com.page包下创建Page.java
package com.page; /** * * @author CHIL * */ public class Page { private Integer pageno; private Integer pagesize; private Integer totalcount; private Integer totalpage; private Integer startrow; private Integer endrow; public Page() { } public Page(Integer pageno, Integer pagesize, Integer totalcount) { this.pageno = pageno; this.pagesize = pagesize; this.startrow=pageno*pagesize; this.endrow=(pageno-1)*pagesize; this.totalcount = totalcount; this.setTotalpage(totalcount); } public Integer getPageno() { return pageno; } public void setPageno(Integer pageno) { this.pageno = pageno; } public Integer getPagesize() { return pagesize; } public void setPagesize(Integer pagesize) { this.pagesize = pagesize; } public Integer getTotalcount() { return totalcount; } public void setTotalcount(Integer totalcount) { this.totalcount = totalcount; } public Integer getTotalpage() { return totalpage; } /** * 总条数 * @param totalcount */ public void setTotalpage(Integer totalcount) { this.totalpage = totalcount%pagesize==0? totalcount/pagesize:totalcount/pagesize+1; } public Integer getStartrow() { return startrow; } public void setStartrow(Integer startrow) { this.startrow = startrow; } public Integer getEndrow() { return endrow; } public void setEndrow(Integer endrow) { this.endrow = endrow; } } Page.java
4、在src下的com.mapper包下创建DeptMapper.java
package com.mapper; import java.util.List; import com.entity.Dept; import com.page.Page; /** * 数据访问层接口 * @author CHIL * */ public interface DeptMapper { //查询所有 public List<Dept> findAll(); //分页查询 public List<Dept> findPage(Page page); //查询总记录数 public Integer findCount(); //根据id查询 public Dept findById(int id); //保存对象 public int saveDept(Dept dept); //修改对象 public int updateDept(Dept dept); //根据id删除 public int deleteById(int id); } DeptMapper.java
5、在src下的com.mapper包下创建DeptMapper.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="com.mapper.DeptMapper"> <!-- 查询所有 --> <select id="findAll" resultType="dept"> select * from dept </select> <!-- 分页查询 --> <select id="findPage" resultType="dept" parameterType="page"> <![CDATA[ select * from ( select rownum r,deptno,dname,loc from dept where rownum<=#{startrow} )d where d.r> #{endrow} ]]> </select> <!-- 查询总记录数 --> <select id="findCount" resultType="Integer"> select count(*) from dept </select> <!-- 根据id查询 --> <select id="findById" parameterType="int" resultType="dept"> select * from dept where deptno=#{deptno} </select> <!-- 保存对象 --> <insert id="saveDept" parameterType="dept"> insert into dept values(#{deptno},#{dname},#{loc}) </insert> <!-- 修改对象 --> <update id="updateDept" parameterType="dept"> update dept set dname=#{dname},loc=#{loc} where deptno=#{deptno} </update> <!-- 根据id删除 --> <delete id="deleteById" parameterType="int"> delete from dept where deptno=#{deptno} </delete> </mapper> DeptMapper.xml
6、在src下创建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> <!-- 别名映射 --> <typeAliases> <typeAlias type="com.entity.Dept" alias="dept"/> <typeAlias type="com.page.Page" alias="page"/> </typeAliases> <!-- 注册xml文件 --> <mappers> <mapper resource="com/mapper/DeptMapper.xml"/> </mappers> </configuration> mybatis-config.xml
7、在src下创建log4j.properties日志属性文件
log4j.rootLogger=DEBUG, Console
#Console
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n
log4j.logger.java.sql.ResultSet=INFO
log4j.logger.org.apache=INFO
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
log4j.properties
8、在src下的com.mapper.impl包下创建DeptMapperImpl.java
package com.mapper.impl; import java.util.List; import org.mybatis.spring.SqlSessionTemplate; import com.entity.Dept; import com.mapper.DeptMapper; import com.page.Page; /** * 数据访问层接口的实现类 * @author CHIL * */ public class DeptMapperImpl implements DeptMapper { //注入seqsession对象 private SqlSessionTemplate sqlSessionTemplate; //必须存在getter和setter否则xml文件不能注入,会报没有session public SqlSessionTemplate getSqlSessionTemplate() { return sqlSessionTemplate; } public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) { this.sqlSessionTemplate = sqlSessionTemplate; } /** * 1.根据id删除 */ public int deleteById(int id) { int num=sqlSessionTemplate.delete("com.mapper.DeptMapper.deleteById", id); if(num>0){ System.out.println("删除成功"); }else{ System.out.println("删除失败"); } return num; } /** * 2.添加部门信息 */ public int saveDept(Dept dept) { int num=sqlSessionTemplate.insert("com.mapper.DeptMapper.saveDept", dept); if(num>0){ System.out.println("添加成功"); }else{ System.out.println("添加失败"); } return num; } /** * 3.修改 */ public int updateDept(Dept dept) { int num=sqlSessionTemplate.update("com.mapper.DeptMapper.updateDept", dept); if(num>0){ System.out.println("修改成功"); }else{ System.out.println("修改失败"); } return num; } /** * 4.查询所有 */ public List<Dept> findAll() { List<Dept> list=sqlSessionTemplate.selectList("com.mapper.DeptMapper.findAll"); if(list!=null){ System.out.println("查到所有"); }else{ System.out.println("没有查到所有"); } return list; } /** * 5.根据id没有查到 */ public Dept findById(int id) { Dept dept=sqlSessionTemplate.selectOne("com.mapper.DeptMapper.findById",id); if(dept!=null){ System.out.println("根据id查到"); }else{ System.out.println("根据id没有查到"); } return dept; } /** * 分页查询 */ public List<Dept> findPage(Page page) { List<Dept> list=sqlSessionTemplate.selectList("com.mapper.DeptMapper.findPage",page); if(list!=null){ System.out.println("分页查到了"); }else{ System.out.println("分页没有查到"); } return list; } /** * 查询总记录数 */ public Integer findCount() { Integer totalCount=sqlSessionTemplate.selectOne("com.mapper.DeptMapper.findCount"); return totalCount; } } DeptMapperImpl.java
9、在src下的com.service包下创建DeptService.java
package com.service; import java.util.List; import com.entity.Dept; import com.page.Page; /** * 业务逻辑层接口 * @author CHIL * */ public interface DeptService { //查询所有 public List<Dept> findAll(); //分页查询 public List<Dept> findPage(Page page); //查询总记录数 public Integer findCount(); //根据id查询 public Dept findById(int id); //保存对象 public int saveDept(Dept dept); //修改对象 public int updateDept(Dept dept); //根据id删除 public int deleteById(int id); } DeptService.java
10、在src下的com.service.impl包下创建DeptServiceImpl.java
package com.service; import java.util.List; import com.entity.Dept; import com.page.Page; /** * 业务逻辑层接口 * @author CHIL * */ public interface DeptService { //查询所有 public List<Dept> findAll(); //分页查询 public List<Dept> findPage(Page page); //查询总记录数 public Integer findCount(); //根据id查询 public Dept findById(int id); //保存对象 public int saveDept(Dept dept); //修改对象 public int updateDept(Dept dept); //根据id删除 public int deleteById(int id); } DeptService.java
11、在src下的com.action包下创建DeptAction.java
package com.action; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.apache.struts2.ServletActionContext; import com.entity.Dept; import com.opensymphony.xwork2.ActionSupport; import com.page.Page; import com.service.DeptService; /** * * @author CHIL * */ public class DeptAction extends ActionSupport { //注入业务逻辑层对象 private DeptService service; //struts标签中动态代理赋值对象 private Dept dept; //分页对象 private Page page; /** * 1.查询所有 * @return */ public String findAll(){ List<Dept> list=service.findAll(); if(list!=null){ HttpServletRequest request=ServletActionContext.getRequest(); request.setAttribute("list", list); return SUCCESS; }else{ return ERROR; } } /** * 1.分页查询所有 * @return */ public String findPage(){ //当前页 Integer pageNo=1; if(page!=null){ System.out.println("page不为空"); pageNo=page.getPageno(); }else{ System.out.println("page为空"); } //页面大小 Integer pageSize=3; //查询总条数 Integer totalCount= service.findCount(); page=new Page(pageNo, pageSize, totalCount); List<Dept> list=service.findPage(page); if(list!=null){ HttpServletRequest request=ServletActionContext.getRequest(); request.setAttribute("list", list); request.setAttribute("page", page); return SUCCESS; }else{ return ERROR; } } /** * 根据id查询 * @return */ public String findById(){ if(dept!=null){ Dept dt=service.findById(dept.getDeptno()); if(dt!=null){ HttpServletRequest request=ServletActionContext.getRequest(); request.setAttribute("dt", dt); return SUCCESS; } } return ERROR; } /** * 添加 * @return */ public String save(){ if(dept!=null){ int num=service.saveDept(dept); if(num>0){ return SUCCESS; }else{ return ERROR; } } return ERROR; } /** * 修改 * @return */ public String update(){ if(dept!=null){ int num=service.updateDept(dept); if(num>0){ return SUCCESS; }else{ return ERROR; } } return ERROR; } /** * 删除 * @return */ public String delete(){ if(dept!=null){ int num=service.deleteById(dept.getDeptno()); if(num>0){ return SUCCESS; }else{ return ERROR; } } return ERROR; } public DeptService getService() { return service; } public void setService(DeptService service) { this.service = service; } public Dept getDept() { return dept; } public void setDept(Dept dept) { this.dept = dept; } public Page getPage() { return page; } public void setPage(Page page) { this.page = page; } } DeptAction.java
12、在src下创建Spring的配置文件applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd "> <!-- 1.数据源配置 --> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/> <property name="url" value="jdbc:oracle:thin:@127.0.0.1:1521:orcl"/> <property name="username" value="scott"/> <property name="password" value="tiger"/> </bean> <!-- 2.配置事务 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <!-- 事务中注入数据源--> <property name="dataSource" ref="dataSource"/> </bean> <!-- 3.配置SqlSessionFactory --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 注入数据源 --> <property name="dataSource" ref="dataSource"/> <!-- 注入mybaits主配置文件 --> <property name="configLocation"> <value>classpath:mybatis-config.xml</value> </property> </bean> <!-- 4.获取SqlSessionTemplate --> <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate"> <!--通过构造注入sqlsessionFactory--> <!-- index表示构造的参数索引位置,type表示构造参数的类型--> <constructor-arg index="0" ref="sqlSessionFactory"/> </bean> <!-- 5.实例化dao --> <bean id="dao" class="com.mapper.impl.DeptMapperImpl"> <!-- 注入sqlSessionTemplate --> <property name="sqlSessionTemplate" ref="sqlSessionTemplate"/> </bean> <!-- 6.实例化service --> <bean id="service" class="com.service.impl.DeptServiceImpl"> <!-- 注入dao --> <property name="dao" ref="dao"/> </bean> <!-- 7.实例化action --> <bean id="DeptAction" class="com.action.DeptAction"> <!-- 注入service --> <property name="service" ref="service"/> </bean> </beans> applicationContext.xml
13、在src下创建Struts2的配置文件struts.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN" "struts-2.1.7.dtd" > <struts> <!-- 中文乱码处理 --> <constant name="struts.i18n.encoding" value="UTF-8"/> <package name="default" namespace="/" extends="struts-default"> <!-- 默认首起项配置 <default-action-ref name="findPage" /> --> <!-- ssm框架集合时,class的值是spring配置文件的实例化action的bean的id值 --> <!-- 1.查询所有 --> <action name="findAll" class="DeptAction" method="findAll"> <result name="success">index.jsp</result> <result name="error">fail.jsp</result> </action> <!-- 1.查询所有 --> <action name="findPage" class="DeptAction" method="findPage"> <result name="success">index.jsp</result> <result name="error">fail.jsp</result> </action> <!-- 2.根据id查询 --> <action name="findById" class="DeptAction" method="findById"> <result name="success">update.jsp</result> <!-- 重定向到action --> <result name="error" type="redirectAction">findAll</result> </action> <!-- 3.添加 --> <action name="save" class="DeptAction" method="save"> <!-- 重定向到action --> <result name="success" type="redirectAction">findAll</result> <result name="error">insert.jsp</result> </action> <!-- 4.修改 --> <action name="update" class="DeptAction" method="update"> <!-- 重定向到action --> <result name="success" type="redirectAction">findAll</result> <result name="error">fail.jsp</result> </action> <!-- 5.删除 --> <action name="delete" class="DeptAction" method="delete"> <!-- 重定向到action --> <result name="success" type="redirectAction">findAll</result> <result name="error">fail.jsp</result> </action> </package> </struts> struts.xml
14、编辑WebRoot下的WEB-INF下web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app id="WebApp_9" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>*.action</url-pattern> </filter-mapping> <welcome-file-list> <welcome-file></welcome-file> </welcome-file-list> </web-app> web.xml
15、在WebRoot下创建index.jsp文件
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'index.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <center> <a href="insert.jsp">添加</a> <table border="1"> <tr><td>部门编号</td><td>部门名称</td><td>部门地址</td><td>操作</td></tr> <c:forEach var="i" items="${requestScope.list}"> <tr> <td>${i.deptno}</td> <td>${i.dname}</td> <td>${i.loc}</td> <td> <a href="delete.action?dept.deptno=${i.deptno}">删除</a> | <a href="findById.action?dept.deptno=${i.deptno}">修改</a> </td> </tr> </c:forEach> </table> 第${page.pageno}/${page.totalpage }页 <a href="findPage.action?page.pageno=1">首页</a> <c:choose> <c:when test="${page.pageno>1}"> <a href="findPage.action?page.pageno=${page.pageno-1 }">上一页</a> </c:when> <c:otherwise> <a href="javascript:alert('已经是第一页了!');">上一页</a> </c:otherwise> </c:choose> <c:choose> <c:when test="${page.pageno<page.totalpage}"> <a href="findPage.action?page.pageno=${page.pageno+1 }">下一页</a> </c:when> <c:otherwise> <a href="javascript:alert('已经是最后一页了!');">上一页</a> </c:otherwise> </c:choose> <a href="findPage.action?page.pageno=${page.totalpage}">末页</a> 总${page.totalcount }条 </center> </body> </html> index.jsp
16、在WebRoot下创建insert.jsp文件
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'index.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <center> <form action="save.action" method="post"> <table border="1"> <tr> <td>部门编号:</td> <td><input type="text" name="dept.deptno"/></td> </tr> <tr> <td>部门名称:</td> <td><input type="text" name="dept.dname"/></td> </tr> <tr> <td>部门地址:</td> <td><input type="text" name="dept.loc"/></td> </tr> <tr> <td><input type="submit" value="提交"/></td> <td><input type="reset" value="重置"/></td> </tr> </table> </form> </center> </body> </html> insert.jsp
17、在WebRoot下创建update.jsp文件
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'index.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <center> <fieldset> <legend>修改操作</legend> <form action="update.action" method="post"> <table border="1"> <tr> <td>部门编号:</td> <td><input type="text" name="dept.deptno" value="${dt.deptno}" readonly="readonly"/></td> </tr> <tr> <td>部门名称:</td> <td><input type="text" name="dept.dname" value="${dt.dname}"/></td> </tr> <tr> <td>部门地址:</td> <td><input type="text" name="dept.loc" value="${dt.loc}"/></td> </tr> <tr> <td><input type="submit" value="提交"/></td> <td><input type="reset" value="重置"/></td> </tr> </table> </form> </fieldset> </center> </body> </html> update.jsp
18、在WebRoot下创建fail.jsp文件
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'index.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> 操作失败 </body> </html> fail.jsp
19、运行项目如下