daixinet

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

 

Java响应Http请求:

1、创建项目

  因为对Java环境不是很熟悉,第一步卡住了好长时间,

  javax怎么引用,

  在Java EE 5 Libraries中的javaee.jar中,项目中怎么引用Java EE 5 Libraries,可以网上查一下。

2、创建Servlet类

  这一块就是实现代码,继承HttpServlet ,实现doGet和doPost方法即可。

  示例源码如下:

package com.nankang;

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

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

public class HelloServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException {
        String clientName = request.getParameter("clientName");
        if (clientName != null) {
            clientName = new String(clientName.getBytes("ISO-8859-1"), "GB2312");
        } else {
            clientName = "我的朋友";
        }

        PrintWriter out;
        String title = "HelloServlet";
        String heading1 = "HelloServlet的doGet方法的输出:";
        response.setContentType("text/html;charset=GB2312");
        out = response.getWriter();
        out.print("<HTML><HEAD><TITLE>" + title + "</TITLE>");
        out.print("</HEAD><BODY>");
        out.print(heading1);
        out.print("<h1><p>" + clientName + ":你好</h1>");
        out.print("</BODY></HTML>");
        out.close();
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException {

        String clientName = "我的朋友";

        PrintWriter out;
        String title = "HelloServlet";
        String heading1 = "HelloServlet的doPost方法的输出:";
        response.setContentType("text/html;charset=GB2312");
        out = response.getWriter();
        out.print("<HTML><HEAD><TITLE>" + title + "</TITLE>");
        out.print("</HEAD><BODY>");
        out.print(heading1);
        out.print("<h1><p>" + clientName + ":你好</h1>");
        out.print("</BODY></HTML>");
        out.close();
    }

}

 

3、更改web.xml

  更改配置文件,添加Servlet和Servlet-mapping两个节点。

  源码如下:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
    <servlet>
        <servlet-name>HelloServlet</servlet-name>
        <servlet-class>com.nankang.HelloServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>HelloServlet</servlet-name>
        <url-pattern>/hello</url-pattern>
    </servlet-mapping>
</web-app>

 

今天是对Java开发环境进行的第一步尝试,加油。

参考文章:http://www.cnblogs.com/panjun-Donet/archive/2010/02/22/1671290.html

posted on 2014-07-19 17:59  daixinet.com  阅读(224)  评论(0编辑  收藏  举报