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

本文涉及的产品
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
云数据库 RDS MySQL,高可用系列 2核4GB
云数据库 RDS PostgreSQL,高可用系列 2核4GB
简介: 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;
相关文章
|
3月前
|
数据采集 缓存 前端开发
如何开发门店业绩上报管理系统中的商品数据板块?(附架构图+流程图+代码参考)
本文深入讲解门店业绩上报系统中商品数据板块的设计与实现,涵盖商品类别、信息、档案等内容,详细阐述技术架构、业务流程、数据库设计及开发技巧,并提供完整代码示例,助力企业构建稳定、可扩展的商品数据系统。
|
2月前
|
数据采集 机器学习/深度学习 搜索推荐
MIT新论文:数据即上限,扩散模型的关键能力来自图像统计规律,而非复杂架构
MIT与丰田研究院研究发现,扩散模型的“局部性”并非源于网络架构的精巧设计,而是自然图像统计规律的产物。通过线性模型仅学习像素相关性,即可复现U-Net般的局部敏感模式,揭示数据本身蕴含生成“魔法”。
159 3
MIT新论文:数据即上限,扩散模型的关键能力来自图像统计规律,而非复杂架构
|
2月前
|
Java 数据库 数据安全/隐私保护
Spring Boot四层架构深度解析
本文详解Spring Boot四层架构(Controller-Service-DAO-Database)的核心思想与实战应用,涵盖职责划分、代码结构、依赖注入、事务管理及常见问题解决方案,助力构建高内聚、低耦合的企业级应用。
789 1
|
2月前
|
JSON 供应链 监控
1688商品详情API技术深度解析:从接口架构到数据融合实战
1688商品详情API(item_get接口)可通过商品ID获取标题、价格、库存、SKU等核心数据,适用于价格监控、供应链管理等场景。支持JSON格式返回,需企业认证。Python示例展示如何调用接口获取商品信息。
|
3月前
|
数据采集 监控 数据可视化
数据量暴涨时,抓取架构该如何应对?——豆瓣电影案例调研
本案例讲述了在豆瓣电影数据采集过程中,面对数据量激增和限制机制带来的挑战,如何通过引入爬虫代理、分布式架构与异步IO等技术手段,实现采集系统的优化与扩展,最终支撑起百万级请求的稳定抓取。
144 0
数据量暴涨时,抓取架构该如何应对?——豆瓣电影案例调研
|
2月前
|
Kubernetes Java 微服务
Spring Cloud 微服务架构技术解析与实践指南
本文档全面介绍 Spring Cloud 微服务架构的核心组件、设计理念和实现方案。作为构建分布式系统的综合工具箱,Spring Cloud 为微服务架构提供了服务发现、配置管理、负载均衡、熔断器等关键功能的标准化实现。本文将深入探讨其核心组件的工作原理、集成方式以及在实际项目中的最佳实践,帮助开发者构建高可用、可扩展的分布式系统。
418 0
|
3月前
|
缓存 前端开发 BI
如何开发门店业绩上报管理系统中的门店数据板块?(附架构图+流程图+代码参考)
门店业绩上报管理是将门店营业、动销、人效等数据按标准化流程上报至企业中台或BI系统,用于考核、分析和决策。其核心在于构建“数据底座”,涵盖门店信息管理、数据采集、校验、汇总与对接。实现时需解决数据脏、上报慢、分析无据等问题。本文详解了实现路径,包括系统架构、数据模型、业务流程、开发要点、三大代码块(数据库、后端、前端)及FAQ,助你构建高效门店数据管理体系。
|
3月前
|
人工智能 自然语言处理 JavaScript
Github又一AI黑科技项目,打造全栈架构,只需一个统一框架?
Motia 是一款现代化后端框架,融合 API 接口、后台任务、事件系统与 AI Agent,支持 JavaScript、TypeScript、Python 多语言协同开发。它提供可视化 Workbench、自动观测追踪、零配置部署等功能,帮助开发者高效构建事件驱动的工作流,显著降低部署与运维成本,提升 AI 项目落地效率。
346 0
|
1月前
|
算法 Java Go
【GoGin】(1)上手Go Gin 基于Go语言开发的Web框架,本文介绍了各种路由的配置信息;包含各场景下请求参数的基本传入接收
gin 框架中采用的路优酷是基于httprouter做的是一个高性能的 HTTP 请求路由器,适用于 Go 语言。它的设计目标是提供高效的路由匹配和低内存占用,特别适合需要高性能和简单路由的应用场景。
215 4
|
5月前
|
缓存 JavaScript 前端开发
鸿蒙5开发宝藏案例分享---Web开发优化案例分享
本文深入解读鸿蒙官方文档中的 `ArkWeb` 性能优化技巧,从预启动进程到预渲染,涵盖预下载、预连接、预取POST等八大优化策略。通过代码示例详解如何提升Web页面加载速度,助你打造流畅的HarmonyOS应用体验。内容实用,按需选用,让H5页面快到飞起!
下一篇
oss云网关配置