SSM整合增删查改

一:项目结构

   二:导入jar包

     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/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>BookManage</groupId>
  <artifactId>BookManage</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>BookManage Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <properties>
    <!-- spring版本号 -->
    <spring.version>4.0.2.RELEASE</spring.version>
    <!-- mybatis版本号 -->
    <mybatis.version>3.2.6</mybatis.version>
    <!-- log4j日志文件管理包版本 -->
    <slf4j.version>1.7.7</slf4j.version>
    <log4j.version>1.2.17</log4j.version>
  </properties>

  <dependencies>

    <!-- 导入dbcp的jar包,用来在applicationContext.xml中配置数据库 -->
    <dependency>
      <groupId>commons-dbcp</groupId>
      <artifactId>commons-dbcp</artifactId>
      <version>1.2.2</version>
    </dependency>
    <!-- 导入java ee jar 包 -->
    <dependency>
      <groupId>javax</groupId>
      <artifactId>javaee-api</artifactId>
      <version>7.0</version>
    </dependency>
    <!-- spring核心包 -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>${spring.version}</version>
    </dependency>


    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-oxm</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>${spring.version}</version>
    </dependency>


    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>${spring.version}</version>
    </dependency>


    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aop</artifactId>
      <version>${spring.version}</version>
    </dependency>


    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context-support</artifactId>
      <version>${spring.version}</version>
    </dependency>


    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <!-- mybatis核心包 -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>${mybatis.version}</version>
    </dependency>
    <!-- mybatis/spring包 -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.2.2</version>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <!-- 导入mybatis包 -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.2.6</version>
    </dependency>


    <!-- 导入Mysql数据库链接jar包 -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.30</version>
    </dependency>
    <!-- json数据 -->
    <dependency>
      <groupId>org.codehaus.jackson</groupId>
      <artifactId>jackson-core-asl</artifactId>
      <version>1.9.13</version>
    </dependency>
    <dependency>
      <groupId>org.codehaus.jackson</groupId>
      <artifactId>jackson-mapper-asl</artifactId>
      <version>1.9.13</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>2.1.0</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.1.0</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-annotations</artifactId>
      <version>2.1.0</version>
    </dependency>

    <!-- JSTL标签类 -->
    <dependency>
      <groupId>jstl</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>



    <!-- 日志文件管理包 -->
    <!-- log start -->
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>${log4j.version}</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>${slf4j.version}</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>${slf4j.version}</version>
    </dependency>
    <!-- log end -->

    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.2.1</version>
    </dependency>

    <!-- dom4j-->
    <dependency>
      <groupId>dom4j</groupId>
      <artifactId>dom4j</artifactId>
      <version>1.6</version>
    </dependency>

 

  </dependencies>
  <build>
    <finalName>BookManage</finalName>
  </build>
</project>

   三、配置文件

    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"
         xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         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></display-name>
    <filter>
        <filter-name>useChinese</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>useChinese</filter-name>
        <url-pattern>*.do</url-pattern>
    </filter-mapping>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:config/mybatis.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener
                                                                       </listener-class>
    </listener>
    <servlet>
        <servlet-name>SpringMVC</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:config/mvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>SpringMVC</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>
    <welcome-file-list>
        <welcome-file>login/index.jsp</welcome-file>
    </welcome-file-list>

</web-app>

    jdbc.properties

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc\:mysql\://localhost\:3306/bookmanage?useUnicode\=true&characterEncoding\=UTF-8
jdbc.username=root
#jdbc.password=111111
jdbc.password=root
#定义初始连接数
initialSize=0  
#定义最大连接数
maxActive=20  
#定义最大空闲
maxIdle=20  
#定义最小空闲
minIdle=1  
#定义最长等待时间
maxWait=60000  

   mvc.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:p="http://www.springframework.org/schema/p"
       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-3.1.xsd
                        http://www.springframework.org/schema/context
                        http://www.springframework.org/schema/context/spring-context-3.1.xsd
                        http://www.springframework.org/schema/mvc
                        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
    <!--加载注解驱动-->
    <mvc:annotation-driven/>

    <!--配置自动扫描-->
    <context:component-scan base-package="main.controller"/>
    <!--视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

   mybatis.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:p="http://www.springframework.org/schema/p"
       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-3.1.xsd
                        http://www.springframework.org/schema/context
                        http://www.springframework.org/schema/context/spring-context-3.1.xsd
                        http://www.springframework.org/schema/mvc
                        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
    <!--注解-->
    <context:annotation-config/>
    <!--自动扫描,将扫描到的类转化为bean-->
    <context:component-scan base-package="main"/>
    <!--加载数据资源属性文件-->
    <!--引入jdbc配置-->
    <bean id="propertyConfigurer" 
            class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location" value="classpath:config/jdbc.properties"/>
    </bean>
    <!--配置数据源-->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" 
                                                                   destroy-method="close">
        <property name="driverClassName" value="${jdbc.driverClassName}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
        <!-- 初始化连接大小 -->
        <property name="initialSize" value="${initialSize}"></property>
        <!-- 连接池最大数量 -->
        <property name="maxActive" value="${maxActive}"></property>
        <!-- 连接池最大空闲 -->
        <property name="maxIdle" value="${maxIdle}"></property>
        <!-- 连接池最小空闲 -->
        <property name="minIdle" value="${minIdle}"></property>
        <!-- 获取连接最大等待时间 -->
        <property name="maxWait" value="${maxWait}"></property>
    </bean>
    <!---->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <!--指定mybatis的xml配置文件位置-->
        <!--另一种定义sqlsession的引用的方式需要指定mybatis的配置文件位置,-->
        <!- <property name="configLocation" value="config/mybatis.xml"/> ->
        <property name="typeAliasesPackage" value="main.dao"/>
        <!-- 自动扫描mapping.xml文件 -->
        <property name="mapperLocations" value="classpath:main/dao/idao/*.xml"/>
    </bean>
    <!--  扫描sqlSessionFactory和定义的dao接口的包 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- DAO接口所在包名,Spring会自动查找其下的dao-->
        <property name="basePackage" value="main.dao.idao"/>
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    </bean>
    <!-- 6、声明式事务管理 -->
    <bean id="transactionManager"
          class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <!--&lt;!&ndash; 7、注解事务切面 &ndash;&gt;-->

    <!--<tx:annotation-driven transaction-manager="transactionManager"/>-->

</beans>

  四、定义数据库操作

   实体Test.class

package main.dao.entity;

/**
 * Created by swordbone on 2017/11/29.
 */
public class Test {
    private Integer id;
    private String name;
    private Integer age;
    private String nickname;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getNickname() {
        return nickname;
    }

    public void setNickname(String nickname) {
        this.nickname = nickname;
    }

    @Override
    public String toString() {
        return "Test{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", nickName='" + nickname + '\'' +
                '}';
    }
}

    testMapper.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="main.dao.idao.TestMapper">
    <resultMap id="TestBaseResultMap" type="main.dao.entity.Test">
        <id column="ID" property="id" jdbcType="INTEGER"/>
        <result column="NAME" property="name" jdbcType="VARCHAR"/>
        <result column="AGE" property="age" jdbcType="INTEGER"/>
        <result column="NICKNAME" property="nickname" jdbcType="VARCHAR"/>
    </resultMap>
    <select id="queryTest" parameterType="main.dao.entity.Test"
                                                     resultMap="TestBaseResultMap">
        SELECT * FROM test WHERE 1=1
        <if test="id != null and id != ''">
            AND ID=#{id,jdbcType=INTEGER}
        </if>
        <if test="name !=null and name != ''">
            AND ID=#{name,jdbcType=VARCHAR}
        </if>
    </select>
    <insert id="createTest" parameterType="main.dao.entity.Test">
        INSERT INTO test
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="id != null">
                ID,
            </if>
            <if test="name != null">
                NAME,
            </if>
            <if test="age != null">
                AGE,
            </if>
            <if test="nickname != null">
                NICKNAME
            </if>
        </trim>
        <trim prefix="VALUES (" suffix=")" suffixOverrides=",">
            <if test="id != null">
                #{id,jdbcType=INTEGER},
            </if>
            <if test="name != null">
                #{name,jdbcType=VARCHAR},
            </if>
            <if test="age != null">
                #{age,jdbcType=INTEGER},
            </if>
            <if test="nickname != null">
                #{nickname,jdbcType=VARCHAR}
            </if>
        </trim>
    </insert>
    <update id="updateTest" parameterType="main.dao.entity.Test">
        UPDATE test
        <set>
            <if test="name != null and name !=''">
                NAME=#{name},
            </if>
            <if test="age !=null">
                AGE=#{age,jdbcType=INTEGER},
            </if>
            <if test="nickname != null and nickname !=''">
                NICKNAME=#{nickname},
            </if>
        </set>
        WHERE ID=#{id}
    </update>
    <delete id="deleteTest" parameterType="java.lang.Integer">
        DELETE FROM test WHERE
        <if test="_parameter != null and _parameter !=''">
            ID=#{id,jdbcType=INTEGER}
        </if>
    </delete>
</mapper>

  在同一目录下创建dao接口,注意接口中的方法名与map.xml文件中的sql语句id相同,参数返回值都要对应

   TestMapper.class

package main.dao.idao;

import main.dao.entity.Test;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * Created by swordbone on 2017/11/29.
 */
@Repository
public interface TestMapper {
    Integer createTest(Test test);
    List<Test> queryTest(Test test);
    Integer updateTest(Test test);
    Integer deleteTest(Integer id);
}

  五、service层

    service接口:TestService.class

package main.service.iService;

import main.dao.entity.Test;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * Created by swordbone on 2017/11/29.
 */

public interface TestService {
    Integer createTest(Test test);
    List<Test> queryTest(Test test);
    Integer updateTest(Test test);
    Integer deleteTest(Integer id);
}

   service实现类:TestServiceImpl.class

package main.service.serviceImpl;

import main.dao.entity.Test;
import main.dao.idao.TestMapper;
import main.service.iService.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * Created by swordbone on 2017/11/29.
 */
@Repository
public class TestServiceImpl implements TestService {
//自动装载dao接口
    @Autowired
    private TestMapper testMapper;
    public Integer createTest(Test test) {
        return testMapper.createTest(test);
    }

    public List<Test> queryTest(Test test) {
        return testMapper.queryTest(test);
    }

    public Integer updateTest(Test test) {
        return testMapper.updateTest(test);
    }

    public Integer deleteTest(Integer id) {
        return testMapper.deleteTest(id);
    }
}

 六、jsp页面

  新建test页面:create.jsp

<%--
  Created by IntelliJ IDEA.
  User: 老牛鼻子的山
  Date: 2017/11/30
  Time: 14:37
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>create page</title>
</head>
<body>
<form action="/test/create.do" method="post">
    <table>
        <tr>
        <th>create new</th>
        </tr>
        <tr>
            <td>id:</td>
            <td><input name="id" type="text"/></td>
        </tr>
        <tr>
            <td>name:</td>
            <td><input name="name" type="text"/></td>
        </tr>
        <tr>
            <td>age:</td>
            <td><input name="age" type="text" /></td>
        </tr>
        <tr>
            <td>nickname:</td>
            <td><input name="nickname" type="text"/></td>
        </tr>
        <tr>
            <td><input type="submit" name="commit" value="create"/></td>
        </tr>
    </table>
</form>

</body>
</html>

  查询界面:query.jsp

<%--
  Created by IntelliJ IDEA.
  User: 老牛鼻子的山
  Date: 2017/11/30
  Time: 10:50
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<html>
<head>
    <title>query page</title>
</head>
<body>
<form method="post" action="/test/query.do">
    <label>id:</label><input type="text" name="id" value="${test.id}"/>
    <label>name:</label><input type="text" name="name" value="${test.name}"/>
    <input type="submit" value="查询">
