web项目中怎么使用容器对象?
1.之前做的是javase项目,有main方法,执行代码是执行main方法的,在main里面创建容器对象。
2.web项目是在tomcat服务器上运行的。tomcat一启动,项目一直运行。
1.创建maven,web项目
1.选择maven模板 2.手工创建java和resource目录 3.设置Java目录为SourcesRoot2.添加依赖
<!--复制ch07项目中的依赖-->
<!--jdk属性信息-->
<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>8.0.23</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>
</dependencies>
<build>
<!--加入maven插件,编译时扫描src/main/java目录中的xml文件-->
<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.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
3.拷贝ch7-spring-mybatis的代码和配置文件
package com.bjpowernode.dao;
import com.bjpowernode.domain.Student;
import java.util.List;
public interface StudentDao {
int insertStudent(Student student);
List<Student>selectStudents();
}
<!--
package:src\main\java\com\bjpowernode\dao\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">
<!--唯一值的,可以自定义,但要求:使用dao接口的全限定名称。(包括包名、类名)-->
<mapper namespace="com.bjpowernode.dao.StudentDao">
<insert id="insertStudent">
insert into student values (#{id},#{name},#{email},#{age})
</insert>
<!--id:接口的方法,resultType该方法的数据类型-->
<select id="selectStudents" resultType="com.bjpowernode.domain.Student">
select id,name,email,age from student order by id desc
</select>
</mapper>
package com.bjpowernode.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 +
'}';
}
}
package com.bjpowernode.service;
import com.bjpowernode.domain.Student;
import java.util.List;
public interface StudentService {
int addStudent(Student student);
List<Student> queryStudents();
}
package com.bjpowernode.service.impl;
import com.bjpowernode.dao.StudentDao;
import com.bjpowernode.domain.Student;
import com.bjpowernode.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 num=studentDao.insertStudent(student);
return num;
}
@Override
public List<Student> queryStudents() {
List<Student>students=studentDao.selectStudents();
return students;
}
}
<!--
src\main\resources\applicationContext.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:util="http://www.springframework.org/schema/util"
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/util https://www.springframework.org/schema/util/spring-util.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"/>
<!--声明数据源DataSource,作用是连接数据库的-->
<bean id="myDataSource" class="com.alibaba.druid.pool.DruidDataSource"
init-method="init" destroy-method="close">
<!--set注入给DruidDataSource体哦那个连接数据库信息-->
<!--
使用属性配置文件中的数据,语法:${key}
-->
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<property name="maxActive" value="${jdbc.maxActive}"/>
</bean>
<!--声明mybatis中所提供能SqlSessionFactoryBean类,
这个类的内部是创建SqlSessionFactory的-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--set注入,把数据库的连接池赋给dataSource属性-->
<property name="dataSource" ref="myDataSource"/>
<!--value:mybatis主配置文件的位置
configLocation是Resource类型的
-->
<property name="configLocation" value="classpath:mybatis.xml"/>
</bean>
<!--创建dao对象,使用SqlSession的getMapper(StudentDao.class)
MapperScannerConfigurer:在内部调用getMapper()生成每个dao接口的代理对象
-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--指定SqlSessionFactory对象id-->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!--指定包名,包名是dao接口所在的包名
MapperScannerConfigurer会扫描这个包中的所有接口,
把每个接口都执行一次getMapper()方法,得到每个接口的dao对象。
创建好的dao对象放入到spring的容器中。-->
<property name="basePackage" value="com.bjpowernode.dao"/>
</bean>
<!--声明service-->
<bean id="studentService" class="com.bjpowernode.service.impl.StudentServiceImpl">
<!--在上一步中创建了dao对象,且默认创建的名称是接口首字母小写(studentDao对象出处)-->
<property name="studentDao" ref="studentDao"/>
</bean>
</beans>
<!--
src\main\resources\jdbc.properties
-->
jdbc.url=jdbc:mysql://localhost:3306/ssm
jdbc.username =root
jdbc.password=abc1234.
jdbc.maxActive=20
<!--
src\main\resources\mybatis.xml
-->
<?xml version="1.0" encoding="UTF-8" ?>
<!--mybatis的主配置文件:主要定义了数据库的配置信息和sql映射文件的位置-->
<!--指定约束文件-->
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<!--根标签-->
<configuration>
<!--settings:控制mybatis全局行为的-->
<settings>
<!--设置mybatis输出日志-->
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
<!--设置别名-->
<typeAliases>
<!--name:实体类所在的包名-->
<package name="com.bjpowernode.domain"/>
</typeAliases>
<!--sql mapper(sql映射文件)的位置-->
<mappers>
<!--一个mapper标签指定一个sql映射文件的位置
从类路径开始的路径信息。 target/class(class后面开始的就是类路径)
<mapper resource=""/>-->
<!--name:包名,这个包中的所有mapper.xml一次都能加载-->
<package name="com.bjpowernode.dao"/>
</mappers>
</configuration>
4.创建一个jsp发起请求,有参数id,name,email,age
创建jsp文件<body>
<p>注册学生</p>
<form action="" 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" name="注册学生"></td>
</tr>
</table>
</form>
</body>
5.创建Servlet,接受请求参数,调用Service,调用dao完成注册
创建项目自带的webxml文件servlet版本太低添加webxml文件
修改webxml文件名
修改后
创建Servlet文件
在web.xml文件中填Servlet名
在jsp文件中填入Servlet名
/*com.bjpowernode.controller.RegisterServlet*/
package com.bjpowernode.controller;
import com.bjpowernode.domain.Student;
import com.bjpowernode.service.StudentService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
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="applicationContext.xml";
ApplicationContext ctx = new ClassPathXmlApplicationContext(config);
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作为显示页面
<!--
package:src\main\webapp\result.jsp
-->
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
result.jsp 注册成功
</body>
</html>
7.将web项目跑起来
1.配置tomcat2.配置tomcat
3.配置tomcat
4.访问页面
http://localhost:8080/ch11_spring_web/
如果报找不到数据库配置文件的,可能是没有把resources文件夹设置为Resources Root
8.改变web项目中容器的创建方式
需求:在web项目中容器对象只需要创建一次
方法:把容器对象放入到全局作用域ServletContext中
实现:使用监听器,当全局作用域对象被创建时,创建容器并存入ServletContext
监听器作用:
1)创建容器对象,执行ApplicationContext ctx = new ClassPathXmlApplicationContext(config);
2)把容器对象放入到ServletContext,ServletContext.setAttribute(key,ctx);
监听器可以自己创建,也可以使用框架提供的ContextLoaderListener
<!--为使用监听器对象,加入依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<!--
package:src\main\webapp\WEB-INF\web.xml
-->
<!--注册监听器ContextLoaderListener-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
最重要👇:配置监听器,目的是创建容器对象,能把springxml配置文件中的所有对象都创建好,用户发起请求即可直接使用对象
<!--注册监听器ContextLoaderListener
监听器被创建对象后,会读取/WEB-INF/spring.xml,
为什么要读取文件:因为在监听器中创建ApplicationContext对象需要加载配置文件
/WEB-INF/applicationContext.xml就是监听器默认读取的spring而皮质文件路径
可修改默认的文件读取位置,使用context-param重新指定读取文件的位置
-->
<context-param>
<!--contextConfigLocation表示配置文件的路径-->
<param-name>contextConfigLocation</param-name>
<!--自定义配置文件的路径-->
<param-value>classpath:spring.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
自己写方法来获取容器对象👇
<!--
package:com.bjpowernode.controller.RegisterServlet
-->
/*创建spring的容器对象*/
//String config= "spring.xml";
//ApplicationContext ctx = new ClassPathXmlApplicationContext(config);
WebApplicationContext ctx= null;
//获取ServlectContext中的容器对象,创建好的容器对象拿来就用
String key= WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE;
Object attr=getServletContext().getAttribute(key);
if(attr!=null){
ctx= (WebApplicationContext) attr;
}
System.out.println("容器对象的信息======"+ctx);
利用工具方法快捷拿到容器对象👇
<!--
package:com.bjpowernode.controller.RegisterServlet
-->
/*创建spring的容器对象*/
//String config= "spring.xml";
//ApplicationContext ctx = new ClassPathXmlApplicationContext(config);
WebApplicationContext ctx= null;
//获取ServlectContext中的容器对象,创建好的容器对象拿来就用
//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);
System.out.println("容器对象的信息======"+ctx);
网友评论