Spring + springMVC + MyBatis 实现 登录+增删改查+分页查询
开发环境: win10 ,
jdk1.8 ,
idea 2019.1.1 ,
tomcat 8.5.38 ,
maven ,
pageHelp
以上工具一定要有
pom.xml 文件: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 <properties> <project.srping.version>5.0.0.RELEASE</project.srping.version> </properties> <dependencies> <!--Spring的依赖--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${project.srping.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${project.srping.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${project.srping.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${project.srping.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${project.srping.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${project.srping.version}</version> </dependency> <!-- 德鲁伊连接池 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.9</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.38</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.5</version> </dependency> <!--mybatis和Spring的整合--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.1</version> </dependency> <!--日志--> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.25</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.25</version> </dependency> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.16.20</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.8.13</version> </dependency> <!--PageHelper分页插件--> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>5.1.2</version> </dependency> </dependencies> <build> <resources> <resource> <directory>src/main/java</directory> <includes> <include>**
Mybatis于Spring的整合 applicationContext.xml: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 <?xml version="1.0" encoding="UTF-8" ?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" 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 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd " > <!--引入属性配置文件--> <context:property-placeholder location="classpath:db.properties" system-properties-mode="NEVER" /> <!--德鲁伊连接池--> <bean id="dataSource" class ="com.alibaba.druid.pool.DruidDataSource" > <property name="driverClassName" value="${driverClassName}" /> <property name="url" value="${url}" /> <property name="username" value="${username}" /> <property name="password" value="${password}" /> </bean> <!--sqlsessionfactory对象--> <bean id="sqlSessionFactoryBean" class ="org.mybatis.spring.SqlSessionFactoryBean" > <!--配置连接池--> <property name="dataSource" ref="dataSource" /> <!--关联mybatis主配置文件--> <property name="configLocation" value="classpath:mybatis.xml" /> <!--配置别名--> <property name="typeAliasesPackage" value="com.ujiuye.domain" /> <!--关联mapper映射文件--> <property name="mapperLocations" value="classpath:com/ujiuye/mapper/*.xml" /> </bean> <!--配置mapper接口的扫描器--> <bean class ="org.mybatis.spring.mapper.MapperScannerConfigurer" > <!--从哪个包扫描mapper接口--> <property name="basePackage" value="com.ujiuye.mapper" /> </bean> <!-- ioc 注解扫描器--> <context:component-scan base-package ="com.ujiuye" /> <!--配置事务管理器--> <tx:annotation-driven /> <bean id="txManager" class ="org.springframework.jdbc.datasource.DataSourceTransactionManager" > <property name="dataSource" ref="dataSource" /> </bean> <!--配置事务--> <aop:config> <!--配置where--> <aop:pointcut id="txPointcut" expression="execution(* com.ujiuye.service..*.*(..))" /> <!--切面--> <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut" /> </aop:config> <!--增强器--> <tx:advice id="txAdvice" transaction-manager="txManager" > <tx:attributes> <tx:method name="list*" read-only="true" /> <tx:method name="get*" read-only="true" /> <tx:method name="select*" read-only="true" /> <tx:method name="find*" read-only="true" /> <tx:method name="query*" read-only="true" /> <tx:method name="*" /> </tx:attributes> </tx:advice> </beans>
applicationCoutext.xml文件总结:
事务中我给查询的方法加上了 read-only=”true”,只读状态可以提高性能
没有配置read-only的method默认非只读
SpringMVC.xml的配置: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 <?xml version="1.0" encoding="UTF-8" ?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" 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 http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd " > <!--引入后台的spring的配置文件--> <import resource="classpath:applicationContext.xml" /> <!--视图解析器--> <bean class ="org.springframework.web.servlet.view.InternalResourceViewResolver" > <!--配置前缀--> <property name="prefix" value="/WEB-INF/views/" /> <!--配置后缀--> <property name="suffix" value=".jsp" /> </bean> <!--SpringMVC注解解析器--> <mvc:annotation-driven/> <!--拦截器--> <mvc:interceptors> <mvc:interceptor> <!--拦截的路径
拦截器:
必须让用户登录才能进入到更深层的jsp,然后 /** 表示拦截所有,但是我们要排除login这个登录页面
等一下要配置一下拦截的类
MyBatis.xml: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 <?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> <!-- pagehelp拦截器配置--> <plugins> <!-- com.github.pagehelper为PageHelper类所在包名 --> <plugin interceptor="com.github.pagehelper.PageInterceptor" > <!-- 使用下面的方式配置参数,后面会有所有的参数介绍 --> </plugin> </plugins> </configuration>
plugins在配置文件中的位置必须符合要求,否则会报错,顺序如下: properties?, settings?, typeAliases?, typeHandlers?, objectFactory?,objectWrapperFactory?, plugins?, environments?, databaseIdProvider?, mappers?
web.xml: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 <?xml version="1.0" encoding="UTF-8" ?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1" metadata-complete="true" > <!--前端控制器--> <servlet> <servlet-name>dispatcherServlet</servlet-name> <servlet-class >org .springframework .web .servlet .DispatcherServlet </servlet -class > <!--spring 的配置文件--> <init -param > <param -name >contextConfigLocation </param -name > <param-value>classpath:SpringMVC.xml</param-value> </init-param> <!--tomcat启动时初始化--> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcherServlet</servlet-name> <!--*.do 意思是访问页面的时候后缀要加上 .do --> <url-pattern>*.do</url-pattern> </servlet-mapping> <!--请求编码过滤器--> <filter> <filter-name>characterEncodingFilter</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 > <init -param > <param -name >forceRequestEncoding </param -name > <param -value >true </param -value > </init -param > <init -param > <param -name >forceResponseEncoding </param -name > <param -value >true </param -value > </init -param > </filter > <filter -mapping > <filter -name >characterEncodingFilter </filter -name > <url -pattern >/*</url -pattern > </filter -mapping > <!--设置欢迎页,意思是登录页,以前默认index .jsp ,现在是login .jsp --> <welcome -file -list > <welcome -file >login .jsp </welcome -file > </welcome -file -list > </web -app >
controller: LoginController> 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 package com.ujiuye.controller;import com.ujiuye.domain.User;import com.ujiuye.service.IUserService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.RequestMapping;import javax.servlet.http.HttpSession;@Controller public class LoginController { @Autowired private IUserService userService; @RequestMapping ("login" ) public String login (String username, String password, HttpSession session, Model model) { User user = userService.selectLogin(username, password); if (user!=null ){ session.setAttribute("USER_IN_SESSION" ,user); return "redirect:/user/query.do" ; }else { model.addAttribute("msg" ,"用户名或者密码错误" ); return "forward:/login.jsp" ; } } }
如果登录密码是正确的,那么这里的 user 是不为 null的,他就会跳转到用户列表页面,
如果密码错误,还会跳的登录页,
UserController> 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 package com.ujiuye.controller;import com.github.pagehelper.PageInfo;import com.ujiuye.domain.User;import com.ujiuye.qo.QueryObject;import com.ujiuye.result.PageResult;import com.ujiuye.service.IUserService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.ModelAttribute;import org.springframework.web.bind.annotation.RequestMapping;import java.util.List;@Controller @RequestMapping ("user" )public class UserController { @Autowired private IUserService service; @RequestMapping ("query" ) public String query (@ModelAttribute("qo" ) QueryObject qo,Model model) { PageInfo pageInfo = service.query3(qo); model.addAttribute("pageInfo" ,pageInfo); return "user/list" ; } @RequestMapping ("list" ) public String list (Model model) { List<User> list = service.list(); model.addAttribute("list" ,list); return "user/list" ; } @RequestMapping ("edit" ) public String edit (Long id,Model model) { if (id!=null ){ User user = service.get(id); model.addAttribute("user" ,user); } return "user/edit" ; } @RequestMapping ("saveOrUpdate" ) public String saveOrUpdate (User user) { if (user.getId()==null ){ service.save(user); }else { service.update(user); } return "redirect:/user/list.do" ; } @RequestMapping ("delete" ) public String delete (Long id) { service.delete(id); return "redirect:/user/list.do" ; } }
domain 实体类: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 package com.ujiuye.domain;import lombok.*;import java.math.BigDecimal;@Setter @Getter @AllArgsConstructor @NoArgsConstructor @ToString public class User { private Long id; private String username; private String password; private Integer age; private BigDecimal salary; }
interceptor登录检查> LoginInterceptor: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 package com.ujiuye.interceptor;import org.springframework.web.servlet.HandlerInterceptor;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;public class LoginInterceptor implements HandlerInterceptor { public boolean preHandle (HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { HttpSession session = request.getSession(); Object user = session.getAttribute("USER_IN_SESSION" ); if (user == null ){ response.sendRedirect("login.jsp" ); return false ; } return true ; } }
刚刚在LoginController定义了if else,如果登录 !=null 那么session里会有 USER_IN_SESSION 这个key,return ture
如果为null 就会跳转到登录页面;
实现HandlerInterceptor接口: HandlerInterceptor 接口中定义了三个方法,我们就是通过这三个方法来对用户的请求进行拦截处理的。
(1 )preHandle (HttpServletRequest request, HttpServletResponse response, Object handle) 方法,
顾名思义,该方法将在请求处理之前进行调用。SpringMVC 中的Interceptor 是链式的调用的,在一个应用中或者说是在一个请求中可以同时存在多个Interceptor 。每个Interceptor 的调用会依据它的声明顺序依次执行,而且最先执行的都是Interceptor 中的preHandle 方法,所以可以在这个方法中进行一些前置初始化操作或者是对当前请求的一个预处理,也可以在这个方法中进行一些判断来决定请求是否要继续进行下去。该方法的返回值是布尔值Boolean 类型的,当它返回为false 时,表示请求结束,后续的Interceptor 和Controller 都不会再执行;当返回值为true 时就会继续调用下一个Interceptor 的preHandle 方法,如果已经是最后一个Interceptor 的时候就会是调用当前请求的Controller 方法。
(2 )postHandle (HttpServletRequest request, HttpServletResponse response, Object handle, ModelAndView modelAndView) 方法,
由preHandle 方法的解释我们知道这个方法包括后面要说到的afterCompletion 方法都只能是在当前所属的Interceptor 的preHandle 方法的返回值为true 时才能被调用。postHandle 方法,顾名思义就是在当前请求进行处理之后,也就是Controller 方法调用之后执行,但是它会在DispatcherServlet 进行视图返回渲染之前被调用,所以我们可以在这个方法中对Controller 处理之后的ModelAndView 对象进行操作。postHandle 方法被调用的方向跟preHandle 是相反的,也就是说先声明的Interceptor 的postHandle 方法反而会后执行,这和Struts2 里面的Interceptor 的执行过程有点类型。Struts2 里面的Interceptor 的执行过程也是链式的,只是在Struts2 里面需要手动调用ActionInvocation 的invoke 方法来触发对下一个Interceptor 或者是Action 的调用,然后每一个Interceptor 中在invoke 方法调用之前的内容都是按照声明顺序执行的,而invoke 方法之后的内容就是反向的。
(3 )afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handle, Exception ex) 方法,
该方法也是需要当前对应的Interceptor 的preHandle 方法的返回值为true时才会执行。顾名思义,该方法将在整个请求结束之后,也就是在DispatcherServlet 渲染了对应的视图之后执行。这个方法的主要作用是用于进行资源清理工作的。
mapper(dao): UserMapper.java> 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 package com.ujiuye.mapper;import com.ujiuye.domain.User;import com.ujiuye.qo.BaseQueryObject;import com.ujiuye.qo.QueryObject;import org.apache.ibatis.annotations.Param;import java.util.List;public interface UserMapper { void save (User user) ; void update (User user) ; void delete (Long id) ; User get (Long id) ; List<User> list () ; User selectLogin (@Param("username" ) String username, @Param ("password" ) String password) ; List<User> query (QueryObject qo) ; List<User> queryForList (BaseQueryObject qo) ; int queryForCount (QueryObject qo) ; }
UserMapper.xml> 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 <?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.ujiuye.mapper.UserMapper" > <insert id="save" useGeneratedKeys="true" keyProperty="id" keyColumn="id" > insert into user (username,password,age,salary) values (#{username},#{password},#{age},#{salary}) </insert> <update id ="update" > update user set username=#{username},password=#{password},age=#{age}, salary=#{salary} where id =#{id} </update> <delete id="delete" > delete from user where id=#{id} </delete> <select id="get" resultType="com.ujiuye.domain.User" > select * from user where id=#{id} </select> <select id="list" resultType="User" > select * from user </select> <select id="selectLogin" resultType="com.ujiuye.domain.User" > select id,username,password,age,salary from user where username=#{username} and password=#{password} </select> <select id="query" resultType="com.ujiuye.domain.User" > select id,username,password,age,salary from user <where> <if test="username!=null and username!='' " > and username like concat ('%' ,#{username},'%' ) </if > <if test ="salary!=null" > and salary = #{salary} </if> </where> </select> <select id="queryForCount" resultType="int" > select count (*) from user <where> <if test ="username!=null and username!='' " > and username like concat ('%' ,#{username},'%' ) </if > <if test ="salary!=null" > and salary = #{salary} </if> </where> </select> <select id="queryForList" resultType="User" > select * from user <where> <if test="username!=null and username!='' " > and username like concat ('%' ,#{username},'%' ) </if > <if test ="salary!=null" > and salary = #{salary} </if> </where> limit #{start},#{pageSize} </select> </mapper>
mapper映射文件可以跟java文件放在同一个目录下,因为pom里配置了:
1 2 3 4 5 6 7 8 9 10 <build > <resources > <resource > <directory > src/main/java</directory > <includes > <include > **/*.xml</include > </includes > </resource > </resources > </build >
qo(分页): BaseQueryObject> 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 package com.ujiuye.qo;import lombok.Getter;import lombok.Setter;@Setter @Getter public class BaseQueryObject { private Integer currentPage = 1 ; private Integer pageSize = 3 ; public Integer getStart () { return (this .currentPage-1 )*this .pageSize; } }
DepartmentQueryObject> 1 2 3 4 5 6 package com.ujiuye.qo;public class DepartemntQueryObject { private String deptName; }
QueryObject> 1 2 3 4 5 6 7 8 9 10 11 12 13 package com.ujiuye.qo;import lombok.Getter;import lombok.Setter;import java.math.BigDecimal;@Getter @Setter public class QueryObject extends BaseQueryObject { private String username; private BigDecimal salary; }
result: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 package com.ujiuye.result;import lombok.Getter;import lombok.Setter;import java.util.Collections;import java.util.List;@Setter @Getter public class PageResult { private List<?> data; private Integer totalCount; private Integer prevPage; private Integer nextPage; private Integer endPage; public PageResult (List<?> data, Integer totalCount, Integer currentPage, Integer pageSize) { this .data = data; this .totalCount = totalCount; this .prevPage= currentPage-1 >1 ?currentPage-1 :1 ; this .endPage=totalCount%pageSize == 0 ?totalCount/pageSize:totalCount/pageSize+1 ; this .nextPage = currentPage+1 <endPage?currentPage+1 :endPage; } public static PageResult EMPTY_LIST = new PageResult(Collections.emptyList(),0 ,1 ,1 ); }
service 层: 接口> 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 package com.ujiuye.service;import com.alibaba.druid.sql.PagerUtils;import com.github.pagehelper.PageInfo;import com.ujiuye.domain.User;import com.ujiuye.qo.BaseQueryObject;import com.ujiuye.qo.QueryObject;import com.ujiuye.result.PageResult;import java.util.List;public interface IUserService { void save (User user) ; void update (User user) ; void delete (Long id) ; User get (Long id) ; List<User> list () ; User selectLogin (String username,String password) ; List<User> query (QueryObject qo) ; PageResult query2 (QueryObject qo) ; PageInfo query3 (QueryObject qo) ; }
UserServiceImpl 实现类> 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 package com.ujiuye.service.impl;import com.github.pagehelper.PageHelper;import com.github.pagehelper.PageInfo;import com.ujiuye.domain.User;import com.ujiuye.mapper.UserMapper;import com.ujiuye.qo.BaseQueryObject;import com.ujiuye.qo.QueryObject;import com.ujiuye.result.PageResult;import com.ujiuye.service.IUserService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import java.util.Collections;import java.util.List;@Service public class UserServiceImpl implements IUserService { private static PageResult EMPTY_LIST = new PageResult(Collections.emptyList(), 0 , 1 , 1 ); @Autowired private UserMapper userMapper; public void save (User user) { userMapper.save(user); } public void update (User user) { userMapper.update(user); } public void delete (Long id) { userMapper.delete(id); } public User get (Long id) { return userMapper.get(id); } public List<User> list () { return userMapper.list(); } public User selectLogin (String username, String password) { return userMapper.selectLogin(username, password); } public List<User> query (QueryObject qo) { return userMapper.query(qo); } public PageResult query2 (QueryObject qo) { int totlaCount = userMapper.queryForCount(qo); if (totlaCount == 0 ){ return PageResult.EMPTY_LIST; } List<User> data = userMapper.queryForList(qo); return new PageResult(data,totlaCount,qo.getCurrentPage(),qo.getPageSize()); } public PageInfo query3 (QueryObject qo) { PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize()); List<User> list = userMapper.query(qo); return new PageInfo(list); } }
Test: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 package com.ujiuye.test;import com.github.pagehelper.PageHelper;import com.github.pagehelper.PageInfo;import com.ujiuye.domain.User;import com.ujiuye.mapper.UserMapper;import com.ujiuye.service.IUserService;import org.apache.ibatis.session.SqlSessionFactory;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.test.context.ContextConfiguration;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;import java.math.BigDecimal;import java.util.List;@RunWith (SpringJUnit4ClassRunner.class)@ContextConfiguration ("classpath:applicationContext.xml" )public class App { @Autowired private SqlSessionFactory sqlSessionFactory; @Autowired private UserMapper userMapper; @Autowired private IUserService service; private User user = null ; @Test public void testSave () { user = new User(null ,"特朗普" ,"123" ,30 ,new BigDecimal("1.00" )); service.save(user); } @Test public void testUpdate () { user = new User(2L ,"奥巴马" ,"123" ,12 ,new BigDecimal("2000.00" )); service.update(user); } @Test public void testDelete () { service.delete(9L ); } @Test public void testGet () { System.out.println(service.get(7L )); } @Test public void testList () { System.out.println(service.list()); } @Test public void testLogin () { user = service.selectLogin("扎克伯格" ,"456" ); System.out.println(user); } @Test public void testPageHelper () { PageHelper.startPage(2 ,3 ); List<User> list = userMapper.list(); PageInfo pageInfo = new PageInfo(list); System.out.println(pageInfo.getList().get(0 )); System.out.println(pageInfo.getList().get(1 )); System.out.println(pageInfo.getList().get(2 )); System.out.println("上一页:" +pageInfo.getPrePage()); System.out.println("下一页:" +pageInfo.getNextPage()); System.out.println("总页数:" +pageInfo.getSize()); System.out.println("首页:" +pageInfo.getNavigateFirstPage()); System.out.println("尾页:" +pageInfo.getNavigateLastPage()); } }
前台: 我的前台很丑不过还是放一下吧>
edit.jsp 用户编辑页面> 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <h1>用户编辑页面</h1> <form action="/user/saveOrUpdate.do" method="post" > <input type="hidden" value="${user.id}" name="id" > 姓名:<input type="text" name="username" value="${user.username}" ><br> 密码:<input type="text" name="password" value="${user.password}" ><br> 年龄:<input type="text" name="age" value="${user.age}" ><br> 月薪:<input type="text" name="salary" value="${user.salary}" ><br> <input type="submit" value="ok!~" > </form> </body> </html>
list.jsp 主页面> 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 <%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <html> <head> <title>Title</title> <script> function goPage (page) { if (page != undefined){ document.getElementById("currentPage" ).value = page; } var pageForm = document.getElementById("pageForm" ); pageForm.submit(); } </script> </head> <body> <form id="pageForm" action="/user/query.do" method="post" > <h1>用户列表</h1> <table> <tr> 姓名:<input type="text" name="username" value="${qo.username}" > 工资:<input type="text" name="salary" value="${qo.salary}" > <input type="submit" value="查询" > </tr> </table> <a href="/user/edit.do">新增</a> <br/> <table border="1" width="60%" > <tr> <th>编号</th> <th>姓名</th> <th>年龄</th> <th>工资</th> <th>操作</th> </tr> <c:forEach items="${pageInfo.list}" var ="user" > <tr> <td>${user.id}</td> <td>${user.username}</td> <td>${user.age}</td> <td>${user.salary}</td> <td> <a href="/user/edit.do?id=${user.id}">修改</a> <a href="/user/delete.do?id=${user.id}">删除</a> </td> </tr> </c:forEach> <tr> <td colspan="5" > <a href="javascript:void(0);" onclick="goPage(1)">首页</a> <a href="javascript:void(0);" onclick="goPage(${pageInfo.prePage})">上一页</a> <a href="javascript:void(0);" onclick="goPage(${pageInfo.nextPage})">下一页</a> <a href="javascript:void(0);" onclick="goPage(${pageInfo.navigateLastPage})">尾页</a> 每个显示 <select name="pageSize" onchange="goPage(1)" > <option value="3" ${qo.pageSize == 3?"selected":""}>3</option> <option value="5" ${qo.pageSize == 5?"selected":""}>5</option> <option value="10" ${qo.pageSize == 10?"selected":""}>10</option> </select> 条 <input type="text" id="currentPage" name="currentPage" style="width: 50px" value="${qo.currentPage}"> <button onclick="goPage()">跳转</button> 总共${pageInfo.total}条/共${pageInfo.navigateLastPage}页 </td> </tr> </table> </form> </body> </html>
login.jsp> 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>login</title> </head> <body> <h1>登录</h1> <%--如果获取到msg说明密码错误--%> <font color="red">${msg}</font> <form action="/login.do" method="post" > 账号:<input type="text" name="username" > <br> 密码:<input type="text" name="password" ><br> <input type="submit" value="登录" > </form> </body> </html>