普通java工程 spring_在普通WEB项目中使用Spring

Spring是一个对象容器,帮助我们管理项目中的对象,那么在web项目中哪些对象应该交给Spring管理呢?

项目中涉及的对象

​我们回顾一下WEB项目中涉及的对象

Servlet

Request

Response

Session

Service

DAO

POJO

分析

我们在学习IOC容器时知道,Spring可以帮助我们管理原来需要自己创建管理的对象,如果一个对象原来就不需要我们自行管理其的创建和声明周期的话,那么该对象也就不需要交给Spring管理

由此来看,上述对象中只有Service,DAO,POJO应该交给Spring管理,而由于POJO通常都是由持久层框架动态创建的,所以最后只有Service和DAO要交给Spring容器管理,

当然Spring中的AOP也是很常用的功能,例如事务管理,日志输出等..

最小pom依赖:

UTF-8

1.7

1.7

org.springframework

spring-context

5.2.2.RELEASE

org.springframework

spring-web

5.2.2.RELEASE

javax.servlet

jstl

1.2

javax.servlet.jsp

javax.servlet.jsp-api

2.3.3

provided

javax.servlet

javax.servlet-api

4.0.1

provided

上述依赖可以保证项目可以使用Spring容器以及JSP,EL,Servlet的正常使用,测试完成后既可以向普通Spring或web项目一样进行开发了

Spring配置文件:

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.xsd">

在容器中添加了一个整数,用于测试容器是否可用

web.xml

/p>

"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"

"http://java.sun.com/dtd/web-app_2_3.dtd" >

xmlns="http://java.sun.com/xml/ns/javaee"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

Archetype Created Web Application

index.jsp

contextConfigLocation

classpath:applicationContext.xml

org.springframework.web.context.ContextLoaderListener

测试Servlet

package com.yh.servlet;

import org.springframework.web.context.WebApplicationContext;

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 = "TestServlet",urlPatterns = "/test")

public class TestServlet extends HttpServlet {

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

}

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

//获取Spring容器

WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(getServletContext());

//获取容器中的对象测试

Object integer = context.getBean("integer");

response.getWriter().println("hello spring "+integer);

}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值