groovy 和jetty 搭建小webapp应用(转)

有时候,我们需要的一个简单的不能再简单的web应用,通常我这时候会用jetty来实现一个嵌入式的web容器,写一个bat,鼠标点一下就能跑起来。 目录结构:

引用---App

---www

---WEB-INF

---web.xml

---index.gsp

---index.groovy

---logs

---lib

---commons-logging.jar

---groovy-all-1.5.7.jar

---jasper.jar

---javax.servlet.jar

      ---jetty5.1.8-z4.jarweb.xml:

web.xml

<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/j2ee/dtds/web-app_2_3.dtd">
<web-app>
<display-name>groovy</display-name>
<description>groovy</description>
<servlet>
<servlet-name>GSP</servlet-name>
<servlet-class>groovy.servlet.TemplateServlet</servlet-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
<init-param>
<param-name>debug</param-name>
<param-value>0</param-value>
</init-param>
</servlet>
<servlet>
<servlet-name>Groovy</servlet-name>
<servlet-class>groovy.servlet.GroovyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Groovy</servlet-name>
<url-pattern>*.groovy</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>GSP</servlet-name>
<url-pattern>*.gsp</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.gsp</welcome-file>
</welcome-file-list>
</web-app>
 

app.groovy(启动脚本):

 
import org.mortbay.http.HttpContext;   
import org.mortbay.http.HttpListener;   
import org.mortbay.http.NCSARequestLog;   
import org.mortbay.http.SocketListener;   
import org.mortbay.http.SslListener;   
import org.mortbay.http.handler.MsieSslHandler;   
import org.mortbay.jetty.Server;   
import org.mortbay.jetty.servlet.WebApplicationContext;   
//应用定义   
def port = 8089  
def approot = ["/":"www"]//虚拟目录,支持多个["/":"www","/demo":"demo"]   
  
SocketListener listener = new SocketListener();   
listener.setPort(port);   
listener.setMinThreads(5);   
listener.setMaxThreads(100);   
listener.setMaxIdleTimeMs(30000);   
listener.setLowResourcePersistTimeMs(2000);   
listener.setAcceptQueueSize(0);   
Server server = new Server();       
server.addListener(listener);   
server.setRequestsPerGC(2000);   
server.setStatsOn(false);   
approot.each(){key,value ->   
  server.addWebApplication(key, value);   
}   
server.start();
 
 
index.groovy(例子): Java代码 
request.setAttribute("user","1111")

context.getRequestDispatcher("/index.gsp?iuser=admin").forward(request,response)

index.gsp(例子):

Java代码 
<%
println params.iuser
println request.getAttribute("user")
println request.remoteHost
println headers.host
%>
 
windows下的bat: run.bat:

Java代码

java-classpathlib/groovy-all-1.5.7.jar;lib/javax.servlet.jar;lib/jetty5.1.8-z4.jar;lib/commons-logging.jar;lib/jasper.jargroovy.ui.GroovyMainapp.groovy

相关推荐