最近經過學習別人博客發表的SSM搭建Demo,嘗試去搭建一個簡單的SSMDemo---實現的功能是對用戶增刪改查的操做
參考博客連接javascript
工程結構
src目錄結構
css
工程所需jar包(jar包下載地址)
html
package com.ssm.ljn.user.model; import java.io.Serializable; /** * * <p> * <b>用戶實體類</b></> * * @author Luojiening */ public class User implements Serializable { private int id; private String username; private int age; private String sex; public User() { super(); } public User(int id, String username, int age, String sex) { super(); this.id = id; this.username = username; this.age = age; this.sex = sex; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } }
package com.ssm.ljn.user.dao; import java.util.List; import org.springframework.stereotype.Repository; import com.ssm.ljn.user.model.User; @Repository public interface IUserDao { void saveUser(User user); boolean updateUser(User user); boolean deleteUser(int id); User queryUserById(int id); List<User> queryAllUser(); }
<?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"> <!-- namespace:必須與對應的接口全類名一致 UserMapper.java id :必須與對應接口的某個對應的方法名一致即必需要和UserMapper.java接口中的方法同名。 --> <mapper namespace="com.ssm.ljn.user.dao.IUserDao"> <!-- 新增用戶--> <insert id="saveUser" parameterType="com.ssm.ljn.user.model.User"> insert into User(user_id,user_name,user_age,user_sex) value(#{id},#{username},#{age},#{sex}) </insert> <!-- 修改用戶 --> <update id="updateUser" parameterType="com.ssm.ljn.user.model.User"> update User set user_name=#{username},user_age=#{age},user_sex=#{sex} where user_id=#{id} </update> <!-- 刪除用戶 --> <delete id="deleteUser" parameterType="com.ssm.ljn.user.model.User"> delete from User where user_id = #{id} </delete> <!-- 根據id查找用戶 --> <select id="queryUserById" parameterType="int" resultType="com.ssm.ljn.user.model.User"> select user_id id,user_name username,user_age age,user_sex sex from User where user_id=#{id} </select> <!-- 查詢全部用戶 --> <select id="queryAllUser" resultType="com.ssm.ljn.user.model.User"> select user_id id,user_name userName,user_age age,user_sex sex from User order by id </select> </mapper>
<?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:aop="http://www.springframework.org/schema/aop" 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/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:component-scan base-package="com.ssm.ljn.user" /> <!-- 配置整合mybatis過程 --> <!-- 1.配置數據庫相關參數properties的屬性:${url} --> <context:property-placeholder location="classpath:cfg/jdbc.properties" /> <!-- 2.數據庫鏈接池 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <!-- 配置鏈接池屬性 --> <property name="driverClass" value="${jdbc.driver}"></property> <property name="jdbcUrl" value="${jdbc.url}"></property> <property name="user" value="${jdbc.username}"></property> <property name="password" value="${jdbc.password}"></property> <!-- c3p0鏈接池的私有屬性 --> <property name="maxPoolSize" value="30"></property> <property name="minPoolSize" value="5"></property> <!-- 關閉鏈接後不自動commit --> <property name="autoCommitOnClose" value="false"></property> <!-- 獲取鏈接超時時間 --> <property name="checkoutTimeout" value="10000"></property> <!-- 當獲取鏈接失敗重試次數 --> <property name="acquireRetryAttempts" value="2"></property> </bean> <!-- 3.配置SqlSessionFactory對象 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property> <!-- 指定Mybatis全局配置文件的位置 --> <property name="configLocation" value="classpath:cfg/mybatis.xml"></property> <property name="mapperLocations" value="classpath:com/ssm/ljn/user/model/mybatis/User.xml"></property> </bean> <!-- 配置mybatis的代理接口開發 * 接口類名和映射文件必須同名 * 接口類和映射文件必須在同一個目錄下 * 接口的映射文件的namespace名稱必須是接口的全限定名 * 接口的方法名必須和映射的statement的id一致 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!-- 掃描全部dao接口的實現,加入到ioc容器中 --> <property name="basePackage" value="com.ssm.ljn.user.dao"></property> <property name="SqlSessionFactoryBeanName" value="sqlSessionFactory"></property> </bean> <!--事物 --> <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean> <!-- 配置攔截service --> <aop:config> <aop:pointcut expression="execution(* com.ssm.ljn.user.service.impl.*.*(..))" id="txPoint"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="txPoint"/> </aop:config> <!-- 配置事物加強,事物如何切入--> <tx:advice id="txAdvice" transaction-manager="txManager"> <tx:attributes> <!-- 全部方法都是事物方法 --> <tx:method name="*"/> <!-- 以get開始的全部方法 --> <tx:method name="get*" read-only="true"/> </tx:attributes> </tx:advice> </beans>
<?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> <package name="com.ssm.ljn.*.model"/> </typeAliases> <!-- mybatis分頁插件 --> <plugins> <plugin interceptor="com.github.pagehelper.PageHelper"></plugin> </plugins> </configuration>
<?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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc" 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/aop http://www.springframework.org/schema/aop/spring-aop.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/context/spring-tx.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd "> <!-- 掃描註解包 --> <context:component-scan base-package="com.ssm.ljn.user.action"></context:component-scan> <!-- 配置sprigmvc視圖解析器:解析邏輯試圖 後臺返回邏輯試圖:index 視圖解析器解析出真正物理視圖:前綴+邏輯試圖+後綴====/WEB-INF/page/index.jsp--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/"></property> <property name="suffix" value=".jsp"></property> </bean> <!--1: mvc:annotation-driven默認建立了 RequestMappingHandlerMapping和 RequestMappingHandlerAdapter對象 提供對JSon數據格式的支持--> <mvc:annotation-driven /> <!-- 2.配置靜態資源訪問 --> <mvc:default-servlet-handler/> <!-- 使用CGLib動態代理技術 --> <aop:aspectj-autoproxy proxy-target-class="true" /> </beans>
#jdbc.properties jdbc.driver = com.mysql.jdbc.Driver jdbc.url = jdbc:mysql://127.0.0.1:3306/ssm?useUnicode=true&characterEncoding=utf8&useSSL=false jdbc.username = root jdbc.password = 123456
### set log levels ### log4j.rootLogger = INFO , console , debug , error ### console ### log4j.appender.console = org.apache.log4j.ConsoleAppender log4j.appender.console.Target = System.out log4j.appender.console.layout = org.apache.log4j.PatternLayout log4j.appender.console.layout.ConversionPattern = %-d{yyyy-MM-dd HH\:mm\:ss} [%p]-[%c] %m%n ### log file ### log4j.appender.debug = org.apache.log4j.DailyRollingFileAppender log4j.appender.debug.File = ../logs/springmvc-demo.log log4j.appender.debug.Append = true log4j.appender.debug.Threshold = INFO log4j.appender.debug.layout = org.apache.log4j.PatternLayout log4j.appender.debug.layout.ConversionPattern = %-d{yyyy-MM-dd HH\:mm\:ss} [%p]-[%c] %m%n ### exception ### log4j.appender.error = org.apache.log4j.DailyRollingFileAppender log4j.appender.error.File = ../logs/springmvc-demo_error.log log4j.appender.error.Append = true log4j.appender.error.Threshold = ERROR log4j.appender.error.layout = org.apache.log4j.PatternLayout log4j.appender.error.layout.ConversionPattern = %-d{yyyy-MM-dd HH\:mm\:ss} [%p]-[%c] %m%n ###log4j.error.key not found log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.Target=System.out log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d{ISO8601} %l %c%n%p: %m%n ### druid sql ### log4j.logger.druid.sql=warn,stdout log4j.logger.druid.sql.DataSource=warn,stdout log4j.logger.druid.sql.Connection=warn,stdout log4j.logger.druid.sql.Statement=warn,stdout log4j.logger.druid.sql.ResultSet=warn,stdout
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:web="http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <display-name>SSMDemo</display-name> <!-- 加載Spring容器配置 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:cfg/spring-mybatis.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 配置SpringMVC核心控制器 --> <servlet> <servlet-name>dispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:cfg/springmvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <!-- 攔截全部請求 --> <servlet-mapping> <servlet-name>dispatcherServlet</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> </filter> <filter-mapping> <filter-name>CharacterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
package com.ssm.ljn.user.service; import java.util.List; import org.springframework.stereotype.Service; import com.ssm.ljn.user.model.User; public interface IUserService { void saveUser(User user); boolean updateUser(User user); boolean deleteUser(int id); User queryUserById(int id); List<User> queryAllUser(); }
package com.ssm.ljn.user.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.ssm.ljn.user.dao.IUserDao; import com.ssm.ljn.user.model.User; import com.ssm.ljn.user.service.IUserService; @Service("userService") @Transactional public class UserService implements IUserService{ @Autowired private IUserDao iUserDao; @Override public void saveUser(User user) { iUserDao.saveUser(user); } @Override public boolean updateUser(User user) { return iUserDao.updateUser(user); } @Override public boolean deleteUser(int id) { return iUserDao.deleteUser(id); } @Override public User queryUserById(int id) { return iUserDao.queryUserById(id); } @Override public List<User> queryAllUser() { return iUserDao.queryAllUser(); } }
package com.ssm.ljn.user.action; import java.util.List; 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.RequestParam; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.ssm.ljn.user.model.User; import com.ssm.ljn.user.service.IUserService;; @Controller @RequestMapping("/user") public class UserAction { @Autowired private IUserService iUserService; /** *跳轉到添加用戶界面 */ @RequestMapping("toAddUser") public String toAddUser(){ return "addUser"; } /** * 添加用戶並重定向 * @param model * @param user * @return */ @RequestMapping("addUser") public String addUser(Model model,User user){ if(user != null){ iUserService.saveUser(user); } return "redirect:/user/userInfo"; } /** * 修改用戶 * @param model * @param request * @param user * @return */ @RequestMapping("updateUser") public String UpdateUser(Model model,User user){ if(iUserService.updateUser(user)){ user = iUserService.queryUserById(user.getId()); model.addAttribute("user", user); return "redirect:/user/userInfo"; } return "/error"; } /** * 查詢全部用戶 * @param request * @param model * @return */ @RequestMapping("getAllUser") public String getAllUser(Model model){ List<User> user = iUserService.queryAllUser(); model.addAttribute("userList",user); return "allUser"; } /** * 查詢單個用戶 * @param id * @param request * @param model * @return */ @RequestMapping("/getUser") public String getUser(int id,Model model){ model.addAttribute("user", iUserService.queryUserById(id)); return "editUser"; } /** * 根據id刪除用戶 * @param id * @param request * @param response */ @RequestMapping("/delUser") public String deleteUser(int id,Model model){ model.addAttribute("user", iUserService.deleteUser(id)); return "redirect:/user/userInfo"; } @RequestMapping("userInfo") public String getUsers(@RequestParam(value="pn",defaultValue="1")Integer pn,Model model){ //從第一條開始 每頁查詢五條數據 PageHelper.startPage(pn, 5); List<User> users = iUserService.queryAllUser(); //將用戶信息放入PageInfo對象裏 PageInfo page = new PageInfo(users,5); model.addAttribute("pageInfo", page); return "allUser"; } }
WebContent目錄結構
java
index界面mysql
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <% pageContext.setAttribute("path", request.getContextPath()); %> <!DOCTYPE htm > <html> <head> <title>首頁</title> <style type="text/css"> a { text-decoration: none; color: #fff; font-size: 14px; } h3 { width: 180px; height: 38px; margin: 100px auto; text-align: center; line-height: 38px; background: #5BC0DE; border-radius: 4px; } </style> </head> <body> <h3> <a href="${path }/user/userInfo">進入用戶管理頁</a> </h3> </body> </html>
jsp頁面主要有顯示全部用戶、新增用戶以及修改用戶三部分組成
allUser.jspjquery
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <% pageContext.setAttribute("path", request.getContextPath()); %> <!DOCTYPE HTML> <html> <head> <title>用戶列表</title> <link href="${path}/resource/css/bootstrap.min.css" rel="stylesheet"> <script type="text/javascript" src="${path}/resource/js/jquery-1.9.1.min.js"></script> <script type="text/javascript" src="${path}/resource/js/bootstrap.min.js"></script> </head> <body> <div class="container"> <!-- 標題 --> <div class="row"> <div class="col-md-12"> <h1>用戶管理</h1> </div> </div> <!-- 按鈕 --> <div class="row"> <div class="col-md-4 col-md-offset-8"> <a class="btn btn-primary" href="${path}/user/toAddUser">新增</a> </div> </div> <!-- 表格 --> <div class="row"> <div class="col-md-12"> <table class="table table-hover"> <tr> <th>id</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.sex }</td> <!-- <td><a class="edit">編輯</a> <a class="delete">刪除</a></td> --> <td> <a type="button" href="${path}/user/getUser?id=${user.id}" class="btn btn-info btn-sm"> <span class="glyphicon glyphicon-pencil" aria-hidden="true"></span> 編輯</a> <a type="button" href="${path}/user/delUser?id=${user.id}" class="btn btn-danger btn-sm"> <span class="glyphicon glyphicon-trash" aria-hidden="true" ></span> 刪除</a> </td> </tr> </c:forEach> </table> </div> </div> <hr style="height:1px;border:none;border-top:1px solid #ccc;" /> <!-- 分頁導航欄 --> <!-- 分頁信息 --> <div class="row"> <!-- 分頁文字信息,其中分頁信息都封裝在pageInfo中 --> <div class="col-md-6"> 當前第:${pageInfo.pageNum}頁,總共:${pageInfo.pages}頁,總共:${pageInfo.total}條記錄 </div> <!-- 分頁條 --> <div class="col-md-6"> <nav aria-label="Page navigation"> <ul class="pagination"> <li><a href="${path}/user/userInfo?pn=1">首頁</a></li> <c:if test="${pageInfo.hasPreviousPage }"> <li> <a href="${path}/user/userInfo?pn=${pageInfo.pageNum-1}" aria-label="Previous"> <span aria-hidden="true">«</span> </a> </li> </c:if> <c:forEach items="${pageInfo.navigatepageNums }" var="page_Num"> <c:if test="${page_Num == pageInfo.pageNum }"> <li class="active"><a href="#">${ page_Num}</a></li> </c:if> <c:if test="${page_Num != pageInfo.pageNum }"> <li><a href="${path}/user/userInfo?pn=${ page_Num}">${ page_Num}</a></li> </c:if> </c:forEach> <c:if test="${pageInfo.hasNextPage }"> <li> <a href="${path}/user/userInfo?pn=${pageInfo.pageNum+1}" aria-label="Next"> <span aria-hidden="true">»</span> </a> </li> </c:if> <li><a href="${path}/user/userInfo?pn=${pageInfo.pages}">末頁</a></li> </ul> </nav> </div> </div> </div> </body> </html>
editUser.jspgit
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; %> <!DOCTYPE html> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <html> <head> <title>編輯用戶</title> <script type="text/javascript"> function updateUser() { var form = document.forms[0]; form.action = "<%=basePath %>user/updateUser"; form.method = "post"; form.submit(); } </script> </head> <body> <h1>添加用戶</h1> <form action="" name="userForm"> <input type="hidden" name="id" value="${user.id }" /> 姓名:<input type="text" name="username" value="${user.username }" /> 年齡:<input type="text" name="age" value="${user.age }" /> 性別:<input type="text" name="sex" value="${user.sex }" /> <input type="button" value="編輯" onclick="updateUser()" /> </form> </body> </html>
addUser.jspgithub
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; %> <html> <title>添加用戶</title> </head> <body> <h1>添加用戶</h1> <form action="" name="userForm"> id:<input type="text" name="id"><br> 姓名:<input type="text" name="username"><br> 年齡:<input type="text" name="age"><br> 性別:<input type="text" name="sex"><br> <input type="button" value="添加" onclick="addUser()"> </form> <script type="text/javascript"> function addUser() { var form = document.forms[0]; form.action = "<%=basePath %>user/addUser"; form.method = "post"; form.submit(); } </script> </body> </html>
數據庫建表語句,相對較爲簡單,也沒有任何的約束條件web
CREATE TABLE `user` ( `user_id` int(50) NOT NULL, `user_name` varchar(20) DEFAULT NULL, `user_age` int(10) DEFAULT NULL, `user_sex` varchar(2) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
在參考實現過程當中遇到不少的問題,有的是jar的缺失引發的,有的是路徑錯誤引發的,主要經過百度相關異常從而找到相應的解決方法。
最後,用戶增刪改查的界面調試成功
spring