需求:
后台使用ssm(spring-springMVC-mybatis)进行整合
前台使用bootstrap框架
前后台交互使用Ajax进行发送
表结构:
登录页面后显示所有用户信息,可对每条进行增删改查
登录时也使用本表的user_name和user_pwd进行校验
项目目录结构
步骤一:搭建框架,进行测试
applicationContext.xml:spring配置文件,内容还包括spring和mybatis整合
mybatis.xml:mybatis配置文件
springmvcServlet-servlet.xml:springMVC配置文件
1.在src目录下新建context包,用来存放配置文件
2.配置web.xml
3.导入需要的jar包
由于本项目还会使用到junit测试,pageHelper等组件,所以有些jar包不是在搭框架的时候所必须的,必须的jar包大家可以问度娘哈
编写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_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>ssm-dynamic</display-name> <!-- 启动spring容器 --> <context-param> <param-name>contextConfigLocation</param-name> <!-- 在根目录存在springContext.xml文件 --> <param-value>classpath*:contexts/applicationContext.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 配置log4j --> <context-param> <param-name>log4jConfigLocation</param-name> <param-value>WEB-INF/classes/contexts/log4j.properties</param-value> </context-param> <context-param> <param-name>log4jRefreshInterval</param-name> <param-value>60000</param-value> </context-param> <!-- 需要添加spring-web.jar包 --> <listener> <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class> </listener> <!-- 配置springmvc前端控制器 --> <servlet> <!-- 在于web.xml同级目录下存在springmvcServlet-servlet.xml文件 --> <servlet-name>springmvcServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:contexts/springmvcServlet-servlet.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvcServlet</servlet-name> <!-- 拦截所有请求 --> <url-pattern>/</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> <!-- 使用Rest风格的URI,将页面普通的post请求转为指定的delete或者put请求 --> <filter> <filter-name>HiddenHttpMethodFilter</filter-name> <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class> </filter> <filter-mapping> <filter-name>HiddenHttpMethodFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
applicationContext.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:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:p="http://www.springframework.org/schema/p" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd" default-lazy-init="true"> <!-- spring配置文件,配置与业务逻辑相关的 --> <context:component-scan base-package="com.huaxin"> <!-- 不扫描控制器 --> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> <!-- 引入外部配置文件 --> <context:property-placeholder location="classpath:contexts/jdbc.properties"/> <!-- ======数据源配置开始====== --> <bean id = "dataSource" class="com.zaxxer.hikari.HikariDataSource" destroy-method="close"> <property name="driverClassName" value="${jdbc.driver}" /> <property name="jdbcUrl" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <property name="maximumPoolSize" value="${jdbc.maximumPoolSize}" /> <property name="minimumIdle" value="${jdbc.minimumIdle}" /> <property name="connectionTestQuery" value="${jdbc.connectionTestQuery}" /> <property name="dataSourceProperties"> <props> <prop key="cachePrepStmts">${jdbc.cachePrepStmts}</prop> <prop key="prepStmtCacheSize">${jdbc.prepStmtCacheSize}</prop> <prop key="prepStmtCacheSqlLimit">${jdbc.prepStmtCacheSqlLimit}</prop> <prop key="useServerPrepStmts">${jdbc.useServerPrepStmts}</prop> </props> </property> </bean> <!-- ======数据源配置结束====== --> <!-- ======整合mybatis开始====== --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 指定mybatis全局配置文件位置 --> <property name="configLocation" value="classpath:contexts/mybatis.xml"></property> <!-- 指定数据源 --> <property name="dataSource" ref="dataSource"></property> <!-- 指定mybatis的mapper文件的位置 --> <property name="mapperLocations" value="classpath:com/huaxin/mapping/*.xml"></property> </bean> <!-- 配置扫描器,将mybatis接口的实现加入到ioc容器中 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!-- 扫描所有dao接口的实现,加入到ioc容器中 --> <property name="basePackage" value="com.huaxin.dao"></property> </bean> <!-- ======整合mybatis结束====== --> <!-- ======配置可执行批量的sqlSession开始====== --> <!-- <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate.class"> <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"></constructor-arg> <constructor-arg name="executorType" value="BATCH"></constructor-arg> </bean> --> <!-- ======配置可执行批量的sqlSession结束====== --> <!-- ======事物控制的配置开始====== --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <!-- 控制数据源 --> <property name="dataSource" ref="dataSource"></property> <!-- 开启基于注解的事物,使用xml配置形式的事物(比较主要的使用配置形式) --> </bean> <aop:config> <!-- 切入点表达式 *[返回值类型]+空格+需要控制事物的包+ ..[两个点表示其子包也可以]+*[方法]+(..)[两个点表示任意多个参数] --> <aop:pointcut expression="execution(* com.huaxin.service..*(..))" id="txPoint"/> <!-- 配置事物增强 --> <aop:advisor advice-ref="txAdvice" pointcut-ref="txPoint"/> </aop:config> <!-- 配置事物增强,事物如何切入 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <!-- *表示所有方法都是事物方法 --> <tx:method name="*"/> <!-- 以get开始的所有方法,认为都是查询方法,进行调优 --> <tx:method name="get*" read-only="true"/> </tx:attributes> </tx:advice> <!-- ======事物控制的配置结束====== --> <!-- Spring配置文件的核心点(数据源,与mybatis的整合,事物控制) --> </beans>
springmvcServlet-servlet.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:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:p="http://www.springframework.org/schema/p" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd" default-lazy-init="true"> <!-- springmvc配置文件,包含网站跳转逻辑的控制,配置 --> <context:component-scan base-package="com.huaxin" use-default-filters="false"> <!-- 只扫描控制器 --> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> <!-- 配置视图解析器,方便页面返回 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/"></property> <property name="suffix" value=".jsp"></property> </bean> <!-- 两个标准配置 --> <!-- 将springmvc不能处理的请求交给tomcat --> <mvc:default-servlet-handler/> <!-- 能支持springmvc更高级的功能,JSR303校验,快捷的Ajax等等,映射动态请求 --> <mvc:annotation-driven/> </beans>
mybatis.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> <setting name="mapUnderscoreToCamelCase" value="true"/> </settings> <!-- 配置类型别名 --> <typeAliases> <package name="com.huaxin.bean"/> </typeAliases> <!-- 配置分页查询 --> <plugins> <plugin interceptor="com.github.pagehelper.PageInterceptor"> <!-- 3.3.0版本可用 - 分页参数合理化,默认false禁用 --> <!-- 启用合理化时,如果pageNum<1会查询第一页,如果pageNum>pages会查询最后一页 --> <property name="reasonable" value="true"/> </plugin> </plugins> </configuration>
使用mybatis逆向工程生成bean,dao和mapping
配置mbg.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"> <generatorConfiguration> <context id="DB2Tables" targetRuntime="MyBatis3"> <!-- 配置是否生成注释 --> <commentGenerator> <property name="suppressAllComments" value="true" /> </commentGenerator> <!-- 配置数据库连接信息 --> <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://127.0.0.1:3306/test" userId="root" password="1234"> </jdbcConnection> <javaTypeResolver > <property name="forceBigDecimals" value="false" /> </javaTypeResolver> <!-- 指定JavaBean生成位置 --> <javaModelGenerator targetPackage="com.huaxin.bean" targetProject=".\src"> <property name="enableSubPackages" value="true" /> <property name="trimStrings" value="true" /> </javaModelGenerator> <!-- 指定sql映射文件生成的位置 --> <sqlMapGenerator targetPackage="com.huaxin.mapping" targetProject=".\src"> <property name="enableSubPackages" value="true" /> </sqlMapGenerator> <!-- 指定dao接口生成的位置,mapper接口生成的位置 --> <javaClientGenerator type="XMLMAPPER" targetPackage="com.huaxin.dao" targetProject=".\src"> <property name="enableSubPackages" value="true" /> </javaClientGenerator> <!-- 指定每个表的生成策略,enable***表示不生成example表 --> <table tableName="user" domainObjectName="User" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table> </context> </generatorConfiguration>
编写生成类
package com.huaxin.test; import java.io.File; import java.util.ArrayList; import java.util.List; import org.mybatis.generator.api.MyBatisGenerator; import org.mybatis.generator.config.Configuration; import org.mybatis.generator.config.xml.ConfigurationParser; import org.mybatis.generator.internal.DefaultShellCallback; public class MBGTest { public static void main(String[] args) throws Exception { List<String> warnings = new ArrayList<String>(); boolean overwrite = true; File configFile = new File("mbg.xml"); ConfigurationParser cp = new ConfigurationParser(warnings); Configuration config = cp.parseConfiguration(configFile); DefaultShellCallback callback = new DefaultShellCallback(overwrite); MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings); myBatisGenerator.generate(null); System.out.println("生成代码成功"); } }
执行后刷新项目,即可看到生成的代码
测试dao层以及项目基本配置是否成功
编写测试类MapperTest.java
package com.huaxin.test; 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 com.huaxin.bean.User; import com.huaxin.dao.UserMapper; /** * 测试dao层 * @author ws * Spring项目可以使用spring的单元测试,可以自动注入我们需要的组件 * 1.导入SpringTest模块spring-test-4.1.7.RELEASE.jar * 2.@ContextConfiguration指定配置文件位置 * @RunWith(SpringJUnit4ClassRunner.class)指定使用spring的单元测试 * 3.直接autowired要使用的组件即可 */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations={"classpath:contexts/applicationContext.xml"}) public class MapperTest { @Autowired UserMapper userMapper; /*@Autowired SqlSession sqlSession;*/ public static void main(String[] args) { /*// 1.创建SpringIOC容器 ApplicationContext ioc = new ClassPathXmlApplicationContext("springContext.xml"); // 2.从容器中获取mapper UserMapper bean = ioc.getBean(UserMapper.class);*/ } @Test public void testC(){ System.out.println(">>>>>>>>>>>>>>>>>>>>" + userMapper); User user = new User(); user.setUserId("testCRUD3"); user.setUserName("李小龙"); user.setUserPwd("qwer123"); user.setAge(231); userMapper.insertSelective(user); /*for(int i = 0;i < 500;i++){ String uid = UUID.randomUUID().toString().substring(0, 5); userMapper.insertSelective(new User(uid, uid, uid, i)); System.out.println("插入成功!"); }*/ System.out.println("插入完成"); } @Test public void testCs(){ /*UserMapper userMapper = sqlSession.getMapper(UserMapper.class); for(int i = 0;i < 1000;i++){ String uid = UUID.randomUUID().toString().substring(0, 5); String id = UUID.randomUUID().toString().substring(5,10); userMapper.insertSelective(new User(id, uid, uid, i)); }*/ } }
编写login.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>登录页面</title> <!-- 获取项目名称 --> <% pageContext.setAttribute("PATH", request.getContextPath()); %> <!-- web路径 不以/开始的相对路径,找资源以当前路径为基准(容易出问题) 以/开始的相对路径,找资源以服务器的路径(http://localhost:8080)为标准,需要加项目名 --> <script type="text/javascript" src="${PATH}/static/jquery/jquery-1.12.4.min.js"></script> <link href="${PATH }/static/bootstrap-3.3.7-dist/css/bootstrap.min.css" rel="stylesheet"> <script type="text/javascript" src="${PATH }/static/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script> <%-- <link href="${PATH }/static/css/login.css" rel="stylesheet"> --%> <style type="text/css"> .container{ display:table; height:100%; } .row{ display: table-cell; vertical-align: middle; } </style> </head> <body> <div class="container"> <div class="row"> <div class="col-sm-2"> <form action="login" method="post"> <div class="form-group"> <label>用户名</label> <input type="text" class="form-control input-sm" name="username"> </div> <div class="form-group"> <label>密码</label> <input type="password" class="form-control input-sm" name="password"> </div> <div class="checkbox"> <label> <input type="checkbox">记住用户名密码 </label> </div> <button type="submit" class="btn btn-default">提交</button> <div>${msg}</div> </form> </div> </div> </div> </body> </html>
LoginController.java
package com.huaxin.controller; import javax.servlet.http.HttpServletRequest; 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 org.springframework.web.bind.annotation.RequestMethod; import com.huaxin.bean.User; import com.huaxin.dao.UserMapper; @Controller public class LoginController { @Autowired private UserMapper userMapper; /** * 访问时跳转登录页面 * @param model * @return */ @RequestMapping(value="/",method=RequestMethod.GET) public String index(Model model){ model.addAttribute("msg", ""); return "login"; } @RequestMapping(value="/login") public String login(Model model, // 向前台页面传的值放入model中 HttpServletRequest request // 从前台页面取得的值 ){ String username = request.getParameter("username"); String password = request.getParameter("password"); boolean flag = LoginCheck(username, password); if(flag){ return "uerList"; }else{ model.addAttribute("msg", "用户名或密码不正确,请重新登录"); return "login"; } } /** * 检查用户名密码是否正确 * @param username * @param password * @return */ private boolean LoginCheck(String username,String password){ User user = userMapper.selectByUserName(username); if(user == null || "".equals(user)){ return false; } if(user.getUserPwd().equals(password)){ return true; }else{ return false; } } }
这里在userMapper中新增了根据username查询该记录的信息
sql写在UserMapper.xml中
<select id="selectByUserName" resultMap="BaseResultMap" parameterType="java.lang.String" > select <include refid="Base_Column_List" /> from user where user_name = #{username,jdbcType=VARCHAR} </select>
启动项目,本项目使用的是tomcat7.0,jdk1.8
页面效果图(ps:目前页面样式没有调整,还比较丑,大家可以自己调整一下,还有记住用户名密码功能尚未实现)
登录成功,显示user列表信息
uerList.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>json展示页面</title> <!-- 获取项目名称路径 --> <% pageContext.setAttribute("PATH", request.getContextPath()); %> <!-- web路径 不以/开始的相对路径,找资源以当前路径为基准(容易出问题) 以/开始的相对路径,找资源以服务器的路径(http://localhost:8080)为标准,需要加项目名 --> <script type="text/javascript" src="${PATH}/static/jquery/jquery-1.12.4.min.js"></script> <link href="${PATH }/static/bootstrap-3.3.7-dist/css/bootstrap.min.css" rel="stylesheet"> <script type="text/javascript" src="${PATH }/static/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script> <link href="${PATH }/static/css/list.css" rel="stylesheet"> <script type="text/javascript" src="${PATH }/static/js/list.js"></script> </head> <body> <%-- ${pageInfo } --%> <!-- 使用bootstrap栅格系统搭建显示页面 --> <div class="container"> <!-- 标题 --> <div class="row"> <div class="col-sm-12"> <h1>USER INFO</h1> </div> </div> <!-- 增加删除按钮 --> <div class="row"> <!-- 使用列偏移 --> <div class="col-sm-4 col-sm-offset-10"> <!-- 使用按钮样式 --> <button type="button" class="btn btn-primary btn-sm" id="userAddBtn">增加</button> <button type="button" class="btn btn-primary btn-sm" id="userDelBtn">删除</button> </div> </div> <!-- 列表信息 --> <div class="row"> <div class="col-sm-12"> <table class="table table-hover" id="user_table"> <thead> <tr> <th width="20%">id</th> <th width="20%">用户名</th> <th width="20%">密码</th> <th width="20%">年龄</th> <th width="20%">操作</th> </tr> </thead> <tbody></tbody> </table> </div> </div> <!-- 分页 --> <div class="row"> <!-- 分页文字信息 --> <div class="col-sm-3" id="pageInfo_area"></div> <!-- 分页条信息 --> <div class="col-sm-5 col-sm-offset-4" id="pageNav_area"></div> </div> </div> <!-- 新增模态框 --> <div class="modal fade" id="userAddModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"> <div class="modal-dialog" role="document" style="width: 35%"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button> <h5 class="modal-title" id="myModalLabel">新增</h5> </div> <div class="modal-body"> <form class="form-horizontal" id="userAddModalForm"> <div class="form-group"> <label class="col-sm-2 control-label">id</label> <div class="col-sm-8"> <input type="text" class="form-control" name="userId"> </div> </div> <div class="form-group"> <label class="col-sm-2 control-label">用户名</label> <div class="col-sm-8"> <input type="text" class="form-control" name="userName" placeholder="邮箱或手机号"> </div> </div> <div class="form-group"> <label class="col-sm-2 control-label">密码</label> <div class="col-sm-8"> <input type="password" class="form-control" name="userPwd" placeholder="请输入密码"> </div> </div> <div class="form-group"> <label class="col-sm-2 control-label">年龄</label> <div class="col-sm-8"> <input type="text" class="form-control" name="age" placeholder="请输入年龄"> </div> </div> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-default btn-sm" data-dismiss="modal">关闭</button> <button type="button" class="btn btn-primary btn-sm" id="userAddModalSaveBtn">保存</button> </div> </div> </div> </div> </body> </html>
页面样式需做微调
list.css
td,th{ text-align: center; } body{ overflow:-Scroll; overflow-x:hidden; }
编写UserController.java
package com.huaxin.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.huaxin.bean.Msg; import com.huaxin.bean.User; import com.huaxin.logic.UserLogic; @Controller public class UserController { @Autowired private UserLogic userLogic; /** * 分页获取用户信息 * @ResponseBody 需导入jackson包 * @param pn * @return */ @RequestMapping(value="/user",method=RequestMethod.GET) @ResponseBody public Msg getUser( @RequestParam(value="pn",defaultValue="1")Integer pn){// 分页参数 /* 配置分页查询 ** 引入PageHelper分页插件,即pagehelper-5.1.2.jar和jsqlparser-0.9.1.jar ** mybatis.xml中配置分页 ** 调用PageHelper.startPage(pageNum[第几页], pageSize[每页显示多少条数据]); **/ PageHelper.startPage(pn, 7); // startPage后紧跟的查询即为分页查询 List<User> list = userLogic.getUserList(); // 使用pageInfo包装查询后的结果集,封装详细的分页信息,5是连续显示5页 PageInfo pageInfo = new PageInfo(list,5); return Msg.success().add("pageInfo",pageInfo); } @RequestMapping(value="/user",method=RequestMethod.POST) @ResponseBody public Msg addUser(User user){ userLogic.addUser(user); return Msg.success(); } }
在usermapper中新增selectAll方法,查询所有用户信息
sql如下
<select id="selectAll" resultMap="BaseResultMap" parameterType="java.lang.String" > select <include refid="Base_Column_List" /> from user </select>
logic包其实就是service层
UserLogic.java代码如下
package com.huaxin.logic; import java.util.List; import java.util.UUID; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.bind.annotation.RequestParam; import com.huaxin.bean.User; import com.huaxin.dao.UserMapper; @Service public class UserLogic { @Autowired private UserMapper userMapper; /** * 查询用户列表(分页查询) * @return */ public List<User> getUserList(){ return userMapper.selectAll(); } /** * 用户新增 * @param user */ public void addUser(User user) { // id为自动生成的uuid String uid = UUID.randomUUID().toString().replaceAll("-", ""); user.setUserId(uid); userMapper.insertSelective(user); } }
由于前后台使用ajax进行提交
编写list.js
var basePath = getRootPath(); $(function () { // 页面加载完成之后,直接发送ajax请求,要到分页数据 doQuery(1); // 将按钮绑定事件 bindEvent(); }); // 查询方法 function doQuery(pn) { $.ajax({ url:basePath + "/user", data:"pn=" + pn, type:"GET", success:function(result){ //console.log(result); // 解析并显示员工数据 build_user_table(result); // 解析并显示分页信息 build_page_info(result); // 解析并显示分页条 build_page_nav(result); } }); } //新增方法 function doAdd(formData){ alert(formData); $.ajax({ url:basePath + "/user", data:formData, type:"POST", success:function(result){ console.log(result); } }); } // 解析并显示员工数据 function build_user_table(result) { // 清空表格 $("#user_table tbody").empty(); var users = result.data.pageInfo.list; $.each(users,function(index,item){ var userIdTd = $("<td></td>").append(item.userId); var userNameTd = $("<td></td>").append(item.userName); var passwordTd = $("<td></td>").append(item.userPwd); var ageTd = $("<td></td>").append(item.age); var editBtn = $("<button></button>").addClass("btn btn-primary btn-sm") .append($("<span></span>").addClass("glyphicon glyphicon-pencil")) .append("编辑"); var delBtn = $("<button></button>").addClass("btn btn-danger btn-sm") .append($("<span></span>").addClass("glyphicon glyphicon-remove")) .append("删除"); var operate = $("<td></td>").append(editBtn).append(" ").append(delBtn); $("<tr></tr>").append(userIdTd) .append(userNameTd) .append(passwordTd) .append(ageTd) .append(operate) .appendTo("#user_table tbody"); }); } // 解析并显示分页信息 function build_page_info(result){ // 清空 $("#pageInfo_area").empty(); $("#pageInfo_area").append("当前第"+ result.data.pageInfo.pageNum +"页,共"+ result.data.pageInfo.pages +"页," + result.data.pageInfo.total +"条记录"); } // 解析并显示分页条 function build_page_nav(result) { // 清空 $("#pageNav_area").empty(); // nav var pageNav = $("<nav></nav>").attr("aria-label","Page navigation"); // ul var pageUl = $("<ul></ul>").addClass("pagination"); // 首页 var firstPageLi = $("<li></li>").append($("<a></a>").append("首页").attr("href","#")); // 前一页 var previousPageLi = $("<li></li>").append($("<a></a>").append("«").attr("href","#")); // 如果没有前一页,首页和前一页设置为不可点 if(!result.data.pageInfo.hasPreviousPage){ firstPageLi.addClass("disabled"); previousPageLi.addClass("disabled"); }else{ // 点击时发送ajax请求,获取当前页数据 firstPageLi.click(function(){ doQuery(1); }); previousPageLi.click(function(){ doQuery(result.data.pageInfo.pageNum - 1); }); } // 将首页和前一页加入到ul标签中 pageUl.append(firstPageLi).append(previousPageLi); // 遍历得到中间页码号 $.each(result.data.pageInfo.navigatepageNums,function(index,item){ var numsLi = $("<li></li>").append($("<a></a>").append(item).attr("href","#")); // 所在页设置为高亮 if(result.data.pageInfo.pageNum == item){ numsLi.addClass("active"); } // 点击时发送ajax请求,获取当前页数据 numsLi.click(function(){ doQuery(item); }); // 将每个li页加入到ul标签中 pageUl.append(numsLi); }) // 后一页 var NextPageLi = $("<li></li>").append($("<a></a>").append("»").attr("href","#")); // 末页 var lastPageLi = $("<li></li>").append($("<a></a>").append("末页").attr("href","#")); // 如果没有后一页,末页和后一页设置为不可点 if(!result.data.pageInfo.hasNextPage){ NextPageLi.addClass("disabled"); lastPageLi.addClass("disabled"); }else{ // 点击时发送ajax请求,获取当前页数据 NextPageLi.click(function(){ doQuery(result.data.pageInfo.pageNum + 1); }); lastPageLi.click(function(){ doQuery(result.data.pageInfo.pages); }); } // 将后一页和末页加入到ul标签中 pageUl.append(NextPageLi).append(lastPageLi); // 将ul标签加到nav标签中 pageNav.append(pageUl); // 将nav标签加入到指定div中 $("#pageNav_area").append(pageNav); } //获取项目根路径,如: http://localhost:8083/ssm-dynamic function getRootPath(){ //获取当前网址,如: http://localhost:8083/ssm-dynamic/jsp/jsonList.jsp var curWwwPath=window.document.location.href; //获取主机地址之后的目录,如: ssm-dynamic/jsp/jsonList.jsp var pathName=window.document.location.pathname; var pos=curWwwPath.indexOf(pathName); //获取主机地址,如: http://localhost:8080 var localhostPaht=curWwwPath.substring(0,pos); //获取带"/"的项目名,如:/ssm-dynamic var projectName=pathName.substring(0,pathName.substr(1).indexOf('/')+1); return(localhostPaht+projectName); } //将按钮绑定事件 function bindEvent(){ //将新增按钮绑定click事件 $("#userAddBtn").click(function(){ $("#userAddModal").modal({ // 点击背景模态框不关闭 backdrop:"static" }); }) //将删除按钮绑定click事件 $("#userDelBtn").click(function(){ $("#userDelModal").modal({ }); }); //将保存按钮绑定click事件 $("#userAddModalSaveBtn").click(function(){ // 获取页面输入的数据 var formData = $("#userAddModalForm").serialize(); // 执行新增方法 //doAdd(formData); alert(formData); $.ajax({ url:basePath + "/user", data:$("#userAddModalForm").serialize(), type:"POST", success:function(result){ alert(0); } }); }); }
启动项目,目前可显示列表及新增用户
效果如下
点击新增按钮效果图
目前项目进度(2018-1-4):
登录:
未实现功能:保存用户名密码,页面样式
展示页面(分页查询):已完成
新增:只完成了点击保存会插入到数据库,细节部分都没做处理(点击保存关闭弹窗,id设置为隐藏,页面进行长度内容check等)
编辑和删除未完成