zoukankan      html  css  js  c++  java
  • Servlet使用方法(只适合新手)

    要使用Servlet一定要继承于HttpServlet
    HttpHello类,切记要继承HttpServlet
     1 import java.io.IOException;
    2 import javax.servlet.ServletException;
    3 import javax.servlet.http.HttpServlet;
    4 import javax.servlet.http.HttpServletRequest;
    5 import javax.servlet.http.HttpServletResponse;
    6
    7 public class HttpHello extends HttpServlet {
    8 private static final long serialVersionUID = 1L;
    9
    10 public HttpHello() {
    11 super();
    12 }
    13
    14 protected void doGet(HttpServletRequest request,
    15 HttpServletResponse response) throws ServletException, IOException {
    16 response.getWriter().write("Hello, world!");
    17 }
    18
    19 protected void doPost(HttpServletRequest request,
    20 HttpServletResponse response) throws ServletException, IOException {
    21 doGet(request, response);
    22 }
    23
    24 }

    然后在\WebContent\WEB-INF 下的Web.xml中进行下面的配置操作(如果没有就自己创建一个)

              

    web.xml
     1 <?xml version="1.0" encoding="UTF-8"?>
    2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 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">
    3 <display-name>DemoWeb</display-name>
    4 <welcome-file-list>
    5 <welcome-file>index.jsp</welcome-file>
    6 </welcome-file-list>
    7 <servlet>
    8 <servlet-name>HttpHello</servlet-name><!-- 名称起的和类名一样-->
    9 <servlet-class>test.HttpHello</servlet-class> <!-- 类所在的路径 -->
    10 </servlet>
    11 <servlet-mapping>
    12 <servlet-name>HttpHello</servlet-name> <!-- 要和上面的名称相同 HttpHello -->
    13 <url-pattern>/HttpHello</url-pattern>
    14 </servlet-mapping>
    15
    16 </web-app>

    注:生成出来的HttpHello.class文件一定要在\WebContent\WEB-INF \classes文件夹下

    tomcat配置正确的情况下。

              直接访问 http://localhost:8080/项目名称/HttpHello 就可以看到效果了(本例显示的是Hello!world)

  • 相关阅读:
    wpf读取mysql字段类型为text的问题
    设计模式简介
    为 RESTful API 配置 CORS 实现跨域请求
    js FileReader 读取文件
    js读取文件fileReader
    制作svg动态图形效果
    H5与Native交互之JSBridge技术
    位(bit)、字节(byte)、字符、编码之间的关系
    node.js的net模块实现socket通信
    Flexbox如何将页面底部固定在屏幕最下方
  • 原文地址:https://www.cnblogs.com/enum/p/2322699.html
Copyright © 2011-2022 走看看