`
独浮云
  • 浏览: 6439 次
  • 性别: Icon_minigender_1
  • 来自: 呼和浩特
社区版块
存档分类
最新评论

servlet+spring测试Demo

阅读更多

      最近在学习熟悉WEB框架。搭建servlet+spring时,卡了很长时间。将遇到的问题记录下来,供以后使用。

参考URL:http://blog.csdn.net/xwl617756974/article/details/7451773

(本文内容只是按引用链接的步骤,进行的测试。非原创)

 

      平时使用spring框架时,总是和strusts或springMVC等MVC框架联用。想自己学习下只用spring框架的IOC,使用servlet来控制跳转。

 

  实现的中心思想:给普通的Servlet提供一个代理类,用于依赖注入。注入好所有需要的属性后,再执行Servlet本身的doGet、doPost等方法。

 

以下直接贴代码备忘:

1.Servlet代理类。

package syh.servlet;

import java.io.IOException;

import javax.servlet.GenericServlet;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

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

public class DelegatingServletProxy extends GenericServlet {
    private String targetBean;
    private Servlet proxy;

    @Override
    public void service(ServletRequest arg0, ServletResponse arg1) throws ServletException, IOException {
        proxy.service(arg0, arg1);
    }

    @Override
    public void init() throws ServletException {
        this.targetBean = this.getServletName();
        getServletBean();
        proxy.init(getServletConfig());
    }
   
    private void getServletBean() {
        WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
        this.proxy = (Servlet) wac.getBean(targetBean);
    }
   
}

2.编写Servlet类。

package syh;

import java.io.IOException;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;

import syh.service.UserAccount;

@Component
public class SpringServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    @Resource
    private UserAccount userAccount;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("aaaaaa");
        System.out.println(userAccount);
        userAccount.checkAccount("", "");
        super.doGet(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // TODO Auto-generated method stub
        super.doPost(req, resp);
    }

}

3.编写Servlet中要注入的Service类。

接口:

package syh.service;

public interface UserAccount {
    public boolean checkAccount(String account, String password);
}
实现:

package syh.service.impl;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.annotation.Resource;

import org.apache.commons.dbcp.BasicDataSource;
import org.springframework.stereotype.Component;

import syh.service.UserAccount;

@Component
public class UserAccountImpl implements UserAccount {
    @Resource
    private BasicDataSource dataSource;

    @Override
    public boolean checkAccount(String account, String password) {
        System.out.println(dataSource);
       
        Connection actualCon = null;
        Statement statement = null;
        ResultSet resultSet = null;
        try {
            actualCon = dataSource.getConnection();
            statement = actualCon.createStatement();
            resultSet = statement.executeQuery("select * from user");
            while (resultSet.next()) {
                System.out.println(resultSet.getString(1) + "  " + resultSet.getString("name"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                resultSet.close();
                statement.close();
                actualCon.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
       
        return "admin".equals(account) && "123".equals(password);
    }

}

为了测试Servlet中注入的Service,是否可级联注入Service中引用的其他类。在Service实现类中注入了dataSource,并执行了查询数据库操作。

 

4.Spring配置文件。springDatasource.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" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation=" 
    http://www.springframework.org/schema/beans  
    http://www.springframework.org/schema/beans/spring-beans-2.5.xsd 
    http://www.springframework.org/schema/context  
    http://www.springframework.org/schema/context/spring-context-2.5.xsd 
    http://www.springframework.org/schema/tx  
    http://www.springframework.org/schema/tx/spring-tx-2.5.xsd 
    http://www.springframework.org/schema/aop  
    http://www.springframework.org/schema/aop/spring-aop-2.5.xsd    
    ">
    <context:component-scan base-package="syh"></context:component-scan>

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close">
        <property name="defaultAutoCommit" value="true" />
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/test" />
        <property name="username" value="root" />
        <property name="password" value="123456" />
        <!--initialSize: 初始化连接 -->
        <property name="initialSize" value="2" />
        <!--maxIdle: 最大空闲连接 -->
        <property name="maxIdle" value="5" />
        <!--minIdle: 最小空闲连接 -->
        <property name="minIdle" value="5" />
        <!--maxActive: 最大连接数量 -->
        <property name="maxActive" value="2" />
        <!--removeAbandoned: 是否自动回收超时连接 -->
        <property name="removeAbandoned" value="true" />
        <!--removeAbandonedTimeout: 超时时间(以秒数为单位) -->
        <property name="removeAbandonedTimeout" value="180" />
        <!--maxWait: 超时等待时间以毫秒为单位 6000毫秒/1000等于60秒 -->
        <property name="maxWait" value="3000" />
        <property name="validationQuery">
            <value>SELECT 1</value>
        </property>
        <property name="minEvictableIdleTimeMillis">
            <value>3600000</value>
        </property>
        <property name="timeBetweenEvictionRunsMillis">
            <value>600000</value>
        </property>
        <property name="testOnBorrow">
            <value>true</value>
        </property>
    </bean>

</beans>

 

开始测试时一直报加载springServlet错误,增加以下配置后解决:

<context:component-scan base-package="syh"></context:component-scan>

 

中间尝试过下面的配置,但是错误依旧。有空研究下

<context:component-scan base-package="syh.*"></context:component-scan>

 

5.配置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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>servletTest</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
   
    <servlet> 
        <servlet-name>springServlet</servlet-name> 
        <servlet-class> 
            syh.servlet.DelegatingServletProxy
        </servlet-class> 
        <load-on-startup>1</load-on-startup> 
    </servlet> 
    <servlet-mapping> 
        <servlet-name>springServlet</servlet-name> 
        <url-pattern>/spring</url-pattern> 
    </servlet-mapping>
   
    <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
           classpath:springDatasource.xml
       </param-value>
  </context-param>
  <listener>
    <description>启动spring上下工厂的监听器</description>
    <listener-class>
          org.springframework.web.context.ContextLoaderListener
       </listener-class>
  </listener>
</web-app>

 

关键点:servlet-class要配置成servlet的代理类。DelegatingServletProx

 

配置完成。

 

测试时,从控制台输出可以看到注入成功,且读库操作成功。

 

 

分享到:
评论

相关推荐

    jsf+spring+servlet的demo

    总的来说,这个"jsf+spring+servlet的demo"是一个综合性的Web应用实例,它演示了如何利用JSF构建用户界面,Spring处理业务逻辑,以及Servlet协调请求处理。开发者可以从中学习到如何集成这三个技术,理解它们在实际...

    maven+servlet+jsp+bean的demo

    在本项目"maven+servlet+jsp+bean的demo"中,我们将会探索JavaWeb开发的基本元素,包括Maven构建工具、Servlet、JSP(JavaServer Pages)以及Bean。这个小示例演示了如何在IntelliJ IDEA中创建一个完整的Maven工程,...

    Struts+Spring+Hibernate+Ajax的Demo

    在这个"Struts+Spring+Hibernate+Ajax的Demo"中,开发者使用了这些技术来创建一个功能丰富的示例应用。下面将详细阐述这四种技术以及DWR和Dojo在其中的作用。 **Struts** 是一个开源的MVC(Model-View-Controller)...

    Spring mvc + Spring + Spring jdbc 整合 demo

    1. **配置文件**:项目通常包含两个主要的配置文件,一个用于Spring MVC(如servlet-context.xml),另一个用于Spring框架的核心配置(如applicationContext.xml)。这些文件会定义Bean,包括Controller、Service、...

    struts2+spring+ibatis的小demo

    在这个“struts2+spring+ibatis”的小demo中,我们将深入探讨这三个框架的核心功能以及它们如何协同工作。 **Struts2** 是一个强大的MVC(Model-View-Controller)框架,它提供了处理用户请求、控制应用程序流程的...

    struts1.2 + spring2.5 + hibernate3.2框架demo

    总结来说,这个demo项目提供了一个学习和实践Struts1.2、Spring2.5和Hibernate3.2集成的平台,涵盖了MVC设计模式、依赖注入、面向切面编程和对象关系映射等多个关键概念。通过深入研究和修改这个项目,开发者能够...

    maven+spring+cxf webservice demo

    【标题】"maven+spring+cxf webservice demo"是一个基于Maven、Spring和CXF框架的Web服务示例项目,旨在展示如何整合这三个技术来创建和消费Web服务。Maven是项目管理和构建工具,Spring提供了强大的依赖注入和面向...

    Spring mvc + Spring + Mybatis 整合demo

    3. **配置Spring MVC**:创建Spring MVC的配置文件(如`servlet-context.xml`),配置DispatcherServlet,声明视图解析器,定义拦截器,以及处理器映射器和处理器适配器。 4. **配置Mybatis**:编写Mybatis的全局...

    【基础练习】jsp+servlet+jdbc 网上购物商系统(带sql脚本)

    往后学习,大家会碰到很多的框架,例如JDBC的配置类不需要自己写,用mybatis就可以做连接和增删改查,例如servlet也会被spring boot的注解所代替,但是归根结底,它们都是要基于这类知识的。我会把我 拓展了的地方写...

    Jersey+spring Demo

    2. **web.xml** - Web应用的部署描述符,配置了Jersey的Servlet和Spring的DispatcherServlet。 3. **ApplicationConfig.java** - 可能是Jersey的应用配置类,用于注册资源类和服务提供者。 4. **Resource Classes** ...

    spring+spring mvc+mybatis配置Demo

    同时,Spring MVC的配置文件(如`servlet-context.xml`)会定义拦截器、视图解析器、资源处理等。 在实际的SSM Demo中,项目结构通常如下: - src/main/java:存放业务逻辑、DAO接口、Service接口及实现、...

    Struts + Spring + EJB3 demo

    总结来说,"Struts + Spring + EJB3 demo"是一个展示如何在Java EE环境中整合这三个框架的实例。通过这样的整合,开发者可以构建出高效、可维护的大型企业系统,同时充分利用每个框架的优势,如Struts的MVC结构、...

    使用jsp+servlet+jdbc实现花卉管理系统.zip

    3. **Servlet框架**:尽管没有具体指出使用了哪个框架,但常见的如Spring MVC或Struts等,可以简化Servlet的开发,提供模型-视图-控制器(MVC)结构,便于代码组织和测试。这些框架可以提高项目的可维护性和可扩展性...

    Springmvc+Spring+MybatisDemo

    【Springmvc+Spring+MybatisDemo】项目是一个典型的Java企业级应用示例,它整合了三个主流的开源框架:Spring MVC、Spring以及MyBatis,用于构建高效、灵活且易于维护的后端服务。这个Demo提供了完整的源码和编译...

    jsp+servlet+jdbc+mysql项目

    【标题】"jsp+servlet+jdbc+mysql项目"是一个典型的Web开发实践,它结合了四种核心技术,用于构建基于...同时,了解这些技术如何协同工作,对于进一步学习更复杂的框架如Spring MVC或Spring Boot也会打下坚实的基础。

    springboot+springcloud项目demo(自己编写,可正常运行)

    在这个"springboot+springcloud项目demo"中,你可能会看到以下结构: - `cloudDemo`: 这是项目的主目录,可能包含多个子模块,每个子模块代表一个微服务。 - `eureka-server`: Eureka服务注册与发现服务器的代码。 ...

    Spring+SpringMVC+MyBatis 整合 DEMO

    Spring框架作为核心,提供了依赖注入(DI)和面向切面编程(AOP)功能,使得组件之间松耦合,便于测试和管理。在DEMO中,Spring会管理所有Bean的生命周期,并负责各组件间的协作。 SpringMVC是Spring的一个模块,专...

    SpringMVC+hibernate4+Spring4+mysql整合demo

    5. **Spring MVC配置**:创建`springmvc-servlet.xml`,定义视图解析器,处理器映射器和处理器适配器。注册Controller,使用`@RequestMapping`处理请求。 6. **编写Controller**:创建一个登录Controller,处理HTTP...

    spring+cxf小demo

    【Spring+CXF小Demo】是基于Java开发的一个入门级示例,主要展示了如何结合Spring框架与CXF库来创建和消费Web服务。Spring是企业级应用开发的强大框架,而CXF是一个开源的服务栈,用于构建和部署Web服务。这个Demo...

    SpringMVC+Hibernate+jpa+Spring demo

    - **配置文件**:如`applicationContext.xml`或`dispatcher-servlet.xml`,用于配置Spring容器和SpringMVC。 - **实体类**:表示数据库表的Java类,通常使用JPA的注解进行配置,例如`@Entity`、`@Table`等。 - **...

Global site tag (gtag.js) - Google Analytics