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
配置完成。
测试时,从控制台输出可以看到注入成功,且读库操作成功。
下一篇: C数组和指针的注意点