Spring整合Web开发

时间:2017-2-2 02:17

——导入jar包

1、导入Spring开发基本jar包
    spring-beans-3.2.0.RELEASE.jar

    spring-context-3.2.0.RELEASE.jar
    spring-core-3.2.0.RELEASE.jar
    spring-expression-3.2.0.RELEASE.jar
 

2、导入commons-logging.jar

3、导入Spring Web开发jar包
    spring-web-3.2.0.RELEASE.jar


——简单测试

1、编写一个Service

2、编写一个Servlet

3、编写配置文件

4、编写log4j.properties

5、访问Servlet调用Service方法

但是在测试的过程中发现:
    每次执行Servlet的时候都会加载Spring环境,如何解决?
        *   将加载的信息内容保存到ServletContext中,ServletContext对象是全局对象,服务器启动时就会创建,在创建ServletContext时就会加载Spring环境。
        *   可以创建一个监听器:ServletContextListener,用于监听ServletContext对象的创建和销毁。

这件事情spring-web-3.2.0.RELEASE.jar帮助我们完成了。

——配置监听器

将Spring容器的初始化操作,交由Web容器负责。

1、配置核心监听器:ContextLoaderListener
    Spring提供的ContextLoaderListener实现了ServletContextListener接口。

2、配置全局参数:contextConfigLocation
    用于指定Spring框架的配置文件的位置。
    默认在XmlWebApplicationContext类中指定为WEB-INF目录下:
        public static final String DEFAULT_CONFIG_LOCATION = "/WEB-INF/applicationContext.xml";
    如果需要修改默认目录,可以通过初始化参数进行修改:
        <param-name>contextConfigLocation</param-name>

        <param-value>classpath:applicationContext.xml</param-value>

——获得WebApplicationContext对象

因为Spring容器已经交由Web容器初始化和管理,所以获得WebApplicationContext对象需要依赖ServletContext对象:

通常直接在Servlet中获取:
    WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
    底层也是通过:getServletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);来获得。

另一种获取方式:
    WebApplicationContext context = (WebApplicationContext) getServletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);


通常使用第一种方式来获得ApplicationContext对象。
 
 
----log4j配置在src目录下
log4j.properties

### \u8BBE\u7F6E###
log4j.rootLogger = debug,stdout,D,E

### \u8F93\u51FA\u4FE1\u606F\u5230\u63A7\u5236\u62AC ###
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target = System.out
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern = [%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n

### \u8F93\u51FADEBUG \u7EA7\u522B\u4EE5\u4E0A\u7684\u65E5\u5FD7\u5230=E://logs/error.log ###
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File = E://study_fold/logs/log.log
log4j.appender.D.Append = true
log4j.appender.D.Threshold = DEBUG
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n

### \u8F93\u51FAERROR \u7EA7\u522B\u4EE5\u4E0A\u7684\u65E5\u5FD7\u5230=E://logs/error.log ###
log4j.appender.E = org.apache.log4j.DailyRollingFileAppender
log4j.appender.E.File =E://study_fold/logs/error.log
log4j.appender.E.Append = true
log4j.appender.E.Threshold = ERROR
log4j.appender.E.layout = org.apache.log4j.PatternLayout
log4j.appender.E.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n

——示例代码

Servlet:

public class UserServlet extends HttpServlet
{
private static final long serialVersionUID = 1L;

Logger log = Logger.getLogger(UserServlet.class);

/**
* Default constructor.
*/
public UserServlet() {
// TODO Auto-generated constructor stub
}

/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
WebApplicationContext con = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
UserService us = (UserService) con.getBean("userService");
response.getWriter().println(us.getName());
us.sayHello();
for(int i=0; i<10; i++)
{
log.debug("debug message..."+i);
log.error("debug message..."+i);
}
}

/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}

}

----------------------------------------------------------------------------------------------------------------------------

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>UserServlet</servlet-name>
<servlet-class>com.donghua.UserServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UserServlet</servlet-name>
<url-pattern>/UserServlet</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
</web-app>

----------------------------------------------------------------------------------------------------------------------------

spring配置文件:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

<bean id="userService" class="com.donghua.UserService">
<property name="name" value="Test Name"/>
</bean>

</beans>

----------------------------------------------------------------------------------------------------------------------------

UserService:

public class UserService
{
private String name;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public void sayHello()
{
System.out.println("Hello Spring Web STE");
}

}

浏览器输入:http://localhost:8083/spring-hibernate/UserServlet

Test Name

