Maven+SSM框架实现简单的增删改查
Spring介绍:
spring 使用基本的 JavaBean 来完成以前只可能由 EJB 完成的事情。然而, Spring的用途不仅限于服务器端的开发。从简单性、可测试性和松耦合的角度而言,任何Java 应用都可以从 Spring 中受益。 简单来说, Spring 是一个轻量级的控制反转(IoC )和面向切面( AOP )的容器框架。
SpringMVC介绍
MyBatis介绍
创建数据库、表db_zsl t_user user_t【最下面有sql语句】
1.项目整体结构
2.添加相关jar 包
3.项目整体结构出来了
4.创建model【User】
- package com.lyt.model;
- /**
- * 用户
- * @author
- *
- */
- public class User {
- private int id;
- private String userName;
- private String age;
- @Override
- public String toString() {
- return "User [id=" + id + ", age=" + age + ", userName=" + userName
- + "]";
- }
- public User(){
- super();
- }
- public int getId() {
- return id;
- }
- public void setId(int id) {
- this.id = id;
- }
- public String getAge() {
- return age;
- }
- public void setAge(String age) {
- this.age = age;
- }
- public String getUserName() {
- return userName;
- }
- public void setUserName(String userName) {
- this.userName = userName;
- }
- public User(int id, String age, String userName) {
- super();
- this.id = id;
- this.age = age;
- this.userName = userName;
- }
- }
5.创建DAO接口【在mybatis中 mapper就相当于dao】
- package com.lyt.mapper;
- import java.util.List;
- import com.lyt.model.User;
- /**
- * 做为 DAO的接口
- * @author
- */
- public interface UserMapper {
- void save(User user);
- boolean update(User user);
- boolean delete(int id);
- User findById(int id);
- List<User> findAll();
- }
- 5.创建DAO接口【在mybatis中 mapper就相当于dao】
- package com.lyt.mapper;
- import java.util.List;
- import com.lyt.model.User;
- /**
- * 做为 DAO的接口
- * @author */
- public interface UserMapper {
- void save(User user);
- boolean update(User user);
- boolean delete(int id);
- User findById(int id);
- List<User> findAll();
- }
6.实现dao接口【mybatis中就是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">
- <!--
- namespace:必须与对应的接口全类名一致 UserMapper.java
- id :必须与对应接口的某个对应的方法名一致即必须要和UserMapper.java接口中的方法同名。
- -->
- <mapper namespace="com.lyt.mapper.UserMapper">
- <insert id="save" parameterType="User">
- insert into t_user(user_name,user_age) values(#{userName},#{age})
- </insert>
- <update id="update" parameterType="User">
- update t_user set user_name=#{userName},user_age=#{age} where user_id=#{id}
- </update>
- <delete id="delete" parameterType="int">
- delete from t_user where user_id=#{id}
- </delete>
- <!-- mybsits_config中配置的alias类别名,也可直接配置resultType为类路径 -->
- <select id="findById" parameterType="int" resultType="User">
- select user_id id,user_name userName,user_age age from t_user where user_id=#{id}
- </select>
- <select id="findAll" resultType="User">
- select user_id id,user_name userName,user_age age from t_user
- </select>
- </mapper>
这里对这个xml文件作几点说明:
1、namespace必须与对应的接口全类名一致。
2、id必须与对应接口的某个对应的方法名一致即必须要和UserMapper.java接口中的方法同名。
7.mybatis与Spring整合【spring-common.xml】放在src的根目录下
对于Mybatis和Spring的整合是这篇博文的重点,需要配置的内容在下面有详细的解释。
- <?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:p="http://www.springframework.org/schema/p"
- xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
- xsi:schemaLocation="
- http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-4.0.xsd
- http://www.springframework.org/schema/tx
- http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
- <!-- Mybatis和Spring的整合 -->
- <!-- 1. 数据源 : DriverManagerDataSource -->
- <bean id="dataSource"
- class="org.springframework.jdbc.datasource.DriverManagerDataSource">
- <property name="driverClassName" value="com.mysql.jdbc.Driver" />
- <property name="url" value="jdbc:mysql://localhost:3306/db_zsl" />
- <property name="username" value="root" />
- <property name="password" value="root" />
- </bean>
- <!--
- 2. mybatis的SqlSession的工厂: SqlSessionFactoryBean dataSource:引用数据源
- MyBatis定义数据源,同意加载配置
- -->
- <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
- <property name="dataSource" ref="dataSource"></property>
- <property name="configLocation" value="classpath:mybatis-config.xml" />
- </bean>
- <!--
- 3. mybatis自动扫描加载Sql映射文件/接口 : MapperScannerConfigurer sqlSessionFactory
- basePackage:指定sql映射文件/接口所在的包(自动扫描)
- -->
- <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
- <property name="basePackage" value="com.lyt.mapper"></property>
- <property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
- </bean>
- <!--
- 4. 事务管理 : DataSourceTransactionManager dataSource:引用上面定义的数据源
- -->
- <bean id="txManager"
- class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
- <property name="dataSource" ref="dataSource"></property>
- </bean>
- <!-- 5. 使用声明式事务
- transaction-manager:引用上面定义的事务管理器
- -->
- <tx:annotation-driven transaction-manager="txManager" />
- </beans>
- 8.mybatis配置文件【mybatis-config.xml】放在src目录下
- <?xml version="1.0" encoding="UTF-8"?>
- <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
- "http://mybatis.org/dtd/mybatis-3-config.dtd">
- <configuration>
- <!-- 实体类,简称 -设置别名 -->
- <typeAliases>
- <typeAlias alias="User" type="com.lyt.model.User" />
- </typeAliases>
- <!-- 实体接口映射资源 -->
- <!--
- 说明:如果xxMapper.xml配置文件放在和xxMapper.java统一目录下,mappers也可以省略,因为org.mybatis.spring.mapper.MapperFactoryBean默认会去查找与xxMapper.java相同目录和名称的xxMapper.xml
- -->
- <mappers>
- <mapper resource="com/lyt/mapper/userMapper.xml" />
- </mappers>
- </configuration>
-
配置log4j.properties
- ### set log levels ###
- log4j.rootLogger = info , Console , D
- #Console
- log4j.appender.Console=org.apache.log4j.ConsoleAppender
- log4j.appender.Console.layout=org.apache.log4j.PatternLayout
- log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n
- log4j.logger.java.sql.ResultSet=INFO
- log4j.logger.org.apache=INFO
- log4j.logger.java.sql.Connection=INFO
- log4j.logger.java.sql.Statement=INFO
- log4j.logger.java.sql.PreparedStatement=INFO
- #output2file
- log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
- log4j.appender.D.File = D\:/logs/log.log
- log4j.appender.D.Append = true
- log4j.appender.D.Threshold = INFO \#\# \u00E8\u00BE\u0093\u00E5\u0087\u00BAinfo\u00E7\u00BA\u00A7\u00E5\u0088\u00AB\u00E4\u00BB\u00A5\u00E4\u00B8\u008A\u00E7\u009A\u0084\u00E6\u0097\u00A5\u00E5\u00BF\u0097
- log4j.appender.D.layout = org.apache.log4j.PatternLayout
- log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH\:mm\:ss} [ %t\:%r ] - [ %p ] %m%n
10.整合Springmvc
配置【spring-mvc.xml】放在src根目录下
- <?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"
- 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-4.0.xsd
- http://www.springframework.org/schema/mvc
- http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
- <!-- 注解扫描包 -->
- <context:component-scan base-package="com.lyt.controller" />
- <context:component-scan base-package="com.lyt.service" />
- <!-- 开启注解 -->
- <mvc:annotation-driven />
- <!--
- 配置静态资源,直接映射到对应的文件夹,不被DispatcherServlet处理,3.04新增功能,需要重新设置spring-mvc-3.0.xsd
- -->
- <mvc:resources mapping="/img/**" location="/img/" />
- <mvc:resources mapping="/js/**" location="/js/" />
- <mvc:resources mapping="/css/**" location="/css/" />
- <mvc:resources mapping="/html/**" location="/html/" />
- <!-- 定义跳转的文件的前后缀 ,视图模式配置-->
- <bean id="viewResolver"
- class="org.springframework.web.servlet.view.InternalResourceViewResolver">
- <!-- 这里的配置我的理解是自动给后面action的方法return的字符串加上前缀和后缀,变成一个 可用的url地址 -->
- <property name="prefix" value="/WEB-INF/jsp/" />
- <property name="suffix" value=".jsp" />
- </bean>
- </beans>
- 11.配置web.xml
- <?xml version="1.0" encoding="UTF-8"?>
- <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
- http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
- <!-- 加载Spring容器配置 -->
- <listener>
- <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
- </listener>
- <!-- 设置Spring容器加载所有的配置文件的路径 -->
- <context-param>
- <param-name>contextConfigLocation</param-name>
- <!-- <param-value>classpath:config/spring-*.xml</param-value> -->
- <param-value>classpath:spring-common.xml,classpath:spring-mvc.xml</param-value>
- </context-param>
- <!-- 配置SpringMVC核心控制器 -->
- <servlet>
- <servlet-name>springMVC</servlet-name>
- <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
- <!-- 配置初始配置化文件,前面contextConfigLocation看情况二选一 -->
- <init-param>
- <param-name>contextConfigLocation</param-name>
- <param-value>classpath:spring-common.xml,classpath:spring-mvc.xml</param-value>
- </init-param>
- <!-- 启动加载一次 -->
- <load-on-startup>1</load-on-startup>
- </servlet>
- <!--为DispatcherServlet建立映射 -->
- <servlet-mapping>
- <servlet-name>springMVC</servlet-name>
- <!-- 此处可以可以配置成*.do,对应struts的后缀习惯 -->
- <url-pattern>/</url-pattern>
- </servlet-mapping>
- <!-- 防止Spring内存溢出监听器 -->
- <listener>
- <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
- </listener>
- <!-- 解决工程编码过滤器 -->
- <filter>
- <filter-name>encodingFilter</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>encodingFilter</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
- <welcome-file-list>
- <welcome-file>index.jsp</welcome-file>
- </welcome-file-list>
- </web-app>
- 12.建立service以及service实现【UserService.java】
- package com.lyt.service;
- import java.util.List;
- import com.lyt.model.User;
- public interface UserService {
- void save(User user);
- boolean update(User user);
- boolean delete(int id);
- User findById(int id);
- List<User> findAll();
- }
【UserServiceImpl.java】
- package com.lyt.service.impl;
- import java.util.List;
- import javax.annotation.Resource;
- import org.springframework.stereotype.Service;
- import org.springframework.transaction.annotation.Transactional;
- import com.lyt.mapper.UserMapper;
- import com.lyt.model.User;
- import com.lyt.service.UserService;
- @Service
- @Transactional
- // 此处不再进行创建SqlSession和提交事务,都已交由spring去管理了。
- public class UserServiceImpl implements UserService {
- @Resource
- private UserMapper mapper;
- /**
- * 根据 id 删除 数据
- */
- public boolean delete(int id) {
- return mapper.delete(id);
- }
- /**
- * 查询User的全部数据
- */
- public List<User> findAll() {
- List<User> findAllList = mapper.findAll();
- return findAllList;
- }
- /**
- * 根据 id 查询 对应数据
- */
- public User findById(int id) {
- User user = mapper.findById(id);
- return user;
- }
- /**
- * 新增数据
- */
- public void save(User user) {
- mapper.save(user);
- }
- /**
- * 根据 id 修改对应数据
- */
- public boolean update(User user) {
- return mapper.update(user);
- }
- }
13.建立Controller【UserController.java】
- <span style="font-size:14px;">package com.lyt.controller;
- import java.io.IOException;
- import java.io.PrintWriter;
- import java.util.List;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- 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 com.lyt.model.User;
- import com.lyt.service.UserService;
- @Controller
- @RequestMapping("/user")
- public class UserController {
- @Autowired
- private UserService userService;
- /**
- * 获取所有用户列表
- * @param request
- * @return
- */
- @RequestMapping("/getAllUser")
- public String getAllUser(HttpServletRequest request,Model model){
- List<User> user = userService.findAll();
- model.addAttribute("userList", user);
- request.setAttribute("userList", user);
- return "/allUser";
- }
- /**
- * 跳转到添加用户界面
- * @param request
- * @return
- */
- @RequestMapping("/toAddUser")
- public String toAddUser(){
- return "/addUser";
- }
- /**
- * 添加用户并重定向
- * @param user
- * @param request
- * @return
- */
- @RequestMapping("/addUser")
- public String addUser(User user,Model model){
- userService.save(user);
- return "redirect:/user/getAllUser";
- }
- /**
- *编辑用户
- * @param user
- * @param request
- * @return
- */
- @RequestMapping("/updateUser")
- public String updateUser(User user,HttpServletRequest request,Model model){
- if(userService.update(user)){
- user = userService.findById(user.getId());
- request.setAttribute("user", user);
- model.addAttribute("user", user);
- return "redirect:/user/getAllUser";
- }else{
- return "/error";
- }
- }
- /**
- * 根据id查询单个用户
- * @param id
- * @param request
- * @return
- */
- @RequestMapping("/getUser")
- public String getUser(int id,HttpServletRequest request,Model model){
- request.setAttribute("user", userService.findById(id));
- model.addAttribute("user", userService.findById(id));
- return "/editUser";
- }
- /**
- * 删除用户
- * @param id
- * @param request
- * @param response
- */
- @RequestMapping("/delUser")
- public void delUser(int id,HttpServletRequest request,HttpServletResponse response){
- String result = "{\"result\":\"error\"}";
- if(userService.delete(id)){
- result = "{\"result\":\"success\"}";
- }
- response.setContentType("application/json");
- try {
- PrintWriter out = response.getWriter();
- out.write(result);
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- </span>
至此 大部分架构以及代码已经搭建完成
我们来做前台页面--修改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 PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <base href="<%=basePath%>">
- <title>首页</title>
- </head>
- <body>
- <h5>
- <a href="<%=basePath%>user/getAllUser">进入用户管理页</a>
- </h5>
- </body>
- </html>
在 WEB-INF 下新建jsp文件夹【里面新建以下文件】【addUser.jsp】【allUser.jsp】【editUser.jsp】addUser.jsp内容
- <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
- <%
- String path = request.getContextPath();
- String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
- %>
- <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <base href="<%=basePath%>">
- <title>添加用户</title>
- <script type="text/javascript">
- function addUser(){
- var form = document.forms[0];
- form.action = "<%=basePath%>user/addUser";
- form.method="post";
- form.submit();
- }
- </script>
- </head>
- <body>
- <h1><%=path%>添加用户<%=basePath%></h1>
- <form action="" name="userForm">
- 姓名:<input type="text" name="userName">
- 年龄:<input type="text" name="age">
- <input type="button" value="添加" onclick="addUser()">
- </form>
- </body>
- </html>
allUser.jsp- <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
- <%
- String path = request.getContextPath();
- String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
- %>
- <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <base href="<%=basePath%>">
- <script type="text/javascript" src="js/jquery-1.7.1.js"></script>
- <title>用户列表</title>
- <script type="text/javascript">
- function del(id){
- $.get("<%=basePath%>user/delUser?id=" + id,function(data){
- if("success" == data.result){
- alert("删除成功");
- window.location.reload();
- }else{
- alert("删除失败");
- }
- });
- }
- </script>
- </head>
- <body>
- <h6><a href="<%=basePath%>user/toAddUser">添加用户</a></h6>
- <table border="1">
- <tbody>
- <tr>
- <th>姓名</th>
- <th>年龄</th>
- <th>操作</th>
- </tr>
- <c:if test="${!empty userList }">
- <c:forEach items="${userList}" var="user">
- <tr>
- <td>${user.userName }</td>
- <td>${user.age }</td>
- <td>
- <a href="<%=basePath%>user/getUser?id=${user.id}">编辑</a>
- <a href="javascript:del('${user.id }')">删除</a>
- </td>
- </tr>
- </c:forEach>
- </c:if>
- </tbody>
- </table>
- </body>
- </html>
editUser.jsp- <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
- <%
- String path = request.getContextPath();
- String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
- %>
- <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <base href="<%=basePath%>">
- <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="button" value="编辑" onclick="updateUser()"/>
- </form>
- </body>
- </html>
到此 简单的整合SSM 【基本的操作内容已经完成】让你们看下界面运行,地址:http://localhost:8088/SpringMVC_Spring_mybatis/
首页:
点击编辑进去:
点击添加进去:
由于我在网络问题 图片暂时没有上传上去。【现在我吧图片都正上去了,希望多多支持】对应的数据库 表- /*
- Navicat MySQL Data Transfer
- Source Server : localhost
- Source Server Version : 50515
- Source Host : localhost:3306
- Source Database : db_zsl
- Target Server Type : MYSQL
- Target Server Version : 50515
- File Encoding : 65001
- Date: 2016-05-16 16:10:51
- */
- SET FOREIGN_KEY_CHECKS=0;
- -- ----------------------------
- -- Table structure for `t_user`
- -- ----------------------------
- DROP TABLE IF EXISTS `t_user`;
- CREATE TABLE `t_user` (
- `user_id` int(11) NOT NULL AUTO_INCREMENT,
- `user_name` varchar(20) NOT NULL,
- `user_age` varchar(20) NOT NULL,
- PRIMARY KEY (`user_id`)
- ) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8;
- -- ----------------------------
- -- Records of t_user
- -- ----------------------------
- INSERT INTO `t_user` VALUES ('2', '朱佳鹏', '25');
- INSERT INTO `t_user` VALUES ('3', '傻狍子', '150');
- INSERT INTO `t_user` VALUES ('4', 'jiuqiyuliang', '23');
- INSERT INTO `t_user` VALUES ('5', 'jiuqiyuliang', '23');
- INSERT INTO `t_user` VALUES ('6', 'jiuqiyuliang', '23');
- INSERT INTO `t_user` VALUES ('7', 'jiuqiyuliang', '23');
- INSERT INTO `t_user` VALUES ('9', 'liyintao123', '23123');
- -- ----------------------------
- -- Table structure for `user_t`
- -- ----------------------------
- DROP TABLE IF EXISTS `user_t`;
- CREATE TABLE `user_t` (
- `id` int(11) NOT NULL AUTO_INCREMENT,
- `user_name` varchar(40) NOT NULL,
- `password` varchar(255) NOT NULL,
- `age` int(4) NOT NULL,
- PRIMARY KEY (`id`)
- ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
- -- ----------------------------
- -- Records of user_t
- -- ----------------------------
- INSERT INTO `user_t` VALUES ('1', '测试', 'sfasgfaf', '24');