使用SSM框架搭建Java Web应用

烟雨江南 2024-07-21 ⋅ 19 阅读

介绍

SSM是指Spring+SpringMVC+MyBatis这三个框架的整合,是目前比较流行且常用的Java后台开发框架。它将JavaWeb开发中常用的Spring、SpringMVC和MyBatis整合在一起,提供了一种较为优雅的开发方式,能够提高开发效率和代码的可维护性。

在本文中,我们将使用SSM框架来搭建一个简单的Java Web应用程序。

准备工作

在开始之前,我们需要确保以下软件已经安装和配置好:

  • JDK(Java Development Kit):确保已经安装并配置好环境变量。
  • Maven:用于构建和管理项目依赖。
  • IDE(Integrated Development Environment):推荐使用Eclipse或者IntelliJ IDEA开发环境,确保已经安装并配置好。

步骤

步骤一:创建Maven项目

  1. 打开IDE,选择创建一个新的Maven项目。
  2. 在项目配置中,填写GroupId和ArtifactId等信息。
  3. 点击完成,IDE将自动创建一个基本的Maven项目结构。

步骤二:添加SSM框架依赖

  1. 打开项目的pom.xml文件,添加以下依赖:
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-context</artifactId>
  <version>5.1.5.RELEASE</version>
</dependency>

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

<dependency>
  <groupId>org.mybatis.spring.boot</groupId>
  <artifactId>mybatis-spring-boot-starter</artifactId>
  <version>2.1.0</version>
</dependency>

<dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
  <version>8.0.15</version>
</dependency>
  1. 保存并更新Maven项目,等待依赖下载完成。

步骤三:配置数据库连接

  1. 在项目的resources目录下,创建一个名为application.properties(或者application.yml)的文件。
  2. 在配置文件中添加以下内容来配置数据库连接:
# 数据库连接配置
spring.datasource.url=jdbc:mysql://localhost:3306/testdb?useSSL=false&useUnicode=true&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

步骤四:创建数据库表和实体类

  1. 在数据库中创建一个名为user的表,表结构如下:
CREATE TABLE `user` (
  `id` int(11) NOT NULL,
  `name` varchar(50) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  `gender` varchar(10) DEFAULT NULL,
  `email` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
  1. 在Java项目的com.example包下,创建一个名为User的实体类:
public class User {
    private Integer id;
    private String name;
    private Integer age;
    private String gender;
    private String email;

    // getter和setter方法...
}

步骤五:创建Dao层和Mapper文件

  1. 在Java项目的com.example.dao包下,创建一个名为UserDao的接口:
public interface UserDao {
    /**
     * 查询所有用户
     */
    List<User> findAll();

    /**
     * 添加用户
     */
    void addUser(User user);

    /**
     * 根据id删除用户
     */
    void deleteUser(Integer id);

    /**
     * 根据id查询用户
     */
    User findUserById(Integer id);
}
  1. 在resources目录下,创建一个名为UserMapper.xml的文件,在文件中编写对应的SQL语句:
<mapper namespace="com.example.dao.UserDao">
    <select id="findAll" resultType="com.example.model.User">
        SELECT * FROM user
    </select>
    
    <insert id="addUser">
        INSERT INTO user(name, age, gender, email)
        VALUES (#{name}, #{age}, #{gender}, #{email})
    </insert>
    
    <delete id="deleteUser">
        DELETE FROM user WHERE id=#{id}
    </delete>
    
    <select id="findUserById" resultType="com.example.model.User">
        SELECT * FROM user WHERE id=#{id}
    </select>
</mapper>

步骤六:创建Service层和Controller层

  1. 在Java项目的com.example.service包下,创建一个名为UserService的接口:
public interface UserService {
    List<User> findAll();

    void addUser(User user);

    void deleteUser(Integer id);

    User findUserById(Integer id);
}
  1. 在Java项目的com.example.service.impl包下,创建一个名为UserServiceImpl的实现类:
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;

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

    @Override
    public void addUser(User user) {
        userDao.addUser(user);
    }

    @Override
    public void deleteUser(Integer id) {
        userDao.deleteUser(id);
    }

    @Override
    public User findUserById(Integer id) {
        return userDao.findUserById(id);
    }
}
  1. 在Java项目的com.example.controller包下,创建一个名为UserController的控制器类:
@Controller
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping("/user/list")
    public String list(Model model) {
        List<User> userList = userService.findAll();
        model.addAttribute("userList", userList);
        return "user/list";
    }

    @GetMapping("/user/add")
    public String addForm() {
        return "user/add";
    }

    @PostMapping("/user/add")
    public String addUser(User user) {
        userService.addUser(user);
        return "redirect:/user/list";
    }

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

    @GetMapping("/user/edit/{id}")
    public String editForm(@PathVariable("id") Integer id, Model model) {
        User user = userService.findUserById(id);
        model.addAttribute("user", user);
        return "user/edit";
    }
}

