软件编程
位置:首页>> 软件编程>> java编程>> javaWeb使用servlet搭建服务器入门

javaWeb使用servlet搭建服务器入门

作者:幸福倒带  发布时间:2023-11-21 04:47:45 

标签:javaWeb,servlet,服务器

百度百科说法:

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>

来源:http://www.cnblogs.com/ncl-960301-success/archive/2017/11/22/7880798.html

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com