Spring——第一个Spring-Web项目(三层架构实现前后端数据交互)

本文涉及的产品
RDS DuckDB + QuickBI 企业套餐,8核32GB + QuickBI 专业版
RDS MySQL DuckDB 分析主实例,基础系列 4核8GB
RDS AI 助手,专业版
简介: Spring——第一个Spring-Web项目(三层架构实现前后端数据交互)

文章目录:


1.写在开头

2.项目的大体步骤

2.1 项目大致结构

2.2 IDEA中使用Maven创建一个web

2.3 在pom.xml文件中加入依赖

2.4 创建Student实体类

2.5 创建dao接口和对应的mapper文件

2.5.1 StudentDao接口

2.5.2 StudentDao.xml

2.6 创建mybatis主配置文件

2.7 创建service接口和实现类

2.7.1 StudentService接口

2.7.2 StudentServiceImpl实现类

2.8 创建jdbc外部属性配置文件、spring配置文件

2.9 创建servlet

2.9.1 AddStudentServlet——对应添加学生操作

2.9.2 QueryStudentServlet——对应查询学生操作

2.9.3 在web.xml中注册servlet和监听器

2.10 创建jsp页面——提交请求参数、显示请求处理结果

2.10.1 提交请求参数

2.10.2 显示请求处理结果——对应AddStudentServlet

2.10.3 显示请求处理结果——对应QueryStudentServlet

2.11 启动tomcat,测试!!!

2.11.1 AddStudentServlet的测试结果

2.11.2 QueryStudentServlet的测试结果


1.写在开头


在学完了Java Web(Tomcat、Servlet、JSP、MVC)、MyBatis、Spring这些内容之后,大脑里基本有了三层架构的整体框架,所以这里就想着去试着写一个简单的Spring-Web项目,实现一下前端页面和后端数据库的交互。


刚刚开始学,文章中有写的不到位的地方,还希望大佬指出,感谢感谢!!!


2.项目的大体步骤


2.1 项目大致结构


controller包:界面层

dao包:数据库访问层

service包:业务逻辑层

entity包:每一个Java类对应于数据库中的一个表

resources目录:mybatis主配置文件、spring配置文件、jdbc外部属性配置文件

webapp:web项目相关内容,注册servlet、监听器、jsp页面


2.2 IDEA中使用Maven创建一个web


2.3 在pom.xml文件中加入依赖


<dependencies>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>4.0.1</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>jsp-api</artifactId>
      <version>2.2.1-b03</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>5.2.5.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>5.2.5.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>5.2.5.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.3.1</version>
    </dependency>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.1</version>
    </dependency>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.9</version>
    </dependency>
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.1.12</version>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <!-- 监听器的依赖 -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>5.2.5.RELEASE</version>
    </dependency>
<build>
    <resources>
      <resource>
        <directory>src/main/java</directory><!--所在的目录-->
        <includes><!--包括目录下的.properties,.xml 文件都会扫描到-->
          <include>**/*.properties</include>
          <include>**/*.xml</include>
        </includes>
        <filtering>false</filtering>
      </resource>
    </resources>
</build>

2.4 创建Student实体类


1.package com.bjpowernode.entity;
/**
 *
 */
public class Student {
    private Integer id;
    private String name;
    private Integer age;
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}


2.5 创建dao接口和对应的mapper文件


2.5.1 StudentDao接口

package com.bjpowernode.dao;
import com.bjpowernode.entity.Student;
import org.apache.ibatis.annotations.Param;
/**
 *
 */
public interface StudentDao {
    int insertStudent(Student student);
    Student selectById(@Param("studentId") Integer id);
}


