SSM项目案例搭建整合含源码(IDEA版)轻松上手

环境:

ssm项目源码 点我下载 !!!!免费下载不要money

  1. IDEA
  2. MySql5.7以上
  3. Tomcat7.0以上
  4. Maven3.0以上

运用Spring MyBatis,mysql 简单前端知识总结来说,配置地狱,各种配置,恶心到吐,还是springboot香,但是总要有个过程吧,难受完了,你会看到新的曙光

1.简洁的运行截图,花里胡哨可以自己加,基础的增删改查CRUD工程师

SSM项目案例搭建整合含源码(IDEA版)轻松上手_第1张图片

2.数据库建表,我这里是navicat

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, '华为手册', 30, '博学的利郎');
(2, '中东局势', 10, '如何生存');
 (3, '上下五千年', 5, '我要当秦始皇');
 (4, '美国是狗', 999999, '不用解释');

3.导入依赖(建议保存,通用依赖)

  <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.4.6</version>
        </dependency>

        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.2</version>
        </dependency>

        <!--Spring-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.3.18.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>4.3.18.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.4</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.8</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>

4.Maven资源过滤设置 静态资源导出设置

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

5.看一下这是整体的架构结构

SSM项目案例搭建整合含源码(IDEA版)轻松上手_第2张图片

6.首先完成数据库的配置: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>

    <!--配置实体别名-->
    <typeAliases>
         <package name="com.learn.pojo"/>
    </typeAliases>

    <mappers>
        <package name="com.learn.dao"/>
    </mappers>
</configuration>

7.MyBatis层(你的mysql用户名和密码与之对应):database.properties

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


8.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>

    <!--配置实体别名-->
    <typeAliases>
         <package name="com.learn.pojo"/>
    </typeAliases>

    <mappers>
        <package name="com.learn.dao"/>
    </mappers>
</configuration>

9.在pojo包下写实体类(与数据库要与之对应):Books

SSM项目案例搭建整合含源码(IDEA版)轻松上手_第3张图片

package com.learn.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;



@Data
@AllArgsConstructor
@NoArgsConstructor
public class Books {

    private  int bookID;
    private  String bookName;
    private  int bookCounts;
    private  String detail;
}

10.编写:BooksMapper

package com.learn.dao;

import com.learn.pojo.Books;

import java.util.List;



public interface BooksMapper {

    int addBook(Books books);

    int deleteBook(int bookId);

    int updateBook(Books books);

    Books getBookById(int bookId);

    List<Books> findAll();





}

11.写SQL语句:BooksMapper.xml