步骤七:创建视图页面

  1. 在resources目录下,创建一个名为templates/user的文件夹,用于存放用户相关的视图页面。
  2. 在该文件夹下,创建一个名为list.html的文件,用于展示用户列表:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<body>
<table>
  <tr>
    <th>ID</th>
    <th>姓名</th>
    <th>年龄</th>
    <th>性别</th>
    <th>邮箱</th>
    <th>操作</th>
  </tr>
  <tr th:each="user: ${userList}">
    <td th:text="${user.id}"></td>
    <td th:text="${user.name}"></td>
    <td th:text="${user.age}"></td>
    <td th:text="${user.gender}"></td>
    <td th:text="${user.email}"></td>
    <td>
      <a th:href="@{/user/edit/{id}(id=${user.id})}">编辑</a>
      <a th:href="@{/user/delete/{id}(id=${user.id})}">删除</a>
    </td>
  </tr>
</table>
</body>
</html>
  1. 在该文件夹下,创建一个名为add.html的文件,用于添加用户:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<body>
<form action="/user/add" method="post">
  <div>
    <label>姓名:</label>
    <input type="text" name="name" required/>
  </div>
  <div>
    <label>年龄:</label>
    <input type="number" name="age" required/>
  </div>
  <div>
    <label>性别:</label>
    <select name="gender" required>
      <option value="男">男</option>
      <option value="女">女</option>
    </select>
  </div>
  <div>
    <label>邮箱:</label>
    <input type="email" name="email" required/>
  </div>
  <input type="submit" value="添加"/>
</form>
</body>
</html>
  1. 在该文件夹下,创建一个名为edit.html的文件,用于编辑用户:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<body>
<form action="/user/edit" method="post">
  <input type="hidden" name="id" th:value="${user.id}"/>
  <div>
    <label>姓名:</label>
    <input type="text" name="name" th:value="${user.name}" required/>
  </div>
  <div>
    <label>年龄:</label>
    <input type="number" name="age" th:value="${user.age}" required/>
  </div>
  <div>
    <label>性别:</label>
    <select name="gender" required>
      <option value="男" th:selected="${user.gender=='男'}">男</option>
      <option value="女" th:selected="${user.gender=='女'}">女</option>
    </select>
  </div>
  <div>
    <label>邮箱:</label>
    <input type="email" name="email" th:value="${user.email}" required/>
  </div>
  <input type="submit" value="保存"/>
</form>
</body>
</html>

步骤八:配置Spring MVC和MyBatis

  1. 在项目的src/main/resources目录下,创建一个名为springmvc.xml的Spring MVC配置文件:
<!-- 定义组件扫描的包 -->
<context:component-scan base-package="com.example.controller"/>

<!-- 开启MVC注解支持 -->
<mvc:annotation-driven/>

<!-- 配置视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  <property name="prefix" value="/WEB-INF/views/"/>
  <property name="suffix" value=".html"/>
</bean>
  1. 在项目的src/main/resources目录下,创建一个名为mybatis-config.xml的MyBatis配置文件:
<configuration>
  <settings>
    <setting name="mapUnderscoreToCamelCase" value="true"/>
  </settings>
</configuration>

步骤九:配置Spring和MyBatis的整合

  1. 在项目的src/main/resources目录下,创建一个名为applicationContext.xml的Spring配置文件:
<!-- 定义组件扫描的包 -->
<context:component-scan base-package="com.example.service.impl,com.example.dao"/>

<!-- 加载数据库配置文件 -->
<context:property-placeholder location="classpath:application.properties"/>

<!-- 配置数据源 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  <property name="driverClassName" value="${spring.datasource.driver-class-name}"/>
  <property name="url" value="${spring.datasource.url}"/>
  <property name="username" value="${spring.datasource.username}"/>
  <property name="password" value="${spring.datasource.password}"/>
</bean>

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

<!-- 配置MyBatis的MapperScannerConfigurer -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
  <property name="basePackage" value="com.example.dao"/>
</bean>
  1. springmvc.xml中添加以下代码,将Spring MVC和MyBatis整合起来:
<!-- 引入Spring和MyBatis的配置文件 -->
<import resource="classpath:application.xml"/>
<import resource="classpath:applicationContext.xml"/>

步骤十:启动项目

  1. 在IDE中,启动Tomcat服务器。
  2. 打开浏览器,访问http://localhost:8080/user/list,即可看到用户列表页面。

总结

通过以上步骤,我们成功地使用SSM框架搭建了一个Java Web应用。SSM框架的优势在于它的层级清晰,功能完善,易于维护和扩展。希望本文能帮助您快速入门SSM框架,并在实际项目中发挥作用。


全部评论: 0

    我有话说: