1、开发自己的Servlet
2、在pom.xml文件中添加必要的支持
<dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.4</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.mortbay.jetty</groupId> <artifactId>jetty</artifactId>
注意:最好不要使用最新版本的servlet-api和jetty。在最新的jetty中增强了Cookie的操作,会调用setHttpOnly方法,而这时servlet3.0中的规范,<version>6.1.25</version> <scope>test</scope> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.1.2</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.7</version> <scope>test</scope> </dependency>
从Maven中下载3.0的servlet-api也不支持该方法,执行将出错。
3、测试用例的编写
// 创建Servlet的运行环境 public static Server server; @Override protected void setUp() throws Exception { // TODO Auto-generated method stub super.setUp(); server = new Server(99); Context root = new Context(server,"/",Context.SESSIONS); root.addServlet(new ServletHolder(new servletName()), "/servletpath");//此处写servlet-mapping的类名和路径 server.start(); } @Test public void testLogin1() { DefaultHttpClient httpclient = new DefaultHttpClient(); HttpPost method = new HttpPost("http://localhost:99/servletpath"); ByteArrayEntity reqEntity = new ByteArrayEntity ("123".getBytes()); method.setEntity(reqEntity); HttpResponse response; try { response = httpclient.execute(method); HttpEntity resEntity = response.getEntity(); assertNotNull(resEntity); assertEquals(response.getStatusLine().getStatusCode(), 200); } catch (ClientProtocolException e1) { // TODO Auto-generated catch block e1.printStackTrace(); Assert.fail(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); Assert.fail(); } } @Override protected void tearDown() throws Exception { // TODO Auto-generated method stub super.tearDown(); server.stop(); } }