2.5.2 StudentDao.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.bjpowernode.dao.StudentDao">
    <!-- 使用insert、update、delete、select标签编写sql语句 -->
    <insert id="insertStudent">
        insert into student2(name,age) values (#{name},#{age})
    </insert>
    <select id="selectById" resultType="com.bjpowernode.entity.Student">
        select id,name,age
        from student2
        where id=#{studentId}
    </select>
</mapper>


2.6 创建mybatis主配置文件


<?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>
    <mappers>
        <mapper resource="com/bjpowernode/dao/StudentDao.xml"/>
    </mappers>
</configuration>


2.7 创建service接口和实现类


2.7.1 StudentService接口

package com.bjpowernode.service;
import com.bjpowernode.entity.Student;
/**
 *
 */
public interface StudentService {
    int addStudent(Student student);
    Student findStudent(Integer id);
}


2.7.2 StudentServiceImpl实现类


package com.bjpowernode.service.impl;
import com.bjpowernode.dao.StudentDao;
import com.bjpowernode.entity.Student;
import com.bjpowernode.service.StudentService;
/**
 *
 */
public class StudentServiceImpl implements StudentService {
    private StudentDao studentDao;
    public void setStudentDao(StudentDao studentDao) {
        this.studentDao = studentDao;
    }
    @Override
    public int addStudent(Student student) {
        int rows=studentDao.insertStudent(student);
        return rows;
    }
    @Override
    public Student findStudent(Integer id) {
        Student student=studentDao.selectById(id);
        return student;
    }
}


2.8 创建jdbc外部属性配置文件、spring配置文件


jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm?useUnicode=true&amp;characterEncoding=UTF-8
jdbc.username=root
jdbc.password=12345678
<?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">
    <context:property-placeholder location="classpath:jdbc.properties" />
    <bean id="myDataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
        <property name="driverClassName" value="${jdbc.driverClassName}"/>
        <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="myDataSource"/>
        <property name="configLocation" value="classpath:mybatis.xml"/>
    </bean>
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        <property name="basePackage" value="com.bjpowernode.dao"/>
    </bean>
    <bean id="studentService" class="com.bjpowernode.service.impl.StudentServiceImpl">
        <property name="studentDao" ref="studentDao"/>
    </bean>
</beans>

2.9 创建servlet


2.9.1 AddStudentServlet——对应添加学生操作

package com.bjpowernode.controller;
import com.bjpowernode.entity.Student;
import com.bjpowernode.service.StudentService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
public class AddStudentServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        String strName=request.getParameter("name");
        String strAge=request.getParameter("age");
        //获取全局作用域对象,确保spring容器对象只创建一次
        ServletContext servletContext=getServletContext();
        //使用spring提供的工具方法,获取容器对象
        WebApplicationContext ctx= WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
        StudentService service= (StudentService) ctx.getBean("studentService");
        Student student=new Student();
        student.setName(strName);
        student.setAge(Integer.valueOf(strAge));
        service.addStudent(student);
        //给用户显示请求的处理结果
        request.getRequestDispatcher("/show.jsp").forward(request,response);
    }
}


2.9.2 QueryStudentServlet——对应查询学生操作

package com.bjpowernode.controller;
import com.bjpowernode.entity.Student;
import com.bjpowernode.service.StudentService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
 *
 */
public class QueryStudentServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        String stuId=request.getParameter("stuid");
        //获取全局作用域对象,确保spring容器对象只创建一次
        ServletContext servletContext=getServletContext();
        //使用spring提供的工具方法,获取容器对象
        WebApplicationContext ctx= WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
        StudentService service= (StudentService) ctx.getBean("studentService");
        Student student=service.findStudent(Integer.parseInt(stuId));
        System.out.println("student对象===" + student);
        request.setAttribute("stu",student);
        request.getRequestDispatcher("/second.jsp").forward(request,response);
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    }
}


2.9.3 在web.xml中注册servlet和监听器

<?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">
    <servlet>
        <servlet-name>AddStudentServlet</servlet-name>
        <servlet-class>com.bjpowernode.controller.AddStudentServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>AddStudentServlet</servlet-name>
        <url-pattern>/add</url-pattern>
    </servlet-mapping>
    <servlet>
        <servlet-name>QueryStudentServlet</servlet-name>
        <servlet-class>com.bjpowernode.controller.QueryStudentServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>QueryStudentServlet</servlet-name>
        <url-pattern>/query</url-pattern>
    </servlet-mapping>
    <!--
        自定义容器使用的配置文件路径
        context-param: 上下文参数,给监听器提供参数的
    -->
    <context-param>
        <!-- 固定名称,表示自定义spring配置文件的路径 -->
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring-beans.xml</param-value>
    </context-param>
    <!-- 声明监听器对象 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
</web-app>


2.10 创建jsp页面——提交请求参数、显示请求处理结果


2.10.1 提交请求参数

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <div align="center">
        <p>添加学生</p>
        <form action="/springWeb/add" method="post">
            姓名:<input type="text" name="name"><br/>
            年龄:<input type="text" name="age"><br/>
            <input type="submit" value="注册学生">
        </form>
        <br/><br/>
        <p>查询学生</p>
        <form action="/springWeb/query" method="get">
            学生id:<input type="text" name="stuid"><br/>
            <input type="submit" value="查询学生">
        </form>
    </div>
</body>
</html>


2.10.2 显示请求处理结果——对应AddStudentServlet

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    /show.jsp  <p>学生注册成功!!!</p>
</body>
</html>


2.10.3 显示请求处理结果——对应QueryStudentServlet

<%@ page import="com.bjpowernode.entity.Student" %>
<%@ page contentType="text/html;charset=utf-8" language="java" %>
<html>
<head>
    <title>$</title>
