欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java 整合模板彻底解决ssm配置难题

程序员文章站 2022-03-28 23:36:10
spring+springmvc+mybatis环境配置ideamysql 5.7tomcat 8.5maven 3.6创建数据库create database `ssmbuild`;use `ssm...

spring+springmvc+mybatis

环境配置
idea
mysql 5.7
tomcat 8.5
maven 3.6
创建数据库

create database `ssmbuild`;

use `ssmbuild`;

drop table if exists `books`;

create table `books` (
`bookid` int(10) not null auto_increment comment '书id',
`bookname` varchar(100) not null comment '书名',
`bookcounts` int(11) not null comment '数量',
`detail` varchar(200) not null comment '描述',
key `bookid` (`bookid`)
) engine=innodb default charset=utf8

insert  into `books`(`bookid`,`bookname`,`bookcounts`,`detail`)values
(1,'java',1,'从入门到放弃'),
(2,'mysql',10,'从删库到跑路'),
(3,'linux',5,'从进门到进牢');

Java 整合模板彻底解决ssm配置难题

编写数据库对应的实体类com.longdi.pojo.books
导入lombok在pom.xml中

package com.longdi.pojo;

import lombok.allargsconstructor;
import lombok.data;
import lombok.noargsconstructor;

/**
 * @author: 龍弟
 * @description
 * @date: 2021/9/27 20:22
 */
@data
@allargsconstructor
@noargsconstructor
public class books {
    private int bookid;
    private string bookname;
    private int bookcounts;
    private string detail;
}

导入相关的pom依赖

<dependencies>
        <!--junit-->
        <dependency>
            <groupid>junit</groupid>
            <artifactid>junit</artifactid>
            <version>4.12</version>
        </dependency>
        <!--数据库驱动-->
        <dependency>
            <groupid>mysql</groupid>
            <artifactid>mysql-connector-java</artifactid>
            <version>5.1.47</version>
        </dependency>
        <!-- 数据库连接池 -->
        <dependency>
            <groupid>com.mchange</groupid>
            <artifactid>c3p0</artifactid>
            <version>0.9.5.2</version>
        </dependency>

        <!--servlet - jsp -->
        <dependency>
            <groupid>javax.servlet</groupid>
            <artifactid>servlet-api</artifactid>
            <version>2.5</version>
        </dependency>
        <dependency>
            <groupid>javax.servlet.jsp</groupid>
            <artifactid>jsp-api</artifactid>
            <version>2.2</version>
        </dependency>
        <dependency>
            <groupid>javax.servlet</groupid>
            <artifactid>jstl</artifactid>
            <version>1.2</version>
        </dependency>

        <!--mybatis-->
        <dependency>
            <groupid>org.mybatis</groupid>
            <artifactid>mybatis</artifactid>
            <version>3.5.2</version>
        </dependency>
        <dependency>
            <groupid>org.mybatis</groupid>
            <artifactid>mybatis-spring</artifactid>
            <version>2.0.2</version>
        </dependency>
        <dependency>
            <groupid>org.aspectj</groupid>
            <artifactid>aspectjweaver</artifactid>
            <version>1.8.4</version>
        </dependency>
        <!--spring-->
        <dependency>
            <groupid>org.springframework</groupid>
            <artifactid>spring-webmvc</artifactid>
            <version>5.1.9.release</version>
        </dependency>
        <dependency>
            <groupid>org.springframework</groupid>
            <artifactid>spring-jdbc</artifactid>
            <version>5.1.9.release</version>
        </dependency>
        <dependency>
            <groupid>org.projectlombok</groupid>
            <artifactid>lombok</artifactid>
            <version>1.18.16</version>
            <scope>compile</scope>
        </dependency>
    </dependencies>

资源过滤设置

<build>
   <resources>
       <resource>
           <directory>src/main/java</directory>
           <includes>
               <include>**/*.properties</include>
               <include>**/*.xml</include>
           </includes>
           <filtering>false</filtering>
       </resource>
       <resource>
           <directory>src/main/resources</directory>
           <includes>
               <include>**/*.properties</include>
               <include>**/*.xml</include>
           </includes>
           <filtering>false</filtering>
       </resource>
   </resources>
</build>

mybatis层编写
创建mybatis-config.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="logimpl" value="stdout_logging"/>
    </settings>

    <typealiases>
        <package name="com.longdi.pojo"/>
    </typealiases>
    <mappers>
        <mapper class="com.longdi.dao.bookmapper"/>
    </mappers>
</configuration>
jdbc.driver=com.mysql.jdbc.driver
jdbc.url=jdbc:mysql://localhost:3306/ssmbuild?usessl=true&useunicode=true&characterencoding=utf8
jdbc.username=root
jdbc.password=123456

编写dao层的mapper接口

package com.longdi.dao;

import com.longdi.pojo.books;
import org.apache.ibatis.annotations.param;

import java.util.list;

/**
 * @author: 龍弟
 * @description
 * @date: 2021/9/27 20:32
 */
public interface bookmapper {
    //增加一本书
    int addbook(books books);

    //删除一本书
    int deletebookbyid(@param("bookid") int id);

    //更新一本书
    int updatebook(books books);

    //查询一本书
    books querybookbyid(@param("bookid")int id);

    //查询全部的书
    list<books> queryallbook();

    books querybookbyname(@param("bookname")string bookname);

}

编写接口对应的 mapper.xml 文件。需要导入mybatis的包;

<?xml version="1.0" encoding="utf-8" ?>
<!doctype mapper
        public "-//mybatis.org//dtd config 3.0//en"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.longdi.dao.bookmapper">
    <insert id="addbook" parametertype="books">
       insert into ssmbuild.books(bookname,bookcounts,detail)
       values(#{bookname},#{bookcounts},#{detail});
    </insert>

    <delete id="deletebookbyid" parametertype="int">
        delete from ssmbuild.books where bookid=#{bookid}
    </delete>
    
    <update id="updatebook" parametertype="books">
        update ssmbuild.books
        set bookname=#{bookname},bookcounts=#{bookcounts},detail=#{detail}
        where bookid=#{bookid};

    </update>

    <select id="querybookbyid" resulttype="books">
        select * from ssmbuild.books
        where bookid=#{bookid}
    </select>

    <select id="queryallbook" resulttype="books">
        select * from ssmbuild.books
    </select>
    
    <select id="querybookbyname" resulttype="books">
        select * from ssmbuild.books where bookname=#{bookname}
    </select>
    
</mapper>

编写service层的接口

package com.longdi.service;

import com.longdi.pojo.books;


import java.util.list;

/**
 * @author: 龍弟
 * @description
 * @date: 2021/9/27 21:03
 */
public interface bookservice {
    //增加一本书
    int addbook(books books);

    //删除一本书
    int deletebookbyid( int id);

    //更新一本书
    int updatebook(books books);

    //查询一本书
    books querybookbyid(int id);

    //查询全部的书
    list<books> queryallbook();

    books querybookbyname(string bookname);
}

service层的实现类

package com.longdi.service;

import com.longdi.dao.bookmapper;
import com.longdi.pojo.books;
import org.springframework.stereotype.service;

import java.util.list;

/**
 * @author: 龍弟
 * @description
 * @date: 2021/9/27 21:05
 */

public class bookserviceimpl implements bookservice{

    private bookmapper bookmapper;
    public void setbookmapper(bookmapper bookmapper) {
        this.bookmapper = bookmapper;
    }

    public int addbook(books books) {
        return bookmapper.addbook(books);
    }

    public int deletebookbyid(int id) {
        return bookmapper.deletebookbyid(id);
    }

    public int updatebook(books books) {
        system.out.println("bookserviceimpl:updatebook=>"+books);
        return bookmapper.updatebook(books);
    }

    public books querybookbyid(int id) {
        return bookmapper.querybookbyid(id);
    }

    public list<books> queryallbook() {
        return bookmapper.queryallbook();
    }

    public books querybookbyname(string bookname) {
        return bookmapper.querybookbyname(bookname);
    }
}

spring整合mybatis spring-dao.xml
以下为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: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/context
       https://www.springframework.org/schema/context/spring-context.xsd">

    <!-- 配置整合mybatis -->
    <!-- 1.关联数据库文件 -->
    <context:property-placeholder location="classpath:database.properties"/>

    <!-- 2.数据库连接池 -->
    <!--数据库连接池
        dbcp 半自动化操作 不能自动连接
        c3p0 自动化操作(自动的加载配置文件 并且设置到对象里面)
    -->
    <bean id="datasource" class="com.mchange.v2.c3p0.combopooleddatasource">
        <!-- 配置连接池属性 -->
        <property name="driverclass" value="${jdbc.driver}"/>
        <property name="jdbcurl" value="${jdbc.url}"/>
        <property name="user" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>

        <!-- c3p0连接池的私有属性 -->
        <property name="maxpoolsize" value="30"/>
        <property name="minpoolsize" value="10"/>
        <!-- 关闭连接后不自动commit -->
        <property name="autocommitonclose" value="false"/>
        <!-- 获取连接超时时间 -->
        <property name="checkouttimeout" value="10000"/>
        <!-- 当获取连接失败重试次数 -->
        <property name="acquireretryattempts" value="2"/>
    </bean>

    <!-- 3.配置sqlsessionfactory对象 -->
    <bean id="sqlsessionfactory" class="org.mybatis.spring.sqlsessionfactorybean">
        <!-- 注入数据库连接池 -->
        <property name="datasource" ref="datasource"/>
        <!-- 配置mybaties全局配置文件:mybatis-config.xml -->
        <property name="configlocation" value="classpath:mybatis-config.xml"/>
    </bean>

    <!-- 4.配置扫描dao接口包,动态实现dao接口注入到spring容器中 -->
    <bean class="org.mybatis.spring.mapper.mapperscannerconfigurer">
        <!-- 注入sqlsessionfactory -->
        <property name="sqlsessionfactorybeanname" value="sqlsessionfactory"/>
        <!-- 给出需要扫描dao接口包 -->
        <property name="basepackage" value="com.longdi.dao"/>
    </bean>

</beans>

spring-service.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/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">

    <!-- 扫描service相关的bean -->
    <context:component-scan base-package="com.longdi.service" />

    <!--bookserviceimpl注入到ioc容器中-->
    <bean id="bookserviceimpl" class="com.longdi.service.bookserviceimpl">
        <property name="bookmapper" ref="bookmapper"/>
    </bean>

    <!-- 配置事务管理器 -->
    <bean id="transactionmanager" class="org.springframework.jdbc.datasource.datasourcetransactionmanager">
        <!-- 注入数据库连接池 -->
        <property name="datasource" ref="datasource" />
    </bean>
    <!--aop事物支持-->

    <!--结合aop实现事物的织入-->
    <!--配置事物的通知-->

    <tx:advice id="txadvice" transaction-manager="transactionmanager">
        <tx:attributes>
            <tx:method name="*" propagation="required"/>
        </tx:attributes>
    </tx:advice>

    <!--配置事物切入-->
    <aop:config>
        <aop:pointcut id="txpointcut" expression="execution(* com.longdi.dao.*.*(..))"/>
        <aop:advisor advice-ref="txadvice" pointcut-ref="txpointcut"/>
    </aop:config>

</beans>

以下为springmvc层
配置web.xml

<?xml version="1.0" encoding="utf-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"
         xsi:schemalocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

    <!--dispatcherservlet-->
    <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:applicationcontext.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>

    <!--encodingfilter-->
    <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>
    </filter>
    <filter-mapping>
        <filter-name>encodingfilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!--session过期时间-->
    <session-config>
        <session-timeout>15</session-timeout>
    </session-config>

</web-app>

spring-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: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.xsd
   http://www.springframework.org/schema/mvc
   https://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!-- 配置springmvc -->
    <!-- 1.开启springmvc注解驱动 -->
    <mvc:annotation-driven />
    <!-- 2.静态资源默认servlet配置-->
    <mvc:default-servlet-handler/>

    <!-- 3.配置jsp 显示viewresolver视图解析器 -->
    <bean class="org.springframework.web.servlet.view.internalresourceviewresolver">
        <property name="viewclass" value="org.springframework.web.servlet.view.jstlview" />
        <property name="prefix" value="/web-inf/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>

    <!-- 4.扫描web相关的bean -->
    <context:component-scan base-package="com.longdi.controller" />

</beans>

spring配置整合文件,创建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"
       xsi:schemalocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd">

    <import resource="spring-dao.xml"/>
    <import resource="spring-service.xml"/>
    <import resource="spring-mvc.xml"/>

</beans>

以上为ssm的环境配置,下面编写controller层和视图层,实现书籍的crud功能

controller层 书籍的增删改查功能

import java.util.arraylist;
import java.util.list;

/**
 * @author: 龍弟
 * @description
 * @date: 2021/9/27 22:47
 */
@controller
@requestmapping("/book")
public class bookcontroller {

    @autowired
    @qualifier("bookserviceimpl")
    private bookservice bookservice;

    @requestmapping("/allbook")
    public string list(model model) {
        list<books> list = bookservice.queryallbook();
        model.addattribute("list", list);
        return "allbook";
    }
    //跳转到增加书籍页面
    @requestmapping("/toaddbook")
    public string toaddpaper(){
        return "addbook";
    }
    //添加书籍的请求
    @requestmapping("/addbook")
    public string addbook(books books){
        system.out.println("addbook=>"+books);
        bookservice.addbook(books);
        return "redirect:/book/allbook";
    }
    //跳转到修改页面
    @requestmapping("toupdatebook")
    public string toupdatepaper(int id,model model){
        books books = bookservice.querybookbyid(id);
        model.addattribute("book",books);
        return "updatebook";
    }
    //修改书籍
    @requestmapping("updatebook")
    public string updatebook(books books){
        system.out.println("updatebook=>"+books);
        int i=bookservice.updatebook(books);
        if(i>0){
            system.out.println("添加books成功"+books);
        }

        return "redirect:/book/allbook";
    }

    //删除书籍
    @requestmapping("/deletebook/{bookid}")
    public string delebook(@pathvariable("bookid") int id){
        bookservice.deletebookbyid(id);
        return "redirect:/book/allbook";
    }
    //查询书籍
    @requestmapping("/querybook")
    public string querybook(string querybookname,model model){
         books books=bookservice.querybookbyname(querybookname);
        system.err.println("querybook=>"+books);
         list<books> list=new arraylist<books>();
         list.add(books);

         if(books==null){
             list=bookservice.queryallbook();
             model.addattribute("error","未查到");
         }

         model.addattribute("list",list);
         return "allbook";
    }

}

编写首页index.jsp

<%@ page language="java" contenttype="text/html; charset=utf-8" pageencoding="utf-8" %>
<!doctype html>
<html>
<head>
  <title>首页</title>
  <style>
    a{
      text-decoration: none;
      color:black;
      font-size:18px;
    }
    h3{
      width:180px;
      height:38px;
      margin: 100px auto;
      text-align: center;
      line-height: 38px;
      background: deepskyblue;
      border-radius: 4px;
    }
  </style>
</head>

<h3>
  <a href="${pagecontext.request.contextpath}/book/allbook" rel="external nofollow"  rel="external nofollow" >进入到书籍页面</a>
</h3>
</body>
</html>

编写书籍列表页面allbook.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contenttype="text/html;charset=utf-8" language="java" %>
<html>
<head>
  <title>书籍列表</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <!-- 引入 bootstrap -->
  <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="stylesheet">
</head>
<body>

<div class="container">

  <div class="row clearfix">
    <div class="col-md-12 column">
      <div class="page-header">
        <h1>
          <small>书籍列表 —— 显示所有书籍</small>
        </h1>
      </div>
    </div>
  </div>

  <div class="row">
    <div class="col-md-4 column">
      <a class="btn btn-primary" href="${pagecontext.request.contextpath}/book/toaddbook" rel="external nofollow" >新增书籍</a>
      <a class="btn btn-primary" href="${pagecontext.request.contextpath}/book/allbook" rel="external nofollow"  rel="external nofollow" >显示全部书籍</a>
    </div>
    <div class="col-md-4 column">
      <div class="col-md-8 column"></div>
      <%--查询书籍--%>

      <form  class="form-inline" action="${pagecontext.request.contextpath}/book/querybook" method="post" style="float: right">
        <span style="color:red;font-weight: bold">${error}</span>
          <input type="text" name="querybookname" class="form-control" placeholder="请输入要查询的书籍名称">
          <input type="submit" value="查询" class="btn btn-primary"/>
      </form>
    </div>
  </div>

  <div class="row clearfix">
    <div class="col-md-12 column">
      <table class="table table-hover table-striped">
        <thead>
        <tr>
          <th>书籍编号</th>
          <th>书籍名字</th>
          <th>书籍数量</th>
          <th>书籍详情</th>
          <th>操作</th>
        </tr>
        </thead>

        <tbody>
        <c:foreach var="book" items="${requestscope.get('list')}">
          <tr>
            <td>${book.getbookid()}</td>
            <td>${book.getbookname()}</td>
            <td>${book.getbookcounts()}</td>
            <td>${book.getdetail()}</td>
            <td>

              <a href="${pagecontext.request.contextpath}/book/toupdatebook?id=${book.getbookid()}" rel="external nofollow" >更改</a> |
              <a href="${pagecontext.request.contextpath}/book/deletebook/${book.getbookid()}" rel="external nofollow" >删除</a>
            </td>
          </tr>
        </c:foreach>
        </tbody>
      </table>
    </div>
  </div>
</div>

添加书籍页面 addbook.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contenttype="text/html;charset=utf-8" language="java" %>

<html>
<head>
    <title>新增书籍</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- 引入 bootstrap -->
    <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="stylesheet">
</head>
<body>
<div class="container">

    <div class="row clearfix">
        <div class="col-md-12 column">
            <div class="page-header">
                <h1>
                    <small>新增书籍</small>
                </h1>
            </div>
        </div>
    </div>
    <form action="${pagecontext.request.contextpath}/book/addbook" method="post">
        书籍名称:<input type="text" name="bookname"><br><br><br>
        书籍数量:<input type="text" name="bookcounts"><br><br><br>
        书籍详情:<input type="text" name="detail"><br><br><br>
        <input type="submit" value="添加">
    </form>

</div>

修改书籍页面 updatebook.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contenttype="text/html;charset=utf-8" language="java" %>
<html>
<head>
    <title>修改信息</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- 引入 bootstrap -->
    <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="stylesheet">
</head>
<body>
<div class="container">

    <div class="row clearfix">
        <div class="col-md-12 column">
            <div class="page-header">
                <h1>
                    <small>修改信息</small>
                </h1>
            </div>
        </div>
    </div>

    <form action="${pagecontext.request.contextpath}/book/updatebook" method="post">
        <input type="hidden" name="bookid" value="${book.getbookid()}"/>
        书籍名称:<input type="text" name="bookname" value="${book.getbookname()}"/>
        书籍数量:<input type="text" name="bookcounts" value="${book.getbookcounts()}"/>
        书籍详情:<input type="text" name="detail" value="${book.getdetail() }"/>
        <input type="submit" value="提交"/>
    </form>

</div>

Java 整合模板彻底解决ssm配置难题

Java 整合模板彻底解决ssm配置难题

Java 整合模板彻底解决ssm配置难题

项目部署到tomcat中

Java 整合模板彻底解决ssm配置难题

项目结构图

Java 整合模板彻底解决ssm配置难题

Java 整合模板彻底解决ssm配置难题

gitee网站下载源码
github网站下载源码

到此这篇关于java 整合模板彻底解决ssm配置难题的文章就介绍到这了,更多相关java ssm配置内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!