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("" + title + " "); out.print(""); out.print(heading1); out.print("" + clientName + ":你好
"); out.print(""); 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("" + title + " "); out.print(""); out.print(heading1); out.print("" + clientName + ":你好
"); out.print(""); out.close(); }}
3、更改web.xml
更改配置文件,添加Servlet和Servlet-mapping两个节点。
源码如下:
index.jsp HelloServlet com.nankang.HelloServlet HelloServlet /hello
今天是对Java开发环境进行的第一步尝试,加油。
参考文章:
posted on 2014-07-19 17:59 阅读( ...) 评论( ...) 收藏