</head>
<body>
    <%
        Student student= (Student) request.getAttribute("stu");
    %>
    查询的结果:<%=student%>
</body>
</html>


2.11 启动tomcat,测试!!!

2.11.1 AddStudentServlet的测试结果



2.11.2 QueryStudentServlet的测试结果

以上就是这个很小很小的项目的全部步骤,第一次将Java Web、Spring、MyBatis这些知识综合在了一起学习,感觉还是很不错的!!!😄😄😄

相关实践学习
每个IT人都想学的“Web应用上云经典架构”实战
本实验从Web应用上云这个最基本的、最普遍的需求出发,帮助IT从业者们通过“阿里云Web应用上云解决方案”,了解一个企业级Web应用上云的常见架构,了解如何构建一个高可用、可扩展的企业级应用架构。
MySQL数据库入门学习
本课程通过最流行的开源数据库MySQL带你了解数据库的世界。 &nbsp; 相关的阿里云产品:云数据库RDS MySQL 版 阿里云关系型数据库RDS(Relational Database Service)是一种稳定可靠、可弹性伸缩的在线数据库服务,提供容灾、备份、恢复、迁移等方面的全套解决方案,彻底解决数据库运维的烦恼。 了解产品详情:&nbsp;https://www.aliyun.com/product/rds/mysql&nbsp;
相关文章
|
8月前
|
安全 Java API
Java Web 在线商城项目最新技术实操指南帮助开发者高效完成商城项目开发
本项目基于Spring Boot 3.2与Vue 3构建现代化在线商城,涵盖技术选型、核心功能实现、安全控制与容器化部署,助开发者掌握最新Java Web全栈开发实践。
775 1
|
9月前
|
JavaScript Java 微服务
现代化 Java Web 在线商城项目技术方案与实战开发流程及核心功能实现详解
本项目基于Spring Boot 3与Vue 3构建现代化在线商城系统,采用微服务架构,整合Spring Cloud、Redis、MySQL等技术,涵盖用户认证、商品管理、购物车功能,并支持Docker容器化部署与Kubernetes编排。提供完整CI/CD流程,助力高效开发与扩展。
1042 64
|
10月前
|
Java 关系型数据库 数据库连接
Spring Boot项目集成MyBatis Plus操作PostgreSQL全解析
集成 Spring Boot、PostgreSQL 和 MyBatis Plus 的步骤与 MyBatis 类似,只不过在 MyBatis Plus 中提供了更多的便利功能,如自动生成 SQL、分页查询、Wrapper 查询等。
1007 2
|
10月前
|
Java 测试技术 Spring
简单学Spring Boot | 博客项目的测试
本内容介绍了基于Spring Boot的博客项目测试实践,重点在于通过测试驱动开发(TDD)优化服务层代码,提升代码质量和功能可靠性。案例详细展示了如何为PostService类编写测试用例、运行测试并根据反馈优化功能代码,包括两次优化过程。通过TDD流程,确保每项功能经过严格验证,增强代码可维护性与系统稳定性。
380 0
|
10月前
|
存储 Java 数据库连接
简单学Spring Boot | 博客项目的三层架构重构
本案例通过采用三层架构(数据访问层、业务逻辑层、表现层)重构项目,解决了集中式开发导致的代码臃肿问题。各层职责清晰,结合依赖注入实现解耦,提升了系统的可维护性、可测试性和可扩展性,为后续接入真实数据库奠定基础。
780 0
|
10月前
|
安全 JavaScript Java
java Web 项目完整案例实操指南包含从搭建到部署的详细步骤及热门长尾关键词解析的实操指南
本项目为一个完整的JavaWeb应用案例,采用Spring Boot 3、Vue 3、MySQL、Redis等最新技术栈,涵盖前后端分离架构设计、RESTful API开发、JWT安全认证、Docker容器化部署等内容,适合掌握企业级Web项目全流程开发与部署。
891 0
|
存储 安全 NoSQL
Spring中国教育管理中心-Apache Cassandra 的 Spring 数据教程十四
Spring中国教育管理中心-Apache Cassandra 的 Spring 数据教程十四
|
存储 NoSQL Java
Spring中国教育管理中心-Apache Cassandra 的 Spring 数据教程十三
Spring中国教育管理中心-Apache Cassandra 的 Spring 数据教程十三
|
存储 NoSQL Java
Spring中国教育管理中心-Apache Cassandra 的 Spring 数据教程十二
Spring中国教育管理中心-Apache Cassandra 的 Spring 数据教程十二
|
存储 NoSQL Java
Spring中国教育管理中心-Apache Cassandra 的 Spring 数据教程十一
Spring中国教育管理中心-Apache Cassandra 的 Spring 数据教程十一

热门文章

最新文章