使用spring访问servlet

首先先建一个web项目,并在pom.xml中引入依赖包:spring-context和jsp servlet相关包,以及tomcat插件

其次建一个spring的配置文件applicationContext.xml,并在配置中开启注解扫描:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
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
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
">
<!--开启扫描-->
<context:component-scan base-package="com.zy"></context:component-scan>
</beans>

注意我们先演示一个有问题的方式:

我们模拟从index.jsp 访问 LoginServlet:

UserService

public interface UserService {
public boolean login();
} @Service("userService")//使用注解
public class UserServiceImpl implements UserService {
public UserServiceImpl() {
System.out.println("userService 构造方法...");
} @Override
public boolean login() {
System.out.println("service login...");
return true;
}
}

index.jsp

<%@ page contentType="text/html; charset=utf-8" language="java" isELIgnored="false" %>
<html>
<body>
<h2>Hello World!</h2>
<a href="${pageContext.request.contextPath}/HelloServlet">helloservlet</a>
</body>
</html>

LoginServlet

public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService service = ac.getBean("userService", UserService.class);//spring容器创建service对象
boolean isOk = service.login();
response.setContentType("text/html;charset=utf-8");
if (isOk) {
response.getWriter().print("登录成功,3秒跳转index页面");
response.setHeader("refresh", "3;url=" + request.getContextPath() + "/index.jsp");
}else {
response.getWriter().print("登录失败");
}
} protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
}

运行tomcat点击了两次index页面上的超链接(访问了两次LoginServlet),后台输出为:

前台页面也显示登录成功,可以看出访问servlet是成功了,但是有一个问题:

问题是每次访问servlet都会重新创建UserService对象,现在我们只有一个对象,如果以后有很多个对象,那每次访问servlet的时候,

 ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");

这句代码都会把对象创建出来,会很浪费资源,那么怎么解决这个问题呢?

现在我们演示正确的方式:

添加监听器,用来监听程序启动,当启动的时候,把所有的对象都创建出来,以后再用的之后直接用,不再创建:

web.xml

<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" > <web-app>
<display-name>Archetype Created Web Application</display-name>
<!--告诉监听器spring配置文件是谁-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param> <!--配置监听器-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener> <servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>com.zy.web.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/HelloServlet</url-pattern>
</servlet-mapping>
</web-app>

上面配置监听器的ContextLoaderListener,需要在pom.xml中引入下面这个包:

<!--web.xml中需要配置监听器,这里就需要导入这个包-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.1.3.RELEASE</version>
</dependency>

这次我们加上dao层:

public interface UserDao {
public boolean login();
} @Repository("userDao")
public class UserDaoImpl implements UserDao {
public UserDaoImpl() {
System.out.println("userDao 构造方法...");
} @Override
public boolean login() {
System.out.println("dao login...");
return true;
}
}

service:

public interface UserService {
public boolean login();
}
@Service("userService")
public class UserServiceImpl implements UserService {
@Value("#{userDao}")//注入UserDao
private UserDao userDao; public UserServiceImpl() {
System.out.println("userService 构造方法...");
} @Override
public boolean login() {
System.out.println("service login...");
return userDao.login();
}
}

配置完成以后,LoginServlet中获取ApplicationContext的方式改变一下:

public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
//使用下面的方法 从工具类中获取ApplicationContext 需要把当前servlet的ServletContext当做参数传进去
ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
UserService service = ac.getBean("userService", UserService.class);
boolean isOk = service.login();
response.setContentType("text/html;charset=utf-8");
if (isOk) {
response.getWriter().print("登录成功,3秒跳转index页面");
response.setHeader("refresh", "3;url=" + request.getContextPath() + "/index.jsp");
} else {
response.getWriter().print("登录失败");
}
} protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
}

当程序启动的时候,两个实现类都被创建出来了:

这样,每次访问LoginServlet的时候,就不会重复创建对象了,只会调用对象的方法(访问了两次):

