怎么用SSM框架实现信息管理系统

发布时间:2022-09-30 13:42:35 作者:iii
来源:亿速云 阅读:167

怎么用SSM框架实现信息管理系统

引言

在现代软件开发中,信息管理系统(Information Management System, IMS)是一个常见的应用场景。它通常用于管理、存储和检索各种类型的信息,如用户数据、产品信息、订单记录等。为了实现一个高效、可扩展的信息管理系统,选择合适的开发框架至关重要。SSM框架(Spring + Spring MVC + MyBatis)是Java开发中非常流行的一种组合,它结合了Spring的依赖注入和面向切面编程、Spring MVC的模型-视图-控制器架构以及MyBatis的持久层框架,能够帮助开发者快速构建高质量的Web应用。

本文将详细介绍如何使用SSM框架实现一个简单的信息管理系统。我们将从项目搭建、数据库设计、业务逻辑实现到前端展示,逐步讲解每个环节的实现细节。

1. 项目搭建

1.1 环境准备

在开始之前,确保你已经安装了以下工具和环境:

1.2 创建Maven项目

首先,使用Maven创建一个新的Java项目。在命令行中执行以下命令:

mvn archetype:generate -DgroupId=com.example -DartifactId=ims -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false

这将生成一个基本的Maven Web项目结构。

1.3 添加依赖

pom.xml文件中添加SSM框架所需的依赖:

<dependencies>
    <!-- Spring -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>5.3.21</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>5.3.21</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>5.3.21</version>
    </dependency>

    <!-- MyBatis -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.7</version>
    </dependency>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>2.0.6</version>
    </dependency>

    <!-- MySQL Connector -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.29</version>
    </dependency>

    <!-- Servlet API -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>4.0.1</version>
        <scope>provided</scope>
    </dependency>

    <!-- JSTL -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency>

    <!-- Logging -->
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>1.7.36</version>
    </dependency>
</dependencies>

1.4 配置Spring

src/main/resources目录下创建applicationContext.xml文件,配置Spring的核心容器:

<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:component-scan base-package="com.example.ims" />
</beans>

1.5 配置Spring MVC

src/main/webapp/WEB-INF目录下创建spring-servlet.xml文件,配置Spring MVC:

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

    <mvc:annotation-driven />
    <context:component-scan base-package="com.example.ims.controller" />

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/" />
        <property name="suffix" value=".jsp" />
    </bean>
</beans>

1.6 配置MyBatis

src/main/resources目录下创建mybatis-config.xml文件,配置MyBatis:

<configuration>
    <typeAliases>
        <package name="com.example.ims.model" />
    </typeAliases>
</configuration>

1.7 配置数据库连接

src/main/resources目录下创建database.properties文件,配置数据库连接信息:

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ims?useSSL=false&serverTimezone=UTC
jdbc.username=root
jdbc.password=yourpassword

applicationContext.xml中添加数据源和MyBatis的配置:

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="${jdbc.driver}" />
    <property name="url" value="${jdbc.url}" />
    <property name="username" value="${jdbc.username}" />
    <property name="password" value="${jdbc.password}" />
</bean>

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

<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="com.example.ims.mapper" />
</bean>

2. 数据库设计

2.1 创建数据库

在MySQL中创建一个名为ims的数据库:

CREATE DATABASE ims;
USE ims;

2.2 创建用户表

创建一个用户表user,用于存储用户信息:

CREATE TABLE user (
    id INT PRIMARY KEY AUTO_INCREMENT,
    username VARCHAR(50) NOT NULL,
    password VARCHAR(50) NOT NULL,
    email VARCHAR(100) NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

2.3 创建产品表

创建一个产品表product,用于存储产品信息:

CREATE TABLE product (
    id INT PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(100) NOT NULL,
    description TEXT,
    price DECIMAL(10, 2) NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

3. 业务逻辑实现

3.1 创建实体类

src/main/java/com/example/ims/model目录下创建实体类UserProduct

package com.example.ims.model;

import java.util.Date;

public class User {
    private Integer id;
    private String username;
    private String password;
    private String email;
    private Date createdAt;

    // Getters and Setters
}

public class Product {
    private Integer id;
    private String name;
    private String description;
    private Double price;
    private Date createdAt;

    // Getters and Setters
}

3.2 创建Mapper接口

src/main/java/com/example/ims/mapper目录下创建Mapper接口UserMapperProductMapper

package com.example.ims.mapper;

import com.example.ims.model.User;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface UserMapper {
    @Select("SELECT * FROM user")
    List<User> findAll();

    @Insert("INSERT INTO user (username, password, email) VALUES (#{username}, #{password}, #{email})")
    void insert(User user);

    @Update("UPDATE user SET username = #{username}, password = #{password}, email = #{email} WHERE id = #{id}")
    void update(User user);

    @Delete("DELETE FROM user WHERE id = #{id}")
    void delete(Integer id);
}

@Mapper
public interface ProductMapper {
    @Select("SELECT * FROM product")
    List<Product> findAll();

    @Insert("INSERT INTO product (name, description, price) VALUES (#{name}, #{description}, #{price})")
    void insert(Product product);

    @Update("UPDATE product SET name = #{name}, description = #{description}, price = #{price} WHERE id = #{id}")
    void update(Product product);

    @Delete("DELETE FROM product WHERE id = #{id}")
    void delete(Integer id);
}

3.3 创建Service层

src/main/java/com/example/ims/service目录下创建Service接口和实现类:

package com.example.ims.service;

import com.example.ims.model.User;

import java.util.List;

public interface UserService {
    List<User> findAll();
    void save(User user);
    void update(User user);
    void delete(Integer id);
}

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public List<User> findAll() {
        return userMapper.findAll();
    }

    @Override
    public void save(User user) {
        userMapper.insert(user);
    }

    @Override
    public void update(User user) {
        userMapper.update(user);
    }

    @Override
    public void delete(Integer id) {
        userMapper.delete(id);
    }
}

public interface ProductService {
    List<Product> findAll();
    void save(Product product);
    void update(Product product);
    void delete(Integer id);
}

@Service
public class ProductServiceImpl implements ProductService {
    @Autowired
    private ProductMapper productMapper;

    @Override
    public List<Product> findAll() {
        return productMapper.findAll();
    }

    @Override
    public void save(Product product) {
        productMapper.insert(product);
    }

    @Override
    public void update(Product product) {
        productMapper.update(product);
    }

    @Override
    public void delete(Integer id) {
        productMapper.delete(id);
    }
}

3.4 创建Controller层

src/main/java/com/example/ims/controller目录下创建Controller类UserControllerProductController

package com.example.ims.controller;

import com.example.ims.model.User;
import com.example.ims.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

@Controller
@RequestMapping("/users")
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping
    public String listUsers(Model model) {
        model.addAttribute("users", userService.findAll());
        return "user/list";
    }

    @GetMapping("/new")
    public String showUserForm(Model model) {
        model.addAttribute("user", new User());
        return "user/form";
    }

    @PostMapping
    public String saveUser(@ModelAttribute User user) {
        userService.save(user);
        return "redirect:/users";
    }

    @GetMapping("/edit/{id}")
    public String showEditForm(@PathVariable Integer id, Model model) {
        model.addAttribute("user", userService.findById(id));
        return "user/form";
    }

    @PostMapping("/update")
    public String updateUser(@ModelAttribute User user) {
        userService.update(user);
        return "redirect:/users";
    }

    @GetMapping("/delete/{id}")
    public String deleteUser(@PathVariable Integer id) {
        userService.delete(id);
        return "redirect:/users";
    }
}