web整合Spring的更多相关文章

  1. web整合Spring和Hibernate

    上一篇是简单整合web和Spring, 这一篇是整合hibernate: 连接池c3p0: spring5.0, hibernate5.0 jars: ------------------------ ...

  2. 《SSM框架搭建》三.整合spring web

    感谢学习http://blog.csdn.net/zhshulin/article/details/37956105#,还是修改了spring到最新的版本和接口开发示例 根据前一篇日志,已经有了myb ...

  3. 【Java EE 学习 81】【CXF框架】【CXF整合Spring】

    一.CXF简介 CXF是Apache公司下的项目,CXF=Celtix+Xfire:它支持soap1.1.soap1.2,而且能够和spring进行快速无缝整合. 另外jax-ws是Sun公司发布的一 ...

  4. Maven 整合 spring profile实现多环境自动切换

    Maven 整合 spring profile实现多环境自动切换 时间:2014-03-19 15:32来源:Internet 作者:Internet 点击:525次 profile主要用在项目多环境 ...

  5. TinyFrame续篇:整合Spring IOC实现依赖注入

    上一篇主要讲解了如何搭建基于CodeFirst的ORM,并且在章节末我们获取了上下文对象的实例:BookContext.这节主要承接上一篇,来讲解如何整合Spring IOC容器实现控制反转,依赖注入 ...

  6. Ehcache 整合Spring 使用页面、对象缓存

    Ehcache 整合Spring 使用页面.对象缓存 Ehcache在很多项目中都出现过,用法也比较简单.一 般的加些配置就可以了,而且Ehcache可以对页面.对象.数据进行缓存,同时支持集群/分布 ...

  7. webservice 服务端例子+客户端例子+CXF整合spring服务端测试+生成wsdl文件 +cxf客户端代码自动生成

    首先到CXF官网及spring官网下载相关jar架包,这个不多说.webservice是干嘛用的也不多说. 入门例子 模拟新增一个用户,并返回新增结果,成功还是失败. 大概的目录如上,很简单. Res ...

  8. (转)Ehcache 整合Spring 使用页面、对象缓存

    Ehcache在很多项目中都出现过,用法也比较简单.一般的加些配置就可以了,而且Ehcache可以对页面.对象.数据进行缓存,同时支持集群/分布式缓存.如果整合Spring.Hibernate也非常的 ...

  9. 整合spring,springmvc和mybatis

    我创建的是maven项目,使用到的依赖架包有下面这些: <dependencies> <dependency> <groupId>org.springframewo ...

随机推荐

  1. MySQL全面瓦解26:代码评审中的MySQL(团队使用)

    数据库对象命名规范 数据库对象 数据库对象是数据库的组成部分,常见的有以下几种: 表(Table ).索引(Index).视图(View).图表(Diagram).缺省值(Default).规则(Ru ...

  2. ES6 数值类型常用方法

    ES6 数值类型常用方法 <script type="text/javascript"> // Number常用方法 /* Number.isFinite() 用来检查 ...

  3. Python + unittest知识点回顾

    postman 安装Newman 先安装node.js,把npm添加到环境变量中. npm install newman --registry=https://registry.npm.taobao. ...

  4. 第十三篇 -- QMainWindow与QAction(新建-打开-保存)

    效果图: 添加了三个Action,分别是新建,打开,和保存,没有具体写相应的功能,只是提供了一个接口,可以自己写相应的功能.这次不仅将这些Action放在了工具栏,还将其添加到了菜单栏.方法同样是直接 ...

  5. SpringBoot添加Cors跨域配置,解决No 'Access-Control-Allow-Origin' header is present on the requested resource

    目录 什么是CORS SpringBoot 全局配置CORS 拦截器处理预检请求 什么是CORS 跨域(CORS)请求:同源策略/SOP(Same origin policy)是一种约定,由Netsc ...

  6. DC-9靶机

    仅供个人娱乐 靶机信息 下载地址:http://www.five86.com/downloads/DC-9.zip 一.主机扫描 二.信息收集 三.漏洞查找和利用 发现search的地方可能有sql注 ...

  7. Android技术分享| 实现视频连麦直播

    视频连麦产品端核心步骤分析 游客申请连麦/取消申请 主播同意/拒绝申请 音视频发布取消 支持很多观众观看 支持多人连麦 低延时 IM 弹幕 视频连麦技术端调研 emmm,大致可以分为视频采集.编码,传 ...

  8. Python - 解包的各种骚操作

    为什么要讲解包 因为我觉得解包是 Python 的一大特性,大大提升了编程的效率,而且适用性很广 啥是解包 个人通俗理解:解开包袱,拿出东西 正确理解:将元素从可迭代对象中一个个取出来 python ...

  9. 蓝桥杯练习-各大OJ平台介绍

    校赛准备的不够充分,简单题失分太遗憾, 有幸参加到省赛,这次先码一下练习平台,等学期结束忙完之后好好练习! 1.题库与网站资源题库-在线提交系统(Online Judge)简介   下面是几个比较大的 ...

  10. S3C2440—2.裸机开发步骤及工具使用

    文章目录 一.裸机开发步骤简介 1.在X86架构的Windows系统中 2.在X86架构的Ubuntu系统中 3.ARM裸机开发 二.soucre insight使用 1.sourec insight ...