实例!使用Idea创建SSM框架的Maven项目

举报
穆雄雄 发表于 2022/12/10 20:21:28 2022/12/10
【摘要】 ​编辑大家好,我是雄雄,欢迎关注微信公众号【雄雄的小课堂】。前言书接前文,昨天带着大家下载且配置了maven,以及在idea中创建maven项目,今天,我们就结合ssm框架,在idea中实现一个增删改查案例。昨天的文章:手把手教你搭建Maven项目 01配置pom文件通常,我们需要使用ssm框架的时候,需要加载一系列的jar包,在未使用maven的时候,我们则采用的是将所需jar包统统复制到...

​编辑

大家好,我是雄雄,欢迎关注微信公众号【雄雄的小课堂】。

前言

书接前文,昨天带着大家下载且配置了maven,以及在idea中创建maven项目,今天,我们就结合ssm框架,在idea中实现一个增删改查案例。

昨天的文章:手把手教你搭建Maven项目

01

配置pom文件

通常,我们需要使用ssm框架的时候,需要加载一系列的jar包,在未使用maven的时候,我们则采用的是将所需jar包统统复制到项目的lib目录中,现在我们不必那样做了,只需要简单的在pom文件中配置即可。

那么,怎么配置呢?

我们以mysql的驱动jar为例(其他jar包配置方式一样,可执行按此配置),mysql的驱动jar包我采用的是:mysql-connector-java-8.0.23,配置方式如下:

1)maven官网为我们提供了jar包在pom文件中的配置方式,打开官网:https://search.maven.org/,我们在输入框中输入需要配置的jar包名,如下:

​编辑

​编辑

​编辑

可以在左边框中的下拉列表里选择版本,在右边的Apache Maven下面,复制所有代码。

复制到项目中pom文件的这里:

​编辑

​编辑

如果你不知道ssm需要哪些jar包,可以去百度搜索,pom中配置方式是一样的,在这就不一一列举了,下面是整个pom.xml文件的代码:

<?xml version="1.0" encoding="UTF-8"?>

<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.xiongxiong</groupId>
  <artifactId>BookManageSys</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>BookManageSys Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
  </properties>

  <dependencies>
    <!--配置jar包-->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.23</version>
    </dependency>
    <!--spring的jar包=-->
    <!--springmvc的jar包-->
    <dependency>
      <groupId>javaee</groupId>
      <artifactId>javaee-api</artifactId>
      <version>5</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>4.2.5.RELEASE</version>
    </dependency>


    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-beans</artifactId>
      <version>4.2.2.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>4.2.2.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>4.1.9.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aspects</artifactId>
      <version>4.2.1.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context-support</artifactId>
      <version>4.1.9.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>4.2.3.release</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>4.1.9.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>4.2.3.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>4.1.9.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.2.2</version>
    </dependency>

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

    <dependency>
      <groupId>org.javassist</groupId>
      <artifactId>javassist</artifactId>
      <version>3.17.1-GA</version>
    </dependency>

    <dependency>
      <groupId>cglib</groupId>
      <artifactId>cglib</artifactId>
      <version>2.2.2</version>
    </dependency>

    <dependency>
      <groupId>c3p0</groupId>
      <artifactId>c3p0</artifactId>
      <version>0.9.1.2</version>
    </dependency>

    <!--加载jstl的包-->
    <dependency>
      <groupId>jstl</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>
  </dependencies>


  <build>
    <finalName>BookManageSys</finalName>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>
        <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-war-plugin</artifactId>
          <version>3.2.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>

这是最后导入的jar包:

​编辑

02

在main目录中创建resources资源文件夹

该资源文件夹用来存放ssm的配置文件,applicationContext.xml,springmvc-servlet.xml,mybatis-config.xml

​编辑

