创建一个spring管理的应用程序,想在应用程序中加一个管理功能,因此采用嵌入式web服务器jetty来完成。
1. spring的xml配置中需要加上<import resource="jetty.xml"/>这一行代码
2.创建jetty.xml文件:
<beans xmlns="http://www.springframework.org/schema/beans" 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"> <bean id="handler" class="org.eclipse.jetty.webapp.WebAppContext"> <property name="contextPath" value="/admin" /> <property name="resourceBase" value="./webapps/admin" /> <property name="logUrlOnStart" value="true" /> </bean> <bean id="Server" class="org.eclipse.jetty.server.Server" init-method="start" destroy-method="stop"> <property name="connectors"> <list> <bean id="Connector" class="org.eclipse.jetty.server.nio.SelectChannelConnector"> <property name="port" value="9191" /> </bean> </list> </property> <property name="handler"> <ref bean="handler" /> </property> </bean> </beans>
注意 name="contextPath" value="/admin" 和 port value="9191"
3.配置好以后需要在项目中添加web目录:
webapps
admin
WEB-INF
web.xml
index.jsp
目录的基本结构为上面描述,admin为访问的上下文环境,如果不创建也可以
4.可以创建你的web项目了,包括jsp和servlet
5.不过有一点,想要在servlet中使用spring管理的bean是个麻烦的问题,因为他们不再同一个上下文环境中,不能随意的注入,解决办法为:创建一个获取spring管理的bean的工具类
package net.etongbao.common.utils; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; /** * 获得指定上下文和Root上下文环境 * <p> * 通过在*.xml文件中配置 * <pre> * <bean id="applicationContextHelper" class="net.etongbao.common.ApplicationContextHelper"></bean> * </pre> * 配置完成后ApplicationContextHelper会获得所在xml文件Context */ public class ApplicationContextHelper implements ApplicationContextAware { private static ApplicationContext ctx = null; /** * 获得Bean对象 * * @param clazz Bean类型 * @return Bean对象 */ public static <T> T getBean(Class<T> clazz) { return ctx.getBean(clazz); } /** * 获得Bean对象 * * @param className * @return */ public static Object getBean(String className) { return ctx.getBean(className); } /** * 获得应用所在上下文环境 * * @return */ public static ApplicationContext getContext() { return ctx; } /* (non-Javadoc) * @see org.springframework.context.ApplicationContextAware#setApplicationContext(org.springframework.context.ApplicationContext) */ @Override public void setApplicationContext(ApplicationContext args0) throws BeansException { ctx = args0; } }
在需要把这个类注入到spring环境中,在xml中这样配置:
<bean id="applicationContextHelper" class="net.etongbao.common.utils.ApplicationContextHelper"></bean>
6.这样就可以在你的Servlet种使用spring管理的bean了 如:
PospCacheService pospCacheService = (PospCacheService) ApplicationContextHelper.getBean("pospCacheService");