<?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.learn.dao.BooksMapper">
    <insert id="addBook" parameterType="Books">
        insert into books (bookName,bookCounts,detail) values (#{bookName},#{bookCounts},#{detail})

    </insert>
    <delete id="deleteBook" parameterType="int">
        delete  from  books where bookID=#{bookID}
    </delete>

    <update id="updateBook" parameterType="Books">
        update books set bookName=#{bookName},bookCounts=#{bookCounts},detail=#{detail} where bookID=#{bookID}
    </update>

    <select id="getBookById" parameterType="int" resultType="Books">
        select *
        from books where bookID=#{bookID};
    </select>

    <select id="findAll" resultType="Books" >
        select *
        from books;
    </select>

</mapper>

12.现在可以写与之对应的(这里写死就可以保存,没有逻辑结构):spring-dao.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"

       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">

    <!--引入数据库配置文件-->
 <context:property-placeholder location="classpath:database.properties"/>

    <!--根据数据库连接信息创建连接池-->
    <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>


    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
         <!--mybatis的客户化配置-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
    </bean>



      <!--使用整合包生产代理对象注入到spring容器中-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        <property name="basePackage"  value="com.learn.dao"/>
    </bean>


</beans>

13.接下来是编写服务层:BooksServiceImpl

package com.learn.service.impl;

import com.learn.dao.BooksMapper;
import com.learn.pojo.Books;
import com.learn.service.BooksService;

import java.util.List;


public class BooksServiceImpl implements BooksService {


    private BooksMapper booksMapper;

    public void setBooksMapper(BooksMapper booksMapper) {
        this.booksMapper = booksMapper;
    }

    public int addBook(Books books) {
        return booksMapper.addBook(books);
    }

    public int deleteBook(int bookId) {
        int i= booksMapper.deleteBook(bookId);
        int j=1/0;
        return  i;
    }

    public int updateBook(Books books) {
        return  booksMapper.updateBook(books);
    }

    public Books getBookById(int bookId) {
        return booksMapper.getBookById(bookId) ;
    }

    public List<Books> findAll() {
        return  booksMapper.findAll();
    }
}

14.与之对应的BooksService

package com.learn.service;

import com.learn.pojo.Books;

import java.util.List;


public interface BooksService {

    int addBook(Books books);

    int deleteBook(int bookId);

    int updateBook(Books books);

    Books getBookById(int bookId);

    List<Books> findAll();
}

15.剩余最后两个配置类了: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
        https://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/tx
        https://www.springframework.org/schema/tx/spring-tx.xsd">


    <context:component-scan base-package="com.learn.service"/>

    <bean id="booksService" class="com.learn.service.impl.BooksServiceImpl">
        <property name="booksMapper" ref="booksMapper"/>
    </bean>
    
    
    <!--开启声明式事务管理器-->
    <bean id="dataSourceTransactionManager"  class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!--定义事务管理器的作用范围-->
    <tx:advice id="txAdvice" transaction-manager="dataSourceTransactionManager">
        <tx:attributes>
            <tx:method name="*" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>

    <!--定义在哪些方法上需要使用事务管理器-->
    <aop:config>
        <aop:pointcut id="txPoint" expression="execution(* com.learn.*.*.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPoint"/>
    </aop:config>


</beans>

16.spring-webMvc.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">

         <!--注解驱动-->
         <mvc:annotation-driven/>
         <!--不处理静态资源-->
         <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.learn.controller" />




</beans>

17.最最关键的:BookController层!!!!!增删改查的操作都在里面

package com.learn.controller;

import com.learn.pojo.Books;
import com.learn.service.BooksService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

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

@Controller
@RequestMapping("/book")
public class BookController {




    @Autowired
    private BooksService booksService;

    @RequestMapping("/queryAll")
    public String getAllBooks(Model model){
        List<Books> books = booksService.findAll();
        model.addAttribute("bookList",books);
         return "AllBook";
    }


    @RequestMapping("/toAddBook")
    public String toAddBookPage(){
          return  "addBook";
    }


    @RequestMapping("/addBook")
    public String addBook(Books book , HttpServletRequest request){
        //表单提交的name与实体类属性一致springmvc会封装到对象中,不一致需要从request中去取
        System.out.println(request.getParameter("detail"));
        booksService.addBook(book);
        return "redirect:/book/queryAll";
    }

    //restful风格参数获取
    @RequestMapping("/del/{bookId}")
    public String delBook(@PathVariable int bookId){
        booksService.deleteBook(bookId);

        return "redirect:/book/queryAll";
    }


    //用问号传参的字段名和参数名一致可以直接接收
    @RequestMapping("/toUpdateBook")
    public  String toUpdateBook(Model model,int id){
        Books book = booksService.getBookById(id);
        model.addAttribute("book",book);
        return "updateBook";
    }

    @RequestMapping("/updateBook")
    public  String updateBook(Books book){
        booksService.updateBook(book);
        return "redirect:/book/queryAll";
    }

}

2.1接下来是网页addBook.jsp

<%@ 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="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>
  </body>
</html>

2.2AllBook.jsp查询所有书籍

<%@ 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="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>
  </body>
</html>

2.3updateBook.jsp更新所有书籍

<%@ 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="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()}" ><br><br><br>
            书籍名称:<input type="text" name="bookName" value="${book.getBookName()}" ><br><br><br>
            书籍数量:<input type="text" name="bookCounts" value="${book.getBookCounts()}"><br><br><br>
            书籍详情:<input type="text" name="detail"  value="${book.getDetail()}"><br><br><br>
            <input type="submit" value="修改">
        </form>
  </body>
</html>

2.4一个简单的登录界面index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>首页</title>
     <style type="text/css">
            a {
                text-decoration: none;
                color: #00870b;
                font-size: 18px;
            }
            h3 {
                width: 180px;
                height: 38px;
                margin: 100px auto;
                text-align: center;
                line-height: 38px;
                background: deepskyblue;
                border-radius: 4px;
            }
        </style>
  </head>
  <body>
   <h3><a href="${pageContext.request.contextPath}/book/queryAll">全部书籍</a></h3>
  </body>
</html>

你可能感兴趣的:(ssm,spring,mysql,java,intellij,idea,ssm)