胖蔡说技术
随便扯扯

Servlet 使用介绍(3)

说明

本篇记录一个Servlet的创建过程和基本使用.由于,Servlet是基于Http协议使用的,所以,可以在http协议的基础上作一些改变,来修改适用我自己的servlet.

Servlet使用

接下来实现一个简单的Servlet创建和通信,服务端创建一个Servlet来接受Post、get请求,为了便于测试客户端,我使用一个python文件模拟客户端请求。

Servlet创建

  • 创建ServletDemo工程

ServletDemo工程选用Eclipse通用动态网页工程结构,目录如下:

ServletDemo
--src
  --cn.enjoytoday
    --Servlet_one.java
--WebContent
  --META_INF
    --MANIFEST.MF
  --WEB_INF
    --lib
    --web.xml
  --index.xml

  • 创建Servlet类Servlet选择继承HttpServlet,便于直接重写doGet和doPost方法,代码如下:
package cn.enjoytoday;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Reader;
import java.util.Enumeration;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author hfcai
 *@date 2017/8/7
 *继承HttpServlet实现Servlet
 *
 */
public class Servlet_one extends HttpServlet {


	/**
	 * get方法回调
	 */
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		System.out.println("doGet,and request url:"+req.getRemoteAddr());
      readString(req.getReader());
      getInitParmas();
    	response(resp.getWriter(), "Servlet_one doGet");

	}



	/**
	 * post 方法回调
	 */
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		System.out.println("doPost,and request url:"+req.getRemoteAddr());
		readString(req.getReader());
    getInitParmas();
		response(resp.getWriter(), "Servlet_one doPost");
	}

	private void  getInitParmas() {
		 Enumeration<String>names=	getInitParameterNames();
		 while (names.hasMoreElements()) {
			String name = (String) names.nextElement();
			System.out.println("initParam name:"+name+",and value is:"+getInitParameter(name));

		}

	}


	private void readString(BufferedReader bufferedReader) throws IOException {

		String line=null;
		StringBuffer stringBuffer=new StringBuffer();
		System.out.println("one line:"+bufferedReader.readLine());
		while( (line=bufferedReader.readLine())!=null) {
			stringBuffer.append(line+"\n");
		}
		System.out.println("get request String:"+stringBuffer.toString());
	}



	private void  response(PrintWriter writer,String content) {
		writer.append(content).flush();
	}



}

  • 创建web.xml文件

配置web.xml文件,让serlvet可以被解析访问,配置信息如下:


<?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"
   xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
   id="WebApp_ID" version="3.0">

   <display-name>ServletDemo</display-name>


   <welcome-file-list>
      <welcome-file>index.html</welcome-file>
   </welcome-file-list>



   <servlet>
     <servlet-name>one</servlet-name>
     <servlet-class>cn.enjoytoday.Servlet_one</servlet-class>

     <!--  初始化参数 -->
     <init-param>
             <param-name>info</param-name>
             <param-value>basic httpServlet demo.</param-value>
     </init-param>
     <!-- servlet加载启动设置,当其大于等于0时表示应用启动时加载,否则则表示访问时加载,初始加载时的数值设置越小加载优先级越高. -->
     <load-on-startup>1</load-on-startup>
   </servlet>

   <servlet-mapping>
     <servlet-name>one</servlet-name>
     <url-pattern>/one</url-pattern>
   </servlet-mapping>
   </web-app>

需要注意的是load-on-startup标签位加载启动设置,init-param为启动传入参数.url开始为当前项目定位url.

  • Tomcat 启动
    可以通过eclipse 将web应用发布在tomcat中。

Servlet_Client创建

为了方便,访问客户端,采用python完成,代码如下:

#!/usr/bin/env python
# -*-encoding:utf-8 -*-
import  socket


IP_ADDRESS="127.0.0.1"
IP_PORT=8080


def main(data):
    '''
     default test method to Servlet.such as use xmpp protocol to request .
    :return:
    '''

    socket_client=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    socket_client.connect((IP_ADDRESS,IP_PORT))
    socket_client.send(data+"\n")
    response=socket_client.recv(1024)
    socket_client.close()
    print "get response %s" % response



def doHttp(method,url):
    data='''%s /ServletDemo/%s HTTP/1.1
Host: %s:%s
Connection: keep-alive
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.84 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8

this is a test about %s
test of servlet
''' % (method,url,IP_ADDRESS,IP_PORT,method)
    return data



if __name__ == '__main__':
    print "begin socket conneted."
    main(doHttp("GET","one"))
    # main(doHttp("POST","one"))

如上,可以通过控制访问方法对servlet进行响应的调整。可通过如下命令发起访问:

# python servlet_client.py

返回结果如下:


begin socket conneted.
get response HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Transfer-Encoding: chunked
Date: Tue, 08 Aug 2017 00:09:49 GMT

11
Servlet_one doGet

测试成功.

赞(0) 打赏
转载请附上原文出处链接:胖蔡说技术 » Servlet 使用介绍(3)
分享到: 更多 (0)

请小编喝杯咖啡~

支付宝扫一扫打赏

微信扫一扫打赏