`

A Simple Server3.0 Example

    博客分类:
  • java
阅读更多

因为好多年没做web开发,所以也一直木有关注JEE新版本的特性了。虽然老早听说Servet3.0可以异步化了,但是一直米有写过例子来跑过。最近思考异步化问题偏向于jvm层面如何保存执行中的栈和恢复栈,对异步化整体缺乏整理的考虑。

现在想来,天天面对的系统主要是接受请求,处理,发起一堆远程调用,接受远程调用结果,处理,构造响应结果,输出,没有太多深层次的业务处理。细化下去就要考虑接受请求、发起远程调用、接受调用结果、构造响应结果这块了。先从接受请求这块开始,就先了解下Servlet的异步化吧。

昨天查了下Servlet3.0的资料,写了个例子,惊奇的发现,竟然不用配置web.xml。虽然从原理上考虑,Annotation这种方式完全可以完成web.xml要实现的功能,但是现在真是这样的时候,还是有点小惊讶的,当然这只是跟记忆中web应用结构的对比后产生的,而不是对其新的实现方式产生的---Spring也有强大的Annotation呢,虽然我的记忆还停留在当年配置文件上......

另外,之前大多用myEclipse开发web应用,所以一时间都不知道怎么写了。。。不能自动发布,没有jee包的导入....淡定中,自己写ant文件拷贝,拷贝到tomcat目录下的时候,拷成webapp的接口即可,jee包从tomcat下边拷!

从tomcat的lib目录下拷servlet-api.jar

写build.xml文件:

<?xml version="1.0" encoding="GB2312"?>
<!DOCTYPE project>
<project name="async" default="autoCopy" basedir=".">
	<property name="targetDir" value="J:\java_tools\apache-tomcat-7.0.28\webapps\async"/>
	<property name="autoCompileClassDir" value="bin"/>
	<property name="webappDir" value="web"/>
	
	<target name="autoCopy" depends="copyClass,copyWeb">
	</target>
	<target name="copyClass">
		<echo message="=====Copying Class Files====="/>  
		<copy todir="${targetDir}/WEB-INF/classes">
			<fileset dir="${autoCompileClassDir}">
				<include name="**/*.class"></include>
			</fileset>
		</copy>
	</target>
	<target name="copyWeb">
		<echo message="=====Copying Web Files====="/>
		<copy todir="${targetDir}">
			<fileset dir="${webappDir}">
				<include name="**/*.xml"></include>
				<include name="**/*.properties"></include>
				<include name="**/*.jsp"></include>
				<include name="**/*.html"></include> 
			</fileset>
		</copy> 
	</target> 
</project>

 拷到我tomcat/webapps目录下了。

Servlet定义:

package com.tmall.buy.web;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.AsyncContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(asyncSupported = true, name = "asyncServlet", urlPatterns = { "/asyncServlet" }, initParams = {
		@WebInitParam(name = "hello", value = "world"),
		@WebInitParam(name = "gun", value = "dan") })
public class AsyncServlet extends HttpServlet {
	private static final long serialVersionUID = 133332222222L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doAsync(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doAsync(req, resp);
	}
	
	private void doAsync(HttpServletRequest req,HttpServletResponse resp) throws IOException{
		resp.setContentType("text/html");
		System.out.println("req.isAsyncSupported = " + req.isAsyncSupported());
		final AsyncContext ctx = req.startAsync();
		new Thread(new Runnable(){
			@Override
			public void run() {
				PrintWriter out = null;
				try {
					out = ctx.getResponse().getWriter();
					Thread.sleep(1000);
					System.out.println("Async Thread~~");
					out.write("<br>Async Write ~~~<br>");
					out.flush();
				} catch (Exception e) {
					e.printStackTrace();
				}finally{
					ctx.complete();
				}
			}
			
		}).start();
	}	
}

 详细参考这里

另外蛋疼写了个Filter:

package com.tmall.buy.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;

@WebFilter(asyncSupported = true, filterName = "commonFilter", urlPatterns = { "*" })
public class CommonFilter implements Filter {

	@Override
	public void destroy() {

	}

	@Override
	public void doFilter(ServletRequest arg0, ServletResponse arg1,
			FilterChain arg2) throws IOException, ServletException {
		System.out.println(arg0.getServerName());
		arg2.doFilter(arg0, arg1);
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {

	}
}

 然后,没了,整个应用就这么多东西了。

只是刚开始Filter的syncSupported属性没设置,于是乎异步就出错了,页面的异常堆栈:

java.lang.IllegalStateException: Not supported.
	org.apache.catalina.connector.Request.startAsync(Request.java:1664)
	org.apache.catalina.connector.Request.startAsync(Request.java:1657)
	org.apache.catalina.connector.RequestFacade.startAsync(RequestFacade.java:1023)
	com.tmall.buy.web.AsyncServlet.doAsync(AsyncServlet.java:35)
	com.tmall.buy.web.AsyncServlet.doGet(AsyncServlet.java:23)
	javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
	javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
	com.tmall.buy.web.filter.CommonFilter.doFilter(CommonFilter.java:25)

在Filter的@WebFilter标注上加了asyncSupported=true之后,就ok了 

 

分享到:
评论
1 楼 zys0523 2013-01-08  
膜拜麦大牛

相关推荐

    openGLES3.0Example_8_Simple_VertexShader.rar

    在这个"openGLES3.0Example_8_Simple_VertexShader"示例中,我们将深入探讨如何利用OpenGL ES 3.0的顶点着色器来绘制一个紫色的三角形。顶点着色器是图形管线中的第一步,负责处理输入的顶点数据,包括位置、颜色、...

    计算机网络第六版答案

    Hence, it becomes possible for the attacker to issue a command to all the nodes, that target a single node (for example, all nodes in the botnet might be commanded by the attacker to send a TCP SYN ...

    Sakemail

    Developed with a version 2.0b of WSockets and D3.0.9.3.1b- Changed the POP.login to a function that return the number of new msgs.- Added the event OnRetrieveProgress on the SakPOP, and fixed the ...

    programming_the_semantic_web.pdf

    A Servlet Container for the Sesame Server 196 Installing the Sesame Web Application 196 The Workbench 197 Adding Data 199 SPARQL Queries 200 REST API 202 Other RDF Stores 203 Jena (Open Source) 204 ...

    Firebird Maestro 17.1 带破解

    For example, you can perform operations with a group of objects as well as with a single object in Object Manager, sort, group and filter the database objects within Object Browser, copy an object ...

    从ASP3.0和JavaScript调用WebService

    本主题主要探讨如何在ASP 3.0(Active Server Pages 3.0)和JavaScript环境中调用WebService,这对于构建分布式系统和跨平台交互至关重要。在.NET框架下,ASP.NET提供了创建Web服务的能力,而JavaScript作为客户端...

    VB编程资源大全(英文源码 数据库)

    graphdb.zip This demonstrates how to graph information from a database to a picturebox.&lt;END&gt;&lt;br&gt;5 , ClassBuilder1.zip Class Builder - reads SQL Server or Access database and creates a class of ...

    Beginning Microsoft Visual CSharp 2008 Wiley Publishing(english)

    Creating a Simple ASP.NET Web Service 757 Testing the Web Service 759 Implementing a Windows Client 761 Calling the Service Asynchronously 765 Implementing an ASP.NET Client 768 ...

    简单的web开发——servlet案例

    &lt;servlet-class&gt;com.example.SimpleServlet&lt;/servlet-class&gt; &lt;servlet-name&gt;SimpleServlet &lt;url-pattern&gt;/simple ``` 这将把URL路径`/simple`映射到`SimpleServlet`。 ### 5. 运行Servlet应用 在...

    创建简单servlet

    这意味着,访问`http://yourserver/yourapp/simple`时,将会触发`SimpleServlet`。 4. **部署和测试**:将编译后的Servlet类打包成`.war`文件,然后将其部署到Tomcat服务器的`webapps`目录下。启动服务器后,可以...

    python3.6.5参考手册 chm

    PEP 3333: Python Web Server Gateway Interface v1.0.1 Other Language Changes New, Improved, and Deprecated Modules email elementtree functools itertools collections threading datetime and time ...

    VB6调用WebService

    通常使用SOAP(Simple Object Access Protocol)协议传输数据,并通过WSDL(Web Services Description Language)定义服务接口,UDDI(Universal Description, Discovery, and Integration)则用于服务的发现和注册...

    EurekaLog_7.5.0.0_Enterprise

    18)..Fixed: Possible "Unit XYZ was compiled with a different version of ABC" when using packages 19)..Fixed: FastMM shared MM compatibility 20)..Fixed: Minor bugs in stack tracing (which usually ...

    php.ini-development

    The syntax of the file is extremely simple. Whitespace and lines ; beginning with a semicolon are silently ignored (as you probably guessed). ; Section headers (e.g. [Foo]) are also silently ignored,...

    使用PHP / C#开发SOAP Web服务

    $server = new SoapServer(null, array('uri' =&gt; 'http://example.com/mysoap')); $server-&gt;setClass('MyService'); $server-&gt;handle(); ``` 2. **生成WSDL**:WSDL是SOAP服务的元数据,描述了服务提供的操作、输入...

    DebuggingWithGDB 6.8-2008

    4.11.1 A Non-obvious Benefit of Using Checkpoints . . . . . . . . . . . . 5 25 26 28 28 29 29 30 31 31 34 36 37 Stopping and Continuing . . . . . . . . . . . . . . . . . . 39 5.1 Breakpoints, ...

    spring-framework-reference4.1.4

    Instantiating a container .................................................................................... 24 Composing XML-based configuration metadata .......................................... ...

    spring-framework-reference-4.1.2

    Instantiating a container .................................................................................... 24 Composing XML-based configuration metadata .......................................... ...

Global site tag (gtag.js) - Google Analytics