`
独浮云
  • 浏览: 6166 次
  • 性别: 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

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

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

    spring+ehcache实例demo

    它具有内存和磁盘存储,缓存加载器,缓存扩展,缓存异常处理程序,一个gzip缓存servlet过滤器,支持REST和SOAP api等特点。 Ehcache最初是由Greg Luck于2003年开始开发。2009年,该项目被Terracotta购买。软件仍然是开源,...

    开发者突击JavaWeb主流框架整合开发(全部源码)

    demo(JSP+JavaBean+Servlet).zip StrutsTest.zip demo(Struts).zip Struts2Test.zip demo(Struts+Hibernate).zip demo(Struts2+Spring+Hibernate).zip HibernateTest.zip demo_ssh2_oa.zip(办公自动化系统) Spring...

    Spring Ibatis Demo

    这是一个servlet + spring + ibatis 的完整例子,里面包含了spring的事务管理以及所有的jar包,下载下来后直接改下数据库配置就可以运行!从界面到action,业务层,dao层有现成的代码!

    struts2+Hibernate+Spring学习示例

    4、网站初始化工作类的实现 dbtest.servlet.LauncherServlet 5、tomcate数据源配置 见 tomcat配置.txt //这个项目用不着了 6、创建了专门的数据库操作工具类 DBUtil、专门的DAO管理工具DAOManager 7、实现了CRUD的...

    Spring 2.0 + Struts 1.2 + Hibernate 3.2 + DWR 2.0 的JavaEE应用示例

    学习对象:熟悉JavaScript, 了解JSTL, servlet/JSP, Struts 1.2, Hibernate, Spring, Ajax技术。 该示例使用MyEclipse 5.5 IDE用来整合四个技术(Struts 1.2, Spring 2.0, Hibernate 3.2和Ajax技术)的轻量级的...

    ssh整合最新demostruts2.3+spring4.0.3+hibernate4.3.4

    3,struts版本:struts-2.3.16.1 spring版本:spring-framework-4.0.3.RELEASE hibernate版本:hibernate-release-4.3.4.Final 4,集成了编码过滤器和压缩过滤器,拿来就可以直接在上面建新工程。

    JAVAjsp_servlet_spring基础语法demo

    本文档主要是pring,mybatis,servlet,jsp,jquery的基础语法点的例子

    Spring-Security-Demo

    SpringSecurity,这是一种基于Spring AOP和Servlet过滤器的安全框架。它提供全面的安全性解决方案,同时在Web请求级和方法调用级处理身份确认和授权。在Spring Framework基础上,Spring Security充分利用了依赖注入...

    spring3+hibernate3+proxool+mysql 超级企业J2EE DEMO(jar在下一个文件中,jar太大了)

    这个工程demo,是本人在企业应用中的项目缩影,绝对实用于企业的应用。 适合朋友: 1.一直用单独的servlet和jsp做J2EE,想使用框架做J2EE的朋友。尤其是对于那些想找工作又不会框架的朋友,会了这个后,你可以很...

    ssh2(struts2+spring2.5+hibernate3.3)自动生成模版

    {自定义的存放包}目录:4个xml文件(applicationContext-dao.xml(dao注入配置),applicationContext-service.xml(service注入配置),action-servlet.xml(action注入配置),struts-{自定义的存放包名}.xml(struts2的...

    demo:构想dubbo + zookeeper + spring mvc

    使用Servlet容器运行(Tomcat、Jetty等),需要在web.xml中装配spring.xml、spring-dao、以及provider配置文件 缺点:增加复杂性(端口、管理、浪费资源(内存) 、需要占用多个端口和内存,不建议 第二种方式: ...

    CXF WebService整合Spring示例工程代码demo

    CXF WebService整合Spring示例工程代码demo可以直接导入eclipse。参照网页http://www.cnblogs.com/hoojo/archive/2011/03/30/1999563.html 完成的webService服务提供。 大致步骤: 1.引入cxf和其他需要的jar包,(本...

    Spring MVC Demo

    &lt;servlet-class&gt;org.springframework.web.servlet.DispatcherServlet&lt;/servlet-class&gt; &lt;!--servlet的参数配置,查找controller位置的xml文件配置,此参数指定了spring配置文件的位置 ,如果你不指定的话,默认...

    org.springframework.web.servlet-3.0.1.RELEASE-A.jar

    Error creating bean with name 'org.springframework.web.servlet.handler.SimpleUrlHandlerMapping#0' defined in ServletContext resource [/WEB-INF/springMVC-servlet.xml]: Initialization of bean failed;...

    spring web flow demo

    从清单 1 中,应注意到一个很重要的特征—— Spring Web Flow 语义与 Servlet API 3 无关。更确切地讲, Spring Web Flow 语义关注的是业务的流程,并未与 Sun 公司的 Web 规范紧密结 合,这种描述是更高层次的抽象...

    Spring+jsp老项目转Springboot的示例Demo

    指导如何将Spring+jsp老项目转Springboot的示例Demo,是以最小化配置方式,访问每个页面不需要经过控制层解释,只需要配置一个JspServlet拦截所有Jsp页面即可。

    spring-security-demo

    SpringSecurity,这是一种基于Spring AOP和Servlet过滤器的安全框架。它提供全面的安全性解决方案,同时在Web请求级和方法调用级处理身份确认和授权。在Spring Framework基础上,Spring Security充分利用了依赖注入...

    Spring零配置Demo---JavaConfig

    采用注解配置SpringMVC,有SpringSecurity,Dao,Controller,Servlet等的样例,部分代码: public void onStartup(ServletContext servletContext) throws ServletException { //日志文件配置 servletContext....

Global site tag (gtag.js) - Google Analytics