关于Servlet和整合spring的步骤

项目目录

关于Servlet和整合spring的步骤

引入spring的依赖包

关于Servlet和整合spring的步骤

相关类

Servlet

package net.zixue.web;
import net.zixue.utils.util;


import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

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

@WebServlet(name = "Servlet",urlPatterns = "/ok")
public class Servlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String name = request.getParameter("name");
        System.out.println(name);


    }

    @Override
    public void init() throws ServletException {
        super.init();
        ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
        util ok = (util)context.getBean("ok");
        ok.say();
    }
}

需要注入的类

package net.zixue.utils;

public class util {
    public void say(){
        System.out.println("OKOKOKOKOKO");
    }
}

相关配置

spring配置文件给放在WEB-INF下,配置时需要以下代码,位置不同情况不同写法,不懂得可以参考
https://blog.csdn.net/konglongaa/article/details/51707783

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
<welcome-file-list>
    <welcome-file>login.jsp</welcome-file>
</welcome-file-list>

    <!-- spring 上下文监听器 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!-- 配置spring 配置文件位置 WEB-INF下面-->
    <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>WEB-INF/applicationcontext.xml</param-value>
</context-param>

    <!-- 配置spring 配置文件位置 1:src下面-->
  <!--
   <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
    -->
</web-app>

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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd">
<bean id="ok" class="net.zixue.utils.util"/>
</beans>

tomcat测试

测试地址http://localhost:8080/ok

输出内容

OKOKOKOKOKO