新西兰服务器

javaWeb使用servlet搭建服务器入门


javaWeb使用servlet搭建服务器入门

发布时间:2020-09-27 09:40:50 来源:脚本之家 阅读:80 作者:幸福倒带 栏目:编程语言

百度百科说法:

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>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持高防服务器网。

[微信提示:高防服务器能助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。

[图文来源于网络,不代表本站立场,如有侵权,请联系高防服务器网删除]
[