@Controller
@RequestMapping("/products")
public class ProductController {
    @Autowired
    private ProductService productService;

    @GetMapping
    public String listProducts(Model model) {
        model.addAttribute("products", productService.findAll());
        return "product/list";
    }

    @GetMapping("/new")
    public String showProductForm(Model model) {
        model.addAttribute("product", new Product());
        return "product/form";
    }

    @PostMapping
    public String saveProduct(@ModelAttribute Product product) {
        productService.save(product);
        return "redirect:/products";
    }

    @GetMapping("/edit/{id}")
    public String showEditForm(@PathVariable Integer id, Model model) {
        model.addAttribute("product", productService.findById(id));
        return "product/form";
    }

    @PostMapping("/update")
    public String updateProduct(@ModelAttribute Product product) {
        productService.update(product);
        return "redirect:/products";
    }

    @GetMapping("/delete/{id}")
    public String deleteProduct(@PathVariable Integer id) {
        productService.delete(id);
        return "redirect:/products";
    }
}

4. 前端展示

4.1 创建JSP页面

src/main/webapp/WEB-INF/views目录下创建JSP页面:

4.2 用户列表页面

user/list.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>User List</title>
</head>
<body>
    <h1>User List</h1>
    <table border="1">
        <tr>
            <th>ID</th>
            <th>Username</th>
            <th>Email</th>
            <th>Actions</th>
        </tr>
        <c:forEach var="user" items="${users}">
            <tr>
                <td>${user.id}</td>
                <td>${user.username}</td>
                <td>${user.email}</td>
                <td>
                    <a href="/users/edit/${user.id}">Edit</a>
                    <a href="/users/delete/${user.id}">Delete</a>
                </td>
            </tr>
        </c:forEach>
    </table>
    <a href="/users/new">Add New User</a>
</body>
</html>

4.3 用户表单页面

user/form.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>User Form</title>
</head>
<body>
    <h1>User Form</h1>
    <form action="/users" method="post">
        <input type="hidden" name="id" value="${user.id}">
        <label for="username">Username:</label>
        <input type="text" id="username" name="username" value="${user.username}"><br>
        <label for="password">Password:</label>
        <input type="password" id="password" name="password" value="${user.password}"><br>
        <label for="email">Email:</label>
        <input type="email" id="email" name="email" value="${user.email}"><br>
        <button type="submit">Save</button>
    </form>
</body>
</html>

4.4 产品列表页面

product/list.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Product List</title>
</head>
<body>
    <h1>Product List</h1>
    <table border="1">
        <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Description</th>
            <th>Price</th>
            <th>Actions</th>
        </tr>
        <c:forEach var="product" items="${products}">
            <tr>
                <td>${product.id}</td>
                <td>${product.name}</td>
                <td>${product.description}</td>
                <td>${product.price}</td>
                <td>
                    <a href="/products/edit/${product.id}">Edit</a>
                    <a href="/products/delete/${product.id}">Delete</a>
                </td>
            </tr>
        </c:forEach>
    </table>
    <a href="/products/new">Add New Product</a>
</body>
</html>

4.5 产品表单页面

product/form.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Product Form</title>
</head>
<body>
    <h1>Product Form</h1>
    <form action="/products" method="post">
        <input type="hidden" name="id" value="${product.id}">
        <label for="name">Name:</label>
        <input type="text" id="name" name="name" value="${product.name}"><br>
        <label for="description">Description:</label>
        <textarea id="description" name="description">${product.description}</textarea><br>
        <label for="price">Price:</label>
        <input type="number" id="price" name="price" value="${product.price}"><br>
        <button type="submit">Save</button>
    </form>
</body>
</html>

5.

推荐阅读:
  1. 怎么用C语言实现学生信息管理系统
  2. 怎么用java实现学生信息管理系统

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

ssm

上一篇:win10两台电脑如何连接局域网

下一篇:SSM框架的基本原理与优势是什么

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》