Spring框架从入门到入土(七):Spring和Web

Spring框架从入门到入土(七):Spring和Web

在web项目中使用spring框架,首先要解决在web层(这里指的是servlet)中获取spring容器的问题,只要在web层获取到了spring容器,便可以获取到service对象。

搭建Web项目环境

在web项目中使用spring,完成学生注册

实现步骤:
1. 创建maven项目,web项目
2. 加入依赖 jsp依赖和servlet依赖
3. 编写代码和配置文件
4. 创建jsp发起请求,有参数id,name,email,age
5. 创建Servlet,接收请求,调用Service和Dao完成注册
6. 创建一个jsp作为显示页面

部分代码如下:

  • 创建maven项目

image-20220408191308107

  • index页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>注册学生页面</title>
</head>
<body>
<h1 align="center">注册学生页面</h1>
<hr/>
<form action="register" method="post">
    <table align="center">
        <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>邮件:</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>

  • servlet类
package com.liar.controller;

import com.liar.entity.Student;
import com.liar.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;

/**
 * @author liar
 * @date 编写时间: 2022/4/8 19:42
 */
public class RegisterServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        req.setCharacterEncoding("UTF-8");
        String id = req.getParameter("id");
        String name = req.getParameter("name");
        String email = req.getParameter("email");
        String age = req.getParameter("age");
        System.out.println(name);

        //创建spring容器对象
        String config = "applicationContext.xml";
        ApplicationContext context = new ClassPathXmlApplicationContext(config);
        System.out.println("容器的对象信息"+context);

        //获取service
        StudentService studentService = (StudentService) context.getBean("studentService");
        Student student = new Student();
        student.setId(Integer.parseInt(id));
        student.setName(name);
        student.setAge(Integer.parseInt(age));
        student.setEmail(email);
        studentService.addStudent(student);

        //给一个页面
        req.getRequestDispatcher("/result.jsp").forward(req,resp);
    }
}

用监听器改进

需求:web对象只需要创建一次,把容器对象放入到全局作用域servletContext中

实现:使用监听器,当全局作用域被创建的时,创建容器,存入servletContext

监听器作用:可以使用框架中提供的ContextLoaderListener

  • 创建容器对象
  • 把容器对象存入到servletContext

实现步骤:

  1. 加入依赖
    <!--使用监听器-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>5.2.5.RELEASE</version>
    </dependency>
  1. web.xml注册监听器
   <!--注册监听器ContextLoaderListener
      修改默认的applicationContext的位置
      使用
    -->
    <context-param>
        <!--contextConfigLocation表示配置文件路径-->
        <param-name>contextConfigLocation</param-name>
        <!--自定义配置文件路径-->
        <param-value>classpath:springContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
  1. 修改servlet
package com.liar.controller;

import com.liar.entity.Student;
import com.liar.service.StudentService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.web.context.WebApplicationContext;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author liar
 * @date 编写时间: 2022/4/8 19:42
 */
public class RegisterServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        req.setCharacterEncoding("UTF-8");
        String id = req.getParameter("id");
        String name = req.getParameter("name");
        String email = req.getParameter("email");
        String age = req.getParameter("age");

        WebApplicationContext context = null;
        //获取ServletContext对象中的方法,创建好的容器对象,拿来就用
        String key = WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE;
        Object attr = getServletContext().getAttribute(key);
        if(attr != null){
            context = (WebApplicationContext)attr;
        }
        System.out.println("容器的对象信息"+context);

        //获取service
        StudentService studentService = (StudentService) context.getBean("studentService");
        Student student = new Student();
        student.setId(Integer.parseInt(id));
        student.setName(name);
        student.setAge(Integer.parseInt(age));
        student.setEmail(email);
        studentService.addStudent(student);

        //给一个页面
        req.getRequestDispatcher("/result.jsp").forward(req,resp);
    }
}

工具类使用

package com.liar.controller;

import com.liar.entity.Student;
import com.liar.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;

/**
 * @author liar
 * @date 编写时间: 2022/4/8 19:42
 */
public class RegisterServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        req.setCharacterEncoding("UTF-8");
        String id = req.getParameter("id");
        String name = req.getParameter("name");
        String email = req.getParameter("email");
        String age = req.getParameter("age");

        WebApplicationContext context = null;
        ServletContext sc = getServletContext();
        context = WebApplicationContextUtils.getRequiredWebApplicationContext(sc);
        System.out.println("容器的对象信息"+context);

        //获取service
        StudentService studentService = (StudentService) context.getBean("studentService");
        Student student = new Student();
        student.setId(Integer.parseInt(id));
        student.setName(name);
        student.setAge(Integer.parseInt(age));
        student.setEmail(email);
        studentService.addStudent(student);

        //给一个页面
        req.getRequestDispatcher("/result.jsp").forward(req,resp);
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值