avaWeb之使用servlet搭建服务器入门

来源:互联网 发布:社交网络关系图 编辑:程序博客网 时间:2024/05/20 12:21

Servlet(Server Applet)是Java Servlet的简称,称为小服务程序或服务连接器,用Java编写的服务器端程序,主要功能在于交互式地浏览和修改数据,生成动态Web内容。

通俗讲法:

是运行在服务器端的一小段Java程序,接受和响应从客户端发送的请求

作用:

处理客户端请求,并且对请求做出响应

编写一个serclet步骤

1、编写一个类

继承自HttpServlet

重写doGet和doPost方法

2、编写配置文件(web.xml)

先注册后绑定

3、访问

http://localhost/项目名/路径

注意:

接收参数: 格式:value=key

String  value = request.getParameter("key");

例如:http://localhost/day09/hello?username=tom

中,String value = request.getParameter("username");

回写参数:

response.getWriter().print("success");

处理响应中的乱码问题:

resp.setContentType("text/html;charset=utf-8");一般放在第一行 

以下是原码:

复制代码
public class RequestServlet extends HttpServlet {    @Override    protected void doGet(HttpServletRequest req, HttpServletResponse resp)            throws ServletException, IOException {
         resp.setContentType("text/html;charset=utf-8");
      // 接收参数        String value = req.getParameter("username");        System.out.println(value);        //向浏览器回写数据        resp.getWriter().print("data:"+value);                resp.getWriter().print("你好");    }}

复制代码
复制代码
web.xml配置
<?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_2_5.xsd" id="WebApp_ID" version="2.5"> <!-- 使用servlet标签 --> <servlet> <servlet-name>HelloServlet</servlet-name> <servlet-class>cn.itcast.a_hello.HelloServlet</servlet-class> </servlet> <servlet> <servlet-name>RequestServlet</servlet-name> <servlet-class>cn.itcast.b_request.RequestServlet</servlet-class> </servlet> <!-- 绑定路径 --> <servlet-mapping> <servlet-name>HelloServlet</servlet-name> <url-pattern>/hello</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>RequestServlet</servlet-name> <url-pattern>/request</url-pattern> </servlet-mapping></web-app>