SSM框架之动态代理Mapper快速搭建
1. 新建Maven项目 ssmnew
2. pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.java</groupId> <artifactId>ssmnew</artifactId> <version>1.0.0-SNAPSHOT</version> <packaging>war</packaging> <name>${project.artifactId}</name> <url>http://maven.apache.org</url> <!-- 配置版本常量 --> <properties> <jdk.version>1.8</jdk.version> <spring.version>3.2.18.RELEASE</spring.version> <mybatis.version>3.4.6</mybatis.version> </properties> <dependencies> <!-- Spring --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.9.7</version> </dependency> <!-- MyBatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.2</version> </dependency> <!-- 连接池 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.11</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.47</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.8.13</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</version> <scope>provided</scope> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.3</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.49</version> </dependency> </dependencies> <build> <finalName>${project.artifactId}</finalName> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.0</version> <configuration> <source>${jdk.version}</source> <target>${jdk.version}</target> <encoding>UTF-8</encoding> </configuration> </plugin> </plugins> </build> </project>
3. web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5"> <display-name>ssmnew</display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <context-param> <param-name>webAppRootKey</param-name> <param-value>ssmnew</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <servlet> <servlet-name>ssmnew</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc-servlet.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>ssmnew</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>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>characterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <listener> <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class> </listener> <context-param> <param-name>log4jConfigLocation</param-name> <param-value>classpath:log4j.properties</param-value> </context-param> <session-config> <session-timeout>30</session-timeout> </session-config> </web-app>
4. /ssmnew/src/main/resources 目录下文件
5. 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: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/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <context:property-placeholder location="classpath:param.properties" /> <!-- 配置连接池 --> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <property name="driverClassName" value="${jdbc.driver}" /> <property name="initialSize" value="5" /> <property name="maxActive" value="20" /> </bean> <!-- 配置数据库会话工厂 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> </bean> <!-- 配置映射包扫描路径 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.java.mapper" /> </bean> <!-- 配置事务管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <!-- 配置通知 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="get*" read-only="true" /> <tx:method name="find*" read-only="true" /> <tx:method name="query*" read-only="true" /> <tx:method name="add*" propagation="REQUIRED" read-only="false" rollback-for="Exception" /> <tx:method name="save*" propagation="REQUIRED" read-only="false" rollback-for="Exception" /> <tx:method name="insert*" propagation="REQUIRED" read-only="false" rollback-for="Exception" /> <tx:method name="update*" propagation="REQUIRED" read-only="false" rollback-for="Exception" /> <tx:method name="delete*" propagation="REQUIRED" read-only="false" rollback-for="Exception" /> <tx:method name="*" propagation="REQUIRES_NEW" read-only="false" rollback-for="Exception" /> </tx:attributes> </tx:advice> <!-- 将事务作用到service包下所有类的所有方法 --> <aop:config> <aop:pointcut id="pointcut" expression="execution(* com.java.service..*.*(..))" /> <aop:advisor pointcut-ref="pointcut" advice-ref="txAdvice" /> </aop:config> <!-- 注解方式管理事务,需要在类上使用注解@Transactional --> <tx:annotation-driven transaction-manager="transactionManager" /> <context:component-scan base-package="com.java.service.impl" /> <context:annotation-config /> </beans>
6. springmvc-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:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" 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/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- 前缀 --> <property name="prefix" value="/WEB-INF/views/" /> <!-- 后缀 --> <property name="suffix" value=".jsp" /> </bean> <!-- 上传文件 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize" value="4294967296"></property> </bean> <!-- 配置资源 --> <mvc:resources location="/WEB-INF/assets/" mapping="/assets/**"></mvc:resources> <mvc:annotation-driven> <mvc:message-converters register-defaults="true"> <bean class="org.springframework.http.converter.StringHttpMessageConverter"> <constructor-arg value="UTF-8" /> </bean> </mvc:message-converters> </mvc:annotation-driven> <context:component-scan base-package="com.java.controller" /> <context:annotation-config /> </beans>
7. param.properties
jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://192.168.32.20:3306/ssmnew?useUnicode=true&characterEncoding=UTF-8 jdbc.username=root jdbc.password=123456
8. log4j.properties
log4j.rootLogger= INFO, stdout
log4j.logger.INFO=INFO,logfile
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH\:mm\:ss.SSS} [%5p] [%c] - %m%n
log4j.appender.logfile=org.apache.log4j.DailyRollingFileAppender
log4j.appender.logfile.File=G:/Java/logs/ssmnew/LogFile.log
log4j.appender.logfile.DatePattern='_'yyyy-MM-dd'.log'
log4j.appender.logfile.Threshold=INFO
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d{yyyy-MM-dd HH\:mm\:ss} [%5p] - %m%n
log4j.appender.logfile.Append=true
9. 创建数据库
DROP DATABASE IF EXISTS ssmnew; CREATE DATABASE ssmnew; USE ssmnew; DROP TABLE IF EXISTS `user`; CREATE TABLE `user` ( `id` varchar(32) NOT NULL, `username` varchar(32) NOT NULL, `password` varchar(32) NOT NULL, `age` int(3) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; ;
10. User.java
package com.java.pojo; public class User { private String id; private String username; private String password; private Integer age; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } @Override public String toString() { return "User [id=" + id + ", username=" + username + ", password=" + password + ", age=" + age + "]"; } }
11. UserMapper.java
package com.java.mapper; import java.util.List; import com.java.pojo.User; public interface UserMapper { Integer checkLogin(User user); List<User> findUserList(User user); void addUser(User user); void updateUser(User user); void deleteUser(User user); }
12. UserMapper.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.java.mapper.UserMapper"> <!-- 配置数据库字段和实体类映射 --> <resultMap id="userMap" type="com.java.pojo.User"> <id property="id" column="id" /> <result property="username" column="username" /> <result property="password" column="password" /> <result property="age" column="age" /> </resultMap> <!-- 检查登录 --> <select id="checkLogin" parameterType="com.java.pojo.User" resultType="java.lang.Integer"> select 1 from user where username=#{username} and password=#{password} </select> <!-- 查询用户列表 --> <select id="findUserList" parameterType="com.java.pojo.User" resultType="com.java.pojo.User"> select id,username,password,age from user </select> <!-- 新增用户 --> <insert id="addUser" parameterType="com.java.pojo.User" > <selectKey keyProperty="id" order="BEFORE" resultType="java.lang.String"> select replace(uuid(), '-', '') as id from dual </selectKey> insert into user(id,username,password,age) values(#{id},#{username},#{password},#{age}); </insert> <!-- 修改用户信息 --> <update id="updateUser" parameterType="com.java.pojo.User" > update user set username=#{username}, password=#{password}, age=#{age} where id=#{id} </update> <!-- 根据id删除用户 --> <delete id="deleteUser" parameterType="java.lang.String"> delete from user where id=#{id} </delete> </mapper>
13. UserService.java
package com.java.service; import java.util.List; import com.java.pojo.User; public interface UserService { Integer checkLogin(User user); List<User> findUserList(User user); void addOrUpdateUser(User user); void deleteUser(User user); }
14. UserServiceImpl.java
package com.java.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.java.mapper.UserMapper; import com.java.pojo.User; import com.java.service.UserService; @Service("userService") public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; @Override public Integer checkLogin(User user) { return userMapper.checkLogin(user); } @Override public List<User> findUserList(User user) { return userMapper.findUserList(user); } @Override public void addOrUpdateUser(User user) { if (null == user.getId() || user.getId().isEmpty()) { userMapper.addUser(user); } else { userMapper.updateUser(user); } } @Override public void deleteUser(User user) { userMapper.deleteUser(user); } }
15. UserController.java
package com.java.controller; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; 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 org.springframework.web.bind.annotation.ResponseBody; import com.java.pojo.User; import com.java.service.UserService; @Controller @Scope("prototype") @RequestMapping("/user") public class UserController { private static final Log LOG = LogFactory.getLog("INFO"); @Autowired private UserService userService; @RequestMapping("/login") public String login(@ModelAttribute User user, Model model) { LOG.info("Into login"); System.out.println(user); // 检查用户名密码是否存在 Integer result = userService.checkLogin(user); System.out.println("result: " + result); LOG.info("result: " + result); // 绑定用户名密码输出返回 if (null == result) { model.addAttribute("username", user.getUsername()); model.addAttribute("password", user.getPassword()); return "user/Login"; } LOG.info("Exit login"); return "user/Main"; } @ResponseBody @RequestMapping("/findUserList") public List<User> findUserList(@ModelAttribute User user) { LOG.info("Into findUserList"); System.out.println(user); List<User> list = userService.findUserList(user); LOG.info("Exit findUserList"); return list; } @RequestMapping("/toAddOrUpdateUser") public String toAddOrUpdateUser(@ModelAttribute User user, Model model) { LOG.info("Into toAddOrUpdateUser"); System.out.println("user: " + user); // 输出id,根据id是否为空,判断是新增还是修改 model.addAttribute("user", user); LOG.info("Exit toAddOrUpdateUser"); return "user/AddOrUpdateUser"; } @RequestMapping("/addOrUpdateUser") public String addOrUpdateUser(@ModelAttribute User user) { LOG.info("Into addOrUpdateUser"); System.out.println("user: " + user); userService.addOrUpdateUser(user); System.out.println(user); LOG.info("Exit addOrUpdateUser"); return "user/Main"; } @ResponseBody @RequestMapping("/deleteUser") public String deleteUser(@ModelAttribute User user) { System.out.println(user); LOG.info("Into deleteUser"); userService.deleteUser(user); LOG.info("Exit deleteUser"); return "删除成功!"; } }
16. 页面文件结构
index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; %> <!DOCTYPE html> <html> <head> <base href="<%=basePath%>"> <title>登录</title> <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> <script type="text/javascript"> function addUser() { location.href = "user/toAddOrUpdateUser"; } </script> </head> <body> <form action="user/login" method="post"> <table> <tr> <td>用户名:</td> <td><input name="username" /><br /></td> </tr> <tr> <td>密码:</td> <td><input type="password" name="password" /><br /></td> </tr> <tr> <td><input type="submit" value="登录" /></td> <td><input type="button" value="注册" onclick="addUser();" /></td> </tr> </table> </form> </body> </html>
Login.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; %> <!DOCTYPE html> <html> <head> <base href="<%=basePath%>"> <title>登录</title> <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> <script type="text/javascript"> function addUser() { location.href = "user/toAddOrUpdateUser"; } </script> </head> <body> <form action="user/login" method="post"> <table> <tr> <td>用户名:</td> <td><input name="username" value="${username}" /><br /></td> </tr> <tr> <td>密码:</td> <td><input type="password" name="password" value="${password}" /><br /></td> </tr> <tr> <td><input type="submit" value="登录" /></td> <td><input type="button" value="注册" onclick="addUser();" /></td> </tr> </table> </form> </body> </html>
Main.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; %> <!DOCTYPE html> <html> <head> <base href="<%=basePath%>"> <title>主页</title> <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> <script src="assets/js/jquery-1.11.3.js"></script> <style type="text/css"> td, th { border: 1px solid #AAA; } </style> <script type="text/jscript"> $(function() { queryUserList(); }); function queryUserList() { $.post("user/findUserList", {id: 1}, function(userList) { /* var userList = eval("(" + userList + ")"); */ var line = null; $("#list").empty(); for(var i in userList) { line = tr(td(userList[i].id) + td(userList[i].username) + td(userList[i].password) + td(userList[i].age) + td(addBtn() + delBtn())); $("#list").append(line); } }); } function tr(text) { return "<tr>" + text + "</tr>"; } function td(text) { if(!text) { text = ""; } return "<td>" + text + "</td>"; } function addBtn() { return "<button onClick='update(this);'>修改</button>"; } function delBtn() { return "<button onClick='deleteUser(this);'>删除</button>"; } function update(obj) { var row = getRow(obj); var user = { id: row.eq(0).text(), username: row.eq(1).text(), password: row.eq(2).text(), age: row.eq(3).text() } var form = document.createElement("form"); form.action = "user/toAddOrUpdateUser"; form.method = "post"; var input = null; for(var key in user) { input = document.createElement("input"); input.type = "hidden"; input.name = key; input.value = user[key]; form.appendChild(input) } document.body.appendChild(form); form.submit(); } function deleteUser(obj) { var row = getRow(obj); var id = row.eq(0).text(); $.post("user/deleteUser", {id: id}, function(data) { alert(data); queryUserList(); }); } function getRow(obj) { return $(obj).parent().parent().children(); } </script> </head> <body> <button onClick="location.href='user/toAddOrUpdateUser'">新增</button> <div> <table style="border-collapse: collapse;width: 800px;"> <thead> <tr> <th>ID</th> <th>用户名</th> <th>密码</th> <th>年龄</th> <th>操作</th> </tr> </thead> <tbody id="list"> </tbody> </table> </div> </body> </html>
AddOrUpdateUser.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; %> <!DOCTYPE html> <html> <head> <base href="<%=basePath%>"> <title>新增用户</title> <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> </head> <body> <form action="user/addOrUpdateUser" method="post"> <input name="id" value="${user.id}" type="hidden"/> <table> <tr> <td>用户名:</td> <td><input type="text" name="username" value="${user.username}" /><br /></td> </tr> <tr> <td>密码:</td> <td><input type="password" name="password" value="${user.password}" /><br /></td> </tr> <tr> <td>年龄:</td> <td><input type="text" name="age" value="${user.age}" /><br /></td> </tr> <tr> <td colspan="2"><input type="submit" value="提交" /></td> </tr> </table> </form> </body> </html>
注意:
jquery-1.11.3.js 请自行下载,配置到Main.jsp文件中
https://code.jquery.com/jquery-1.11.3.js
https://code.jquery.com/jquery-1.11.3.min.js
配置完成!
.