栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Spring详解(五)Spring和Web

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spring详解(五)Spring和Web

文章目录
  • 第六章 Spring和Web
      • 实例:在网页上新建和查询学生信息
    • 1.使用容器对象的问题
    • 2.需要一个什么样的容器对象
    • 3.ContextLoaderListener
    • 4.ContextLoaderListener 源代码
      • 实例:修改查询只实例化对象一次
      • 实例:使用spring提供的方法进行简化

第六章 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配置文件

添加的依赖

	
    
      javax.servlet
      javax.servlet-api
      3.1.0
      provided
    
    
    
      javax.servlet.jsp
      jsp-api
      2.2.1-b03
      provided
    

applicationContext.xml






    


    
    
        
        
        
    


    

        
        
    

    

        

        
    

    
        
    

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




    



    

    
        
    
    


        
    

jsp

index.jsp


    添加学生


    

添加学生

姓名:
年龄:


查询学生

学生id:
show.jsp <%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ page isELIgnored="false" %> Title /show.jsp 注册成功

查询结果:v ${stu}

​ 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

    
      org.springframework
      spring-web
      5.2.5.RELEASE
    a

2.web.xml 声明监听器

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



    

        contextConfigLocation

        classpath:spring-beans.xml
    
    
        org.springframework.web.context.ContextLoaderListener
    
    

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 {

    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/337965.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号