web项目中的spring容器注入servlet——使用工具

1、servlet

package com.servlets;

import com.beans.Student;
import com.service.IStudentService;
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 java.io.IOException;

/**

  • @author dc

  • @date 2020/4/3 - 14:42
    */
    public class RegisterServlet extends javax.servlet.http.HttpServlet {
    protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {

     request.setCharacterEncoding("utf-8");
     String name = request.getParameter("name");
     String ageStr = request.getParameter("age");
     Integer age = Integer.valueOf(ageStr);
     Student student = new Student();
     student.setName(name);
     student.setAge(age);
    
     // System.out.println(student);
    
     //获取spring容器
     WebApplicationContext ac = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
     System.out.println(ac);
    
     //获取service对象
     IStudentService service = (IStudentService) ac.getBean("myService");
    
     //将调用dao层方法学生对象插入到数据库
     service.addStudent(student);
    
     request.getRequestDispatcher("/welcome.jsp").forward(request, response);
    

    }

    protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
    doPost(request, response);
    }
    }

2、web.xml

<?xml version="1.0" encoding="UTF-8"?>

<!--指定spring配置文件的名称及位置-->
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
</context-param>

<!--注册listener-->
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<!--注册registerServlet-->
<servlet>
    <servlet-name>RegisterServlet</servlet-name>
    <servlet-class>com.servlets.RegisterServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>RegisterServlet</servlet-name>
    <url-pattern>/registerServlet</url-pattern>
</servlet-mapping>
发布了46 篇原创文章 · 获赞 1 · 访问量 383

猜你喜欢

转载自blog.csdn.net/weixin_43925059/article/details/105300310