</form><br>
<a href="create.jsp" method="post">create</a><br>
<table border="2">

    <tr>
        <th>select</th>
        <th>id</th>
        <th>name</th>
        <th>age</th>
        <th>nickname</th>
        <th>update</th>
        <th>delete</th>
    </tr>
    <c:forEach items="#{list}" var="li">
        <tr>
            <td><input type="checkbox" name="check" value="${li.id}"/> </td>
            <td>${li.id}</td>
            <td>${li.name}</td>
            <td>${li.age}</td>
            <td>${li.nickname}</td>
            <td><a href="/test/${li.id}/update.do">update</a></td>
            <td><a href="/test/${li.id}/delete.do">delete</a></td>
        </tr>
    </c:forEach>
</table>

</body>
</html>

 编辑页面:updatepage.jsp

<%--
  Created by IntelliJ IDEA.
  User: 老牛鼻子的山
  Date: 2017/12/4
  Time: 11:42
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>updatepage</title>
</head>
<body>
<form action="/test/updateForm.do" method="post">
    <table>
        <tr>
            <th>update one</th>
        </tr>
        <tr>
            <td>id:</td>
            <td><input name="id" type="text" value="${test.id}" readonly/></td>
        </tr>
        <tr>
            <td>name:</td>
            <td><input name="name" type="text" value="${test.name}"/></td>
        </tr>
        <tr>
            <td>age:</td>
            <td><input name="age" type="text" value="${test.age}" /></td>
        </tr>
        <tr>
            <td>nickname:</td>
            <td><input name="nickname" type="text" value="${test.nickname}"/></td>
        </tr>
        <tr>
            <td><input type="submit" value="submit"></td>
        </tr>

    </table>
</form>


</body>
</html>

  页面入口index.jsp

<html>
<body>
<h2><a href="/test/create.jsp">create</a></h2>
<h2><a href="/test/query.do">query</a> </h2>
</body>
</html>

七、controller

  TestController.class

package main.controller.test;

import main.dao.entity.Test;
import main.service.iService.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * Created by swordbone on 2017/11/29.
 */
@Controller
@RequestMapping("/test")
public class TestController {
//   自动装载TestService接口
    @Autowired
    TestService testService;
//  查询所有的test
    @RequestMapping("/query")
    public String queryTest(ModelMap map, HttpServletRequest request, Test test){
        List<Test> list = testService.queryTest(test);
        map.addAttribute("list",list);
        return null;
    }
//    新建test
    @RequestMapping("/create")
    public String createTest(ModelMap map,HttpServletRequest request,Test test){
        Integer returnnum = testService.createTest(test);
        map.addAttribute("returnnum",returnnum);
        return "redirect:/test/query.do";
    }
//    编辑test
    @RequestMapping("/{id}/update")
    public String updateTest (ModelMap map, HttpServletRequest request, 
                                                     Test test, @PathVariable String id){
        Integer intId = Integer.valueOf(id);
        Test test1 = new Test();
        test1.setId(intId);
        List<Test> list = testService.queryTest(test1);
        map.addAttribute("test",list.get(0));
        return "/test/updatepage";
    }
//    更改test
    @RequestMapping("/updateForm")
    public String updateForm(ModelMap map,HttpServletRequest request,Test test){
        Integer returnint = testService.updateTest(test);
        return "redirect:/test/query.do";
    }
//    删除test
    @RequestMapping("/{id}/delete")
    public String deleteTest(ModelMap map,HttpServletRequest request,
                                                    Test test,@PathVariable String id){
        Integer intId = Integer.valueOf(id);
        Integer returnnum = testService.deleteTest(intId);
        map.addAttribute("returnnum",returnnum);
        return "redirect:/test/query.do";
    }
}

 项目页面:

   index.jsp


   点击query跳转到query.do

 点击create跳转到create.jsp


  新建一条数据


 编辑

  

   

猜你喜欢

转载自201610222643.iteye.com/blog/2404546