Spring总结五:小结 使用spring访问servlet的更多相关文章

  1. Spring(五):Spring&Struts2&Hibernate整合后,实现查询Employee信息

    背景: 基于之前两篇文章<Spring(三):Spring整合Hibernate>.<Spring(四):Spring整合Hibernate,之后整合Struts2>,了解了如 ...

  2. Spring Boot2(五):使用Spring Boot结合Thymeleaf模板引擎使用总结

    一.Thymeleaf概述 一般来说,常用的模板引擎有JSP.Velocity.Freemarker.Thymeleaf . SpringBoot推荐的 Thymeleaf – 语法更简单,功能更强大 ...

  3. 学习spring第五天 mybatis+spring的整合(maven多模块数据查询使用了分页和连接池),以及aop

    mybatis+spring的整合: 导入的依赖:1.数据库连接:mysql-connector-java 2.连接池:druid 3.servlet:javax.servlet-api 4.jstl ...

  4. Spring第五弹—–配置Spring管理的bean的作用域和生命周期

    singleton (默认方式) 在每个Spring IoC容器中一个bean定义只有一个对象实例.默认情况下会在容器启动时初始化bean,但我们可以指定bean节点的lazy-init=“true” ...

  5. Spring ( 五 )Spring之数据访问与事务管理

    个人博客网:https://wushaopei.github.io/    (你想要这里多有) 一.Spring之数据访问 1.Spring数据访问工程环境搭建 ​ jdbc.properties配置 ...

  6. spring的webutils包。适用于访问httpservletrequest和httpservletresponse

    WebUtils位 于 org.springframework.web.util 包中的 WebUtils 是一个非常好用的工具类,它对很多 Servlet API 提供了易用的代理方法,降低了访问 ...

  7. 【Java EE 学习 53】【Spring学习第五天】【Spring整合Hibernate】【Spring整合Hibernate、Struts2】【问题:整合hibernate之后事务不能回滚】

    一.Spring整合Hibernate 1.如果一个DAO 类继承了HibernateDaoSupport,只需要在spring配置文件中注入SessionFactory就可以了:如果一个DAO类没有 ...

  8. Java框架之Spring(五)

    本文主要介绍Spring中, 1 Spring JDBC 2 使用注解方式管理事务的传播行为 3 采用XML 方式配置事务 4 SH 整合 5 SSH 整合 一.Spring JDBC 1) 导包 , ...

  9. 【Spring学习笔记-MVC-14】Spring MVC对静态资源的访问

    作者:ssslinppp       参考链接: http://www.cnblogs.com/luxh/archive/2013/03/14/2959207.html  http://www.cnb ...

随机推荐

  1. iOS开发之谈谈App应用的架构搭建(推荐给大家看)

    1.iOS应用架构谈 开篇: 2.iOS应用架构谈 view层的组织和调用方案: 3.iOS应用架构谈 网络层设计方案: 4.iOS应用架构谈 本地持久化方案及动态部署: 5.iOS应用架构谈 组件化 ...

  2. requestAnimationFrame 与 cancelAnimationFrame

    API接口 Window对象定义了以下两个接口: partial interface Window { long requestAnimationFrame(FrameRequestCallback ...

  3. 使用 event.preventDefault 拦截表单的提交

    event.preventDefault() 方法 W3C 官方的定义是:取消事件的默认动作,不单单可以拦截表单的提交,<a>标签的跳转, <input>标签的输入等等默认动作 ...

  4. Java中数据库连接池原理机制的详细讲解(转)

    连接池的基本工作原理 1.基本概念及原理 由上面的分析可以看出,问题的根源就在于对数据库连接资源的低效管理.我们知道,对于共享资源,有一个很著名的设计模式:资源池 (Resource Pool).该模 ...

  5. Java程序员必须掌握的知识

    1.语法:Java程序员必须比较熟悉语法,在写代码的时候IDE的编辑器对某一行报错应该能够根据报错信息 知道是什么样的语法错误并且知道任何修正. 2.命令:必须熟悉JDK带的一些常用命令及其常用选项, ...

  6. 模仿Masonry链式编程思想

    使用masonry 也将近一年多了,它的链式编程方式一直是很吸引我的. 之前一直没空好好思考它是如何实现,直到现在正好自己有空,因此写下链式编程的基本思路. 链式基本的编程形式如 a.property ...

  7. HTML标签01

    html标签:table 表格 (里面加的属性指整个表格的)tr 行td 单元格 (可以换成th,只有在单元格里面才能输入文字)th 表头 默认让文字居中 文字还会显示加粗状态 font 文字标签 属 ...

  8. 十六、python沉淀之路--迭代器

    一.迭代器 1.什么是迭代器协议:对象必须提供一个next方法,执行该方法要返回迭代中的下一项,要么就引起一个StopIteration异常,以终止迭代(只能往后走,不能往前走). 2.可迭代对象:实 ...

  9. 微软发布WCF教程及大量示例

    继前面 微软公司发布Windows Communication Foundation (WCF)和Windows CardSpace的示例程序之后,微软今天又发布了WF的教程和大量示例,对于学习WF的 ...

  10. python使用wxPython创建一个简单的文本编辑器。

    ubuntu下通过'sudo apt-get install python-wxtools'下载wxPython.load和save函数用于加载和保存文件内容,button通过Bind函数绑定这两个函 ...