各配置文件代码如下:

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:mvc="http://www.springframework.org/schema/mvc"
        xmlns:context="http://www.springframework.org/schema/context"
        xsi:schemaLocation="
  http://www.springframework.org/schema/beans 
  http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
  http://www.springframework.org/schema/mvc 
  http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
  http://www.springframework.org/schema/context 
  http://www.springframework.org/schema/context/spring-context-3.1.xsd
  ">

    <!-- 配置数据源-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql://localhost:3306/schooldb"></property>
        <property name="username" value="root"></property>
        <property name="password" value="root"></property>
    </bean>

    <!--sqlSessionFactory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <property name="configLocation" value="classpath:mybatis-config.xml"></property>
        <property name="mapperLocations">
            <list>
                <value>classpath:com/dao/*.xml</value>
            </list>
        </property>
    </bean>

    <!-- 配置自动映射器 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.dao"></property>
    </bean>

    <!-- 扫描所有注解信息 -->
    <context:component-scan base-package="com.dao,com.service,com.web"/>
    <mvc:annotation-driven/>

</beans>

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:p="http://www.springframework.org/schema/p"
        xmlns:aop="http://www.springframework.org/schema/aop"
        xmlns:mvc="http://www.springframework.org/schema/mvc"
        xmlns:context="http://www.springframework.org/schema/context"
        xsi:schemaLocation="
  http://www.springframework.org/schema/beans 
  http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
  http://www.springframework.org/schema/p 
  http://www.springframework.org/schema/p/spring-p-3.1.xsd
  http://www.springframework.org/schema/aop 
  http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
  http://www.springframework.org/schema/mvc 
  http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
  http://www.springframework.org/schema/context 
  http://www.springframework.org/schema/context/spring-context-3.1.xsd
  ">

    <!-- 扫描注解 -->
    <context:component-scan base-package="com.web,com.dao,com.service"/>
    <mvc:annotation-driven/>
    <!--扫描静态资源文件-->
    <mvc:default-servlet-handler/>

    <!-- 配置前缀和后缀 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>

</beans>

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>
        <!-- 打印sql语句 -->
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>
    <!-- 起别名 -->
    <typeAliases>
        <package name="com.entity"/>
    </typeAliases>

</configuration>

​编辑

03

配置web.xml文件

web.xml文件所在的路径:src/main/webapp/WEB/INF/wen.xml

代码如下:

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >


<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">
  <display-name>Archetype Created Web Application</display-name>
  <welcome-file-list>
    <welcome-file>/</welcome-file>
  </welcome-file-list>

  <!-- springmvc的配置 -->
  <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:springmvc-servlet.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

  <!-- spring -->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
  </context-param>
  <!-- 监听配置 -->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

  <!-- 解决springmvc传递值乱码问题 -->
  <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>
</web-app>

04

创建src资源资源文件夹

在main文件夹中创建资源文件夹src,且在里面创建实体层、Dao层、Service层和web层。

​编辑

下面我们来在src中创建包com(包名随便起),在com中分别创建entity、dao、service以及web包(Package),分别在各个包中创建对应的类,其目录结构如下:

​编辑

下面是各个类的代码:

BookManage.java:

package com.entity;

import org.springframework.format.annotation.DateTimeFormat;

import java.util.Date;

public class BookManage {

    private int bid;
    private String bname;
    private String bauthor;

    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private Date btime;
    private int btype;

    public int getBid() {
        return bid;
    }

    public void setBid(int bid) {
        this.bid = bid;
    }

    public String getBname() {
        return bname;
    }

    public void setBname(String bname) {
        this.bname = bname;
    }

    public String getBauthor() {
        return bauthor;
    }

    public void setBauthor(String bauthor) {
        this.bauthor = bauthor;
    }

    public Date getBtime() {
        return btime;
    }

    public void setBtime(Date btime) {
        this.btime = btime;
    }

    public int getBtype() {
        return btype;
    }

    public void setBtype(int btype) {
        this.btype = btype;
    }
}

BookManageMapper.java

package com.dao;

import com.entity.BookManage;

import java.util.List;

public interface BookManageMapper {

    //查询全部
    List<BookManage> findBookAll();

    //添加
    int addBook(BookManage bookManage);

    //删除
    int delBook(int bid);
}

BookManageMapper.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.dao.BookManageMapper">

    <!-- 查询全部 -->
    <select id="findBookAll" resultType="BookManage">
        select * from BookManage;
    </select>
    <!-- 添加 -->
    <insert id="addBook" parameterType="BookManage">
        insert into bookmanage (bname,bauthor,btime,btype)
        value(#{bname},#{bauthor},#{btime},#{btype});
    </insert>

    <!-- 删除 -->
    <delete id="delBook" parameterType="int">
        delete from BookManage where bid = #{bid};
    </delete>

</mapper>

IBookManageService.java

package com.service;

import com.entity.BookManage;

import java.util.List;

public interface IBookManageService {


    //查询全部
    List<BookManage> findBookAll();

    //添加
    int addBook(BookManage bookManage);

    //删除
    int delBook(int bid);
}

BookManageServiceImpl.java

package com.service.impl;


import com.dao.BookManageMapper;
import com.entity.BookManage;
import com.service.IBookManageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;



import java.util.List;

@Service("bookManageService")
public class BookManageServiceImpl implements IBookManageService {

    @Autowired
    private BookManageMapper bookManageMapper;

    @Override
    public List<BookManage> findBookAll() {
        return bookManageMapper.findBookAll();
    }

    @Override
    public int addBook(BookManage bookManage) {
        return bookManageMapper.addBook(bookManage);
    }

    @Override
    public int delBook(int bid) {
        return bookManageMapper.delBook(bid);
    }

    public BookManageMapper getBookManageMapper() {
        return bookManageMapper;
    }

    public void setBookManageMapper(BookManageMapper bookManageMapper) {
        this.bookManageMapper = bookManageMapper;
    }
}

IndexController.java

package com.web;

import com.entity.BookManage;
import com.service.IBookManageService;
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 java.util.List;

@Controller
@RequestMapping("/")
public class IndexController {

    //创建Service的对象
    @Autowired
    private IBookManageService bookManageService;

    //默认进入首页
    @RequestMapping("/")
    public String index(Model model){

        List<BookManage> bookManageList =
                bookManageService.findBookAll();
        model.addAttribute("bookManageList",bookManageList);
        return "index";
    }

    //删除
    @RequestMapping("delBook")
    public String delBook(Model model,int bid){
        bookManageService.delBook(bid);
        index(model);
        return "index";
    }
    //添加
    @RequestMapping("addBook")
    public String addBook(BookManage bookManage,Model model){
        bookManageService.addBook(bookManage);
        index(model);
        return "index";
    }


    public IBookManageService getBookManageService() {
        return bookManageService;
    }

    public void setBookManageService(IBookManageService bookManageService) {
        this.bookManageService = bookManageService;
    }
}

05

引入jQuery环境

将jquery的环境拷贝到项目中的webapp下:

​编辑

06

首页

修改index.jsp,使其实现进入页面即查询数据库中所有数据功能,代码如下:

<%--
  Created by IntelliJ IDEA.
  User: 24519
  Date: 2021/1/20
  Time: 10:38
  To change this template use File | Settings | File Templates.
--%>  
<%@ page isELIgnored="false"%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="f" uri="http://java.sun.com/jsp/jstl/fmt" %>
<html>
  <head>
    <title>首页</title>
  </head>
  <body>
    <h1>图书信息</h1>
  <table border="1">
    <tr>
      <td>图书名称</td>
      <td>图书作者</td>
      <td>购买时间</td>
      <td>图书分类</td>
      <td>操作</td>
    </tr>
    <c:forEach items="${bookManageList}" var="book">
      <tr>
        <td>${book.bname}</td>
        <td>${book.bauthor}</td>
        <td>
            <f:formatDate value="${book.btime}" pattern="yyyy-MM-dd"></f:formatDate>
            </td>
        <td>
            <c:if test="${book.btype==1}">
              计算机/软件
            </c:if>
          <c:if test="${book.btype==2}">
            小说/文摘
          </c:if>
          <c:if test="${book.btype==3}">
            杂项
          </c:if>
        </td>
        <td><a href="delBook?bid=${book.bid}">删除</a></td>
      </tr>
    </c:forEach>

  </table>
  <a href="addBook.jsp" style="color:red">新增图书信息</a>
  <script src="js/jquery-1.12.4.js" type="text/javascript"></script>
  <script type="text/javascript">
    $(function(){
        $("tr:even").css("background","green");
        $("tr:first").css("background","blue");
    });
  </script>
  </body>
</html>

07

添加图书的页面

创建添加数据的页面addBook.jsp,代码如下:

注意,addBook.jsp和index.jsp都需要放在webapp目录下。

08

配置tomcat

配置tomcat

​编辑

​编辑

​编辑

​编辑

​编辑

​编辑

测试发现,正常运行。

最后附数据库脚本代码:

/*
SQLyog Professional v12.08 (32 bit)
MySQL - 5.5.27 : Database - schooldb
*********************************************************************
*/


/*!40101 SET NAMES utf8 */;

/*!40101 SET SQL_MODE=''*/;

/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
CREATE DATABASE /*!32312 IF NOT EXISTS*/`schooldb` /*!40100 DEFAULT CHARACTER SET utf8 */;

USE `schooldb`;

/*Table structure for table `bookmanage` */

DROP TABLE IF EXISTS `bookmanage`;

CREATE TABLE `bookmanage` (
  `bid` int(11) NOT NULL AUTO_INCREMENT,
  `bname` varchar(40) NOT NULL,
  `bauthor` varchar(40) NOT NULL,
  `btime` datetime NOT NULL,
  `btype` int(11) NOT NULL,
  PRIMARY KEY (`bid`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;

/*Data for the table `bookmanage` */

insert  into `bookmanage`(`bid`,`bname`,`bauthor`,`btime`,`btype`) values (1,'三国演义','罗贯中','2021-09-08 00:00:00',2),(2,'水浒传','施耐庵','2021-09-08 00:00:00',2),(3,'狂人日记','魯迅','2021-09-08 00:00:00',3),(4,'改善java的151个建议','秦少波','2021-09-08 00:00:00',1);

/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;

今天的分享就到这里了,明天见!

【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。