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

简介: 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;
相关文章
|
人工智能 运维 Java
Spring AI Alibaba Admin 开源!以数据为中心的 Agent 开发平台
Spring AI Alibaba Admin 正式发布!一站式实现 Prompt 管理、动态热更新、评测集构建、自动化评估与全链路可观测,助力企业高效构建可信赖的 AI Agent 应用。开源共建,现已上线!
9299 129
|
监控 Java API
Spring Boot 3.2 结合 Spring Cloud 微服务架构实操指南 现代分布式应用系统构建实战教程
Spring Boot 3.2 + Spring Cloud 2023.0 微服务架构实践摘要 本文基于Spring Boot 3.2.5和Spring Cloud 2023.0.1最新稳定版本,演示现代微服务架构的构建过程。主要内容包括: 技术栈选择:采用Spring Cloud Netflix Eureka 4.1.0作为服务注册中心,Resilience4j 2.1.0替代Hystrix实现熔断机制,配合OpenFeign和Gateway等组件。 核心实操步骤: 搭建Eureka注册中心服务 构建商品
1809 3
|
监控 Cloud Native Java
Spring Boot 3.x 微服务架构实战指南
🌟蒋星熠Jaxonic,技术宇宙中的星际旅人。深耕Spring Boot 3.x与微服务架构,探索云原生、性能优化与高可用系统设计。以代码为笔,在二进制星河中谱写极客诗篇。关注我,共赴技术星辰大海!(238字)
1748 2
Spring Boot 3.x 微服务架构实战指南
|
NoSQL Java 数据库连接
《深入理解Spring》Spring Data——数据访问的统一抽象与极致简化
Spring Data通过Repository抽象和方法名派生查询,简化数据访问层开发,告别冗余CRUD代码。支持JPA、MongoDB、Redis等多种存储,统一编程模型,提升开发效率与架构灵活性,是Java开发者必备利器。(238字)
|
Java 数据库 数据安全/隐私保护
Spring Boot四层架构深度解析
本文详解Spring Boot四层架构(Controller-Service-DAO-Database)的核心思想与实战应用,涵盖职责划分、代码结构、依赖注入、事务管理及常见问题解决方案,助力构建高内聚、低耦合的企业级应用。
2240 1
|
Kubernetes Java 微服务
Spring Cloud 微服务架构技术解析与实践指南
本文档全面介绍 Spring Cloud 微服务架构的核心组件、设计理念和实现方案。作为构建分布式系统的综合工具箱,Spring Cloud 为微服务架构提供了服务发现、配置管理、负载均衡、熔断器等关键功能的标准化实现。本文将深入探讨其核心组件的工作原理、集成方式以及在实际项目中的最佳实践,帮助开发者构建高可用、可扩展的分布式系统。
1112 0
|
人工智能 自然语言处理 JavaScript
Github又一AI黑科技项目,打造全栈架构,只需一个统一框架?
Motia 是一款现代化后端框架,融合 API 接口、后台任务、事件系统与 AI Agent,支持 JavaScript、TypeScript、Python 多语言协同开发。它提供可视化 Workbench、自动观测追踪、零配置部署等功能,帮助开发者高效构建事件驱动的工作流,显著降低部署与运维成本,提升 AI 项目落地效率。
1087 0
|
存储 Java 数据库连接
简单学Spring Boot | 博客项目的三层架构重构
本案例通过采用三层架构(数据访问层、业务逻辑层、表现层)重构项目,解决了集中式开发导致的代码臃肿问题。各层职责清晰,结合依赖注入实现解耦,提升了系统的可维护性、可测试性和可扩展性,为后续接入真实数据库奠定基础。
1051 0
|
算法 Java Go
【GoGin】(1)上手Go Gin 基于Go语言开发的Web框架,本文介绍了各种路由的配置信息;包含各场景下请求参数的基本传入接收
gin 框架中采用的路优酷是基于httprouter做的是一个高性能的 HTTP 请求路由器,适用于 Go 语言。它的设计目标是提供高效的路由匹配和低内存占用,特别适合需要高性能和简单路由的应用场景。
982 4