首页 > 开发 > Java > 正文

javaWeb使用servlet搭建服务器入门

2024-07-13 10:13:47
字体:
来源:转载
供稿:网友

百度百科说法:

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>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持VeVb武林网。


注:相关教程知识阅读请移步到JAVA教程频道。
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表