Spring——第一个Spring-Web项目(三层架构实现前后端数据交互)
Posted 宋子浩
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring——第一个Spring-Web项目(三层架构实现前后端数据交互)相关的知识,希望对你有一定的参考价值。
文章目录:
2.9.1 AddStudentServlet——对应添加学生操作
2.9.2 QueryStudentServlet——对应查询学生操作
2.10.2 显示请求处理结果——对应AddStudentServlet
2.10.3 显示请求处理结果——对应QueryStudentServlet
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实体类
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&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这些知识综合在了一起学习,感觉还是很不错的!!!😄😄😄
以上是关于Spring——第一个Spring-Web项目(三层架构实现前后端数据交互)的主要内容,如果未能解决你的问题,请参考以下文章
myeclipse2015不支持spring-web-3.2.3.RELEASE.jar吗
myeclipse2015不支持spring-web-4.1.3.RELEASE.jar怎么回事,tomcat部署项目启动报错
如何防止spring-web的spring-boot自动配置?
pom文件报错Failed to read artifact descriptor for org.springframework;spring-web:jar:5.1.8RELEASE