spring-搭建web项目
- 1.之前做的是javase项目有main方法的,执行代码是执行main方法的,在main里面创建的容器对象。
ApplicationContext ctx = new ClassPathXmlApplicationContext("application.xml"); - 2.web项目是在tomcat服务器上运行的。tomcat一启动,项目是一致运行的。
- 3.需求:web项目中容器对象只需要创建一次,把容器对象放入到全局作用域servletContext中。
怎么实现:使用监听器,当全局作用域对象被创建时,创建容器,存入ServletContext.
监听器作用:
1)创建容器对象,执行
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
2)把容器对象放入到ServletContext,ServletContext.setAttribute(key,ctx)
监听器可以自己创建,也可以 使用框架中提供好的ContextLoaderListener.
在web项目中使用spring,完成学生注册功能
1.创建maven,web项目



2.加入依赖
拷贝ch07-spring-mybatis中依赖,并加入 jsp,servlet依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.putao</groupId>
<artifactId>ch11-spring-web</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<!-- 单元测试-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!-- spring核心IOC-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<!-- 做spring事物用到的-->
<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>
<!-- mybatis依赖-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.1</version>
</dependency>
<!-- mybatis和spring集成的依赖-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
<!-- mysql驱动-->
<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>
<!-- servlet依赖-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!-- jsp依赖-->
<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-web</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
</dependencies>
<build>
<!-- 目的是把src/main/java目录中的xml文件包含到输出结果中。输出到classes目录中-->
<resources>
<resource>
<directory>src/main/java</directory><!--所在的目录-->
<includes><!--包括目录下的.properties,.xml文件都会扫描到-->
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
<!-- 指定jdk的版本-->
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
3.拷贝ch07-spring-mybatis中的代码和配置文件
- 1)实体类
package com.putao.domain;
public class Student {
//属性名和列名一样
private Integer id;
private String name;
private String email;
private Integer age;
public Student() {
}
public Student(Integer id, String name, String email, Integer age) {
this.id = id;
this.name = name;
this.email = email;
this.age = 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 String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", email='" + email + '\'' +
", age=" + age +
'}';
}
}
- 2)dao类,dao.xml类
package com.putao.dao;
import com.putao.domain.Student;
import java.util.List;
public interface StudentDao {
int insertStudent(Student student);
List<Student> selectStudents();
}
<?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.putao.dao.StudentDao">
<insert id="insertStudent" >
insert into student values(#{id},#{name},#{email},#{age})
</insert>
<select id="selectStudents" resultType="com.putao.domain.Student" >
select id,name,email,age from student order by id desc
</select>
</mapper>
- 3)service类,service实现类
package com.putao.service;
import com.putao.domain.Student;
import java.util.List;
public interface StudentService {
int addStudent(Student student);
List<Student> queryStudents();
}
package com.putao.service.impl;
import com.putao.dao.StudentDao;
import com.putao.domain.Student;
import com.putao.service.StudentService;
import java.util.List;
public class StudentServiceImpl implements StudentService {
//引用类型
private StudentDao studentDao;
//使用set注入,赋值
public void setStudentDao(StudentDao studentDao) {
this.studentDao = studentDao;
}
@Override
public int addStudent(Student student) {
int nums = studentDao.insertStudent(student);
return nums;
}
@Override
public List<Student> queryStudents() {
List<Student> students = studentDao.selectStudents();
return students;
}
}
- 4)配置文件
spring.xml
<?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">
<!-- 把数据库的配置信息,写在一个独立的文件,便于修改数据库的配置内容
spring知道jdbc.properties文件的位置
-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!-- 声明数据源DayaSource,作用是连接数据库的-->
<bean id="myDataSource" class="com.alibaba.druid.pool.DruidDataSource"
init-method="init" destroy-method="close" >
<!-- set注入给DruidDataSource提供连接数据库信息-->
<!-- 使用属性配置文件中的数据,语法${key}-->
<property name="url" value="${jdbc.url}"/> <!--setUrl()-->
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.passwd}" />
<property name="maxActive" value="${jdbc.max}" />
</bean>
<!-- 声明的是mybatis中所提供的SqlSessionFactoryBean类,这个类内部创建SqlSessionFactory的-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- set注入,把数据库连接池付给了dataSource属性-->
<property name="dataSource" ref="myDataSource" />
<!-- mybatis主配置文件的位置
configLocation属性是Resource类型,读取配置文件
它的赋值,使用value,指定文件的路径,使用classpath:表示文件的位置
-->
<property name="configLocation" value="classpath:mybatis.xml" />
</bean>
<!--創建dao對象,使用SqlSession的getMapper(StudentDao.class)
MapperScannerConfigurer:在内部调用getMapper()生成每个到接口的代理对象
-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 指定SqlSessionFactory对象的id-->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
<!--指定包名,包名是dao接口所在的包名
MapperScannerConfigurer会扫描这个包中的所有接口,把每个接口都执行
一次getMapper()方法,得到每个接口的dao对象。
创建好的dao对象放入到spring的容器中的。dao对象的默认名称是 接口名首字母小写
-->
<property name="basePackage" value="com.putao.dao" />
</bean>
<bean id="studentService" class="com.putao.service.impl.StudentServiceImpl">
<property name="studentDao" ref="studentDao" />
</bean>
</beans>
jdbc.properties
jdbc.url=jdbc:mysql://localhost:3306/springdb?characterEncoding=utf-8
jdbc.username=root
jdbc.passwd=root
jdbc.max=30
mybatis.xml
<?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>
<!-- 设置别名-->
<typeAliases>
<!-- name:实体类所在的包名-->
<package name="com.putao.domain"/>
</typeAliases>
<!-- sql mapper(sql映射文件的位置)-->
<mappers>
<!--
name:是包名,这个包中的所有mapper.xml一次都能加载
-->
<package name="com.putao.dao"/>
</mappers>
</configuration>
4.创建一个jsp发起请求,有参数id,name,email,age。
index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<p>注册学生</p>
<form action="reg" method="post">
<table>
<tr>
<td>id</td>
<td><input type="text" name="id"></td>
</tr>
<tr>
<td>姓名:</td>
<td><input type="text" name="name"></td>
</tr>
<tr>
<td>email:</td>
<td><input type="text" name="email"></td>
</tr>
<tr>
<td>年龄:</td>
<td><input type="text" name="age"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="注册学生"></td>
</tr>
</table>
</form>
</body>
</html>
5.创建Servlet,接收请求参数,调用Service,调用dao完成注册
package com.putao.controller;
import com.putao.domain.Student;
import com.putao.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 RegisterServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String strId = request.getParameter("id");
String strName = request.getParameter("name");
String strEmail = request.getParameter("email");
String strAge = request.getParameter("age");
//创建spring的容器对象
// String config= "spring.xml";
// ApplicationContext ctx = new ClassPathXmlApplicationContext(config);
//org.springframework.context.support.ClassPathXmlApplicationContext@e685c79, started on Tue Sep 28 17:34:38 GMT+08:00 2021
//org.springframework.context.support.ClassPathXmlApplicationContext@56f7297a, started on Tue Sep 28 17:36:15 GMT+08:00 2021
// System.out.println("容器对象的信息===="+ctx);
WebApplicationContext ctx = null;
//获取ServletContext中的容器对象,创建好的容器对象,拿来就用
// String key = WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE;
// Object attr = getServletContext().getAttribute(key);
// if (attr != null){
// ctx = (WebApplicationContext) attr;
// }
//使用框架中的方法,获取容器对象
ServletContext sc = getServletContext();
ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(sc);
//容器对象的信息====Root WebApplicationContext, started on Wed Sep 29 09:43:09 GMT+08:00 2021
//容器对象的信息====Root WebApplicationContext, started on Wed Sep 29 09:43:09 GMT+08:00 2021
System.out.println("容器对象的信息===="+ctx);
//获取service
StudentService service = (StudentService) ctx.getBean("studentService");
Student student = new Student();
student.setId(Integer.parseInt(strId));
student.setName(strName);
student.setEmail(strEmail);
student.setAge(Integer.valueOf(strAge));
service.addStudent(student);
//给一个页面
request.getRequestDispatcher("/result.jsp").forward(request,response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
6.创建一个jsp作为显示结果的页面
result.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
result.jsp注册成功
</body>
</html>
本文档详细介绍了如何使用Spring搭建Web项目,从创建Maven Web项目,加入必要的依赖,复制代码和配置文件,到创建JSP发起请求,编写Servlet处理请求,调用Service和DAO完成用户注册功能,最后展示结果页面。整个过程利用了监听器将Spring容器放入ServletContext,确保容器对象全局唯一。
19万+

被折叠的 条评论
为什么被折叠?



