java servlet helloworld,Java如何创建HelloWorld Servlet?
Servlet是用于創建動態Web應用程序的Java解決方案,可以與舊的CGI技術進行比較。使用Servlet,我們可以創建一個Web應用程序,該應用程序可以顯示來自數據庫的信息,可以從Web表單接收要存儲在應用程序數據庫中的信息。
這個例子展示了servlet的基本知識,它為瀏覽器返回一個hello world html文檔。Servlet至少會具有doPost()anddoGet()方法,用于處理HTTP POST和GET請求。package?org.nhooo.example.servlet;
import?javax.servlet.ServletException;
import?javax.servlet.http.HttpServlet;
import?javax.servlet.http.HttpServletRequest;
import?javax.servlet.http.HttpServletResponse;
import?java.io.IOException;
import?java.io.PrintWriter;
public?class?HelloWorld?extends?HttpServlet?{
public?HelloWorld()?{
super();
}
protected?void?doGet(HttpServletRequest?req,?HttpServletResponse?res)
throws?ServletException,?IOException?{
doPost(req,?res);
}
protected?void?doPost(HttpServletRequest?req,?HttpServletResponse?res)
throws?ServletException,?IOException?{
res.setContentType("text/html");
PrintWriter?writer?=?res.getWriter();
writer.println("");
writer.println("
Hello?World?Servlet");writer.println("
Hello?World!?How?are?you?doing?");writer.println("");
writer.close();
}
}
為了使servlet在諸如Apache Tomcat之類的servlet容器上工作,我們需要在應用程序的web.xml文件中添加或注冊servlet 。此配置告訴容器有關我們的servlet類的信息以及將請求映射到servlet的URL。<?xml ?version="1.0"?encoding="UTF-8"?>
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee?http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
nhooo-example
HelloWorld
HelloWorld
org.nhooo.example.servlet.HelloWorld
HelloWorld
/HelloWorld
將Servlet部署到容器后,我們可以從URL中以http:// localhost:8080 / app-name / HelloWorld的形式訪問它。
總結
以上是生活随笔為你收集整理的java servlet helloworld,Java如何创建HelloWorld Servlet?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java8 lambda 排序算法,Ja
- 下一篇: tomcat9扩展php 插件,Ecli