Spring详解(五)Spring和Web

第六章 Spring和Web

实例:在网页上新建和查询学生信息

在这里插入图片描述

readme

ch18-spring-web:完成学生注册功能

步骤:
1.新建 maven
2.修改破灭.xml
    spring,mybatis 以外的依赖,servlet ,jsp依赖
3.创建实体类,Student,对应Student2表
4.创建dao接口 和mapper文件
5.创建mybatis主配置文件
6.创建Service和实现类
7.创建Servlet,接收请求的参数,调用service对象
8.创建jsp提交请求参数
9.创建jsp,作为视图,显示请求的处理结果
10.创建spring配置文件

添加的依赖

	<!-- 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>

在这里插入图片描述

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: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"/>


    <!--    声明数据源DataSource-->
    <bean id="myDataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>

<!--    声明SqlSessionFactoryBean,在这个类的内部,创建SqlSessionFactory-->
    <bean id="factory" 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">
<!--        指定SqlSessionFactory对象的名称-->
        <property name="sqlSessionFactoryBeanName" value="factory"/>
<!--        指定基本包,dao接口所在的包名-->
        <property name="basePackage" value="com.sunny.dao"/>
    </bean>

    <bean id="studentService" class="com.sunny.service.impl.StudentServiceImpl">
        <property name="dao" ref="studentDao"/>
    </bean>
</beans>

com.sunny.service.impl.StudentServiceImpl

public class StudentServiceImpl implements StudentService {
    private StudentDao dao;

    public void setDao(StudentDao dao) {
        this.dao = dao;
    }

    @Override
    public int addStudent(Student student) {

//        对象来自现实生活  逻辑可以写名字不能为空  如果有就不能添加
//        Student student1 = findStudentById(student.getStuid());
//        if(student ==null){
//            int rows = dao.insertStudent(student);
//
//        }
        int rows = dao.insertStudent(student);


        return rows;
    }

    @Override
    public Student findStudentById(Integer id) {
        Student student= dao.selectById(id);
        return student;
    }
}

com.sunny.controller.QueryStudentServlet

public class QueryStudentServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String stuId = request.getParameter("stuid");

        String config = "applicationContext.xml";
        ApplicationContext ctx = new ClassPathXmlApplicationContext(config);
        System.out.println("在servlet中创建的对象容器========"+ctx);
        StudentService service = (StudentService) ctx.getBean("studentService");

        Student student = service.findStudentById(Integer.valueOf(stuId));

        System.out.println("student对象====="+student);

        request.setAttribute("stu",student);
        request.getRequestDispatcher("/show.jsp").forward(request,response);
    }
}

com.sunny.dao.StudentDao

public interface StudentDao {
    int insertStudent(Student student);

    Student selectById(@Param("studentId") Integer id);
}

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>
    <!--    设置日志-->
<!--    <settings>-->
<!--        <setting name="logImpl" value="STDOUT_LOGGING"/>-->
<!--    </settings>-->
    
<!--    别名-->
    <typeAliases>
        <package name="com.sunny.domain"/>
    </typeAliases>
    <mappers>
<!--        <mapper resource="com/sunny/dao/StudentDao.xml"/>-->
<!--
            要求:
            1.mapper文件和dao接口在同一目录
            2.mapper文件和dao接口名称一致
-->
        <package name="com.sunny.dao"/>
    </mappers>
</configuration>

jsp

index.jsp
<html>
<head>
    <title>添加学生</title>
</head>
<body>
    <div align="center">
        <p>添加学生</p>
        <form action="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="queryStudent" method="get">
            学生id:<input type="text" name="stuid"><br/>
            <input type="submit" value="查询学生">
        </form>
    </div>
</body>
</html>
show.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page isELIgnored="false" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    /show.jsp 注册成功
    <br/>
    <p>查询结果:v ${stu} </p>
</body>
</html>

​ PS: 在这种情况下每一插入或者查询操作都将 spring配置的对象实例化一次,浪费资源,执行时间延长。

1.使用容器对象的问题

1.创建容器对象多次

2.在多个servlet中,分别创建容器对象。

2.需要一个什么样的容器对象

1.容器对象只有一个,创建一次就可以了

2.容器对象应该在整个项目中共享使用。多个servlet都能使用同一个容器对象

解决问题使用监听器 ServletContextListener(两个方法初始化时执行的,销毁时执行的)

在监听器中,创建好的容器对象,应该放在web应用中的ServletContext作用域中。

3.ContextLoaderListener

​ ContextLoaderListener 是一个监听器对象,是spring框架提供的,使用这个监听器的作用:

1.创建容器对象,只创建一次

2.把容器对象放入到ServletContext作用域。

使用步骤:

1.pom.xml加入依赖spring-web

<!--    监听器依赖-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>5.2.5.RELEASE</version>
    </dependency>a

2.web.xml 声明监听器

这样可以避免重复实例化对象。


<!--    声明监听器
        默认监听器:创建容器对象时,读取配置文件:/WEB-INF/spring-beans.xml
-->
<!--    自定义容器使用的配置文件路径
        context-param:叫做上下文参数,给监听器,提供参数的

-->
    <context-param>
<!--
        contextConfigLocation:名称是固定的,表示自定义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>

4.ContextLoaderListener 源代码

public class ContextLoaderListener extends ContextLoader implements ServletContextListener {
	//监听器的初始化方法
    public void contextInitialized(ServletContextEvent event) {
        this.initWebApplicationContext(event.getServletContext());
    }
}


public WebApplicationContext initWebApplicationContext(ServletContext servletContext) {
    

            try {
                if (this.context == null) {
                    //创建容器对象
                    this.context = this.createWebApplicationContext(servletContext);
                }

               
				//把容器对象放入到ServletContext作用域
                //key = WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE
                servletContext.setAttribute(WebApplicationContext
                                            .ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE,this.context);
                
            } catch (Error | RuntimeException var8) {
                
             
            }
        }
    }
WebApplicationContext 是web项目中使用的对象;
public interface WebApplicationContext extends ApplicationContext ;

实例:修改查询只实例化对象一次

public class QueryStudentServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String stuId = request.getParameter("stuid");

//        使用了监听器创建好了容器对象,从ServletContext作用域中获取容器
        WebApplicationContext ctx =null;
        String key = WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE;
        ServletContext sc = getServletContext();//ServletContext,servlet中的方法

//        ServletContext sc = request.getServletContext(); //HttpServletRequest对象的方法
        Object attr =sc.getAttribute(key);
        if(attr != null){
            ctx = (WebApplicationContext) attr;
        }
        System.out.println("在servlet中创建的对象容器========"+ctx);
        StudentService service = (StudentService) ctx.getBean("studentService");

        Student student = service.findStudentById(Integer.valueOf(stuId));

        System.out.println("student对象====="+student);

        request.setAttribute("stu",student);
        request.getRequestDispatcher("/show.jsp").forward(request,response);
    }
}

实例:使用spring提供的方法进行简化

public class AddStudentServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String strName = request.getParameter("name");
        String strAge = request.getParameter("age");

//        调用service
//        使用spring提供的工具方法,获取容器对象
        ServletContext sc=getServletContext();
        WebApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(sc);



        StudentService service = (StudentService) ctx.getBean("studentService");

        Student student =new Student();
        student.setStuname(strName);
        student.setStuage(Integer.valueOf(strAge));
        service.addStudent(student);

//        给用户显示请求的处理结果
        request.getRequestDispatcher("/show.jsp").forward(request,response);

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值