首頁  >  文章  >  Java  >  Servlet怎麼設定xml

Servlet怎麼設定xml

(*-*)浩
(*-*)浩原創
2019-05-06 13:44:519893瀏覽

本篇文章將大致介紹servlet如何進行xml檔案的簡單配置,如需詳細了解,推薦課程:Java教學

Servlet怎麼設定xml

在web專案中寫一個類別。

檔名:「SimpleServlet.java」

package cn.mldn.lxh.servlet ;//定义包
import java.io.* ;
// HttpServlet属于javax.servlet.http包下
// ServletException属于javax.servlet包下
import javax.servlet.* ;//导入HttpServlet所属的包
// HttpServletRequest、HttpServletResponse存放在javax.servlet.http包下
import javax.servlet.http.* ;
 
public class SimpleServlet extends HttpServlet
{
       // 表示处理get请求
       public void doGet(HttpServletRequest req,HttpServletResponse resp) throws IOException,ServletException //抛出异常
       {
              PrintWriter out = resp.getWriter() ;//实例化out对象。
              out.println("<HTML>") ;
              out.println("<HEAD>") ;
              out.println("<TITLE>THE FIRST SERVLET</TITLE>") ;
              out.println("</HEAD>") ;
              out.println("<BODY>") ;
              out.println("<H1>Hello World!!!</H1>") ;
              out.println("</BODY>") ;
              out.println("</HTML>") ;
              out.close() ;
       }
       public void doPost(HttpServletRequest req,HttpServletResponse resp) throws IOException,ServletException
       {
              this.doGet(request,response) ;
       }
};

JSP功能和servlet一致,也就是說servlet可以被外部訪問,那麼要存取它就需要透過一個位址,因此只有透過WEB的地址映射來解決了。

如何進行位址對應呢?

這時就需要設定web.xml檔案進行更改到我們想要的位址、路徑。

<servlet>
       <servlet-name>simple</servlet-name>//我们定义的servlet应用名字
       <servlet-class>cn.mldn.lxh.servlet.SimpleServlet</servlet-class> //我们定义的servlet应用名字对应的具体servlet文件
</servlet>
<servlet-mapping>   //地址映射
       <servlet-name>simple</servlet-name> //我们定义的servlet应用名字
       <url-pattern>/demo</url-pattern> //地址名
</servlet-mapping>

行位址對應目的是為了使用servlet,它的工作流程是:

#工作過程:

##輸入位址:http:// localhost:8080/ demo,透過它找到映射檔內部的檔名simple,透過simple找到對應的

name>simple,然後定位到這個servlet檔:cn .mldn.lxh.servlet.SimpleServlet 

由此可見,simple中的名字simple不一定要與servlet的檔案名稱「SimpleServlet.java」一致,它只是在對web.xml檔案配置的時候我們對servlet應用名字的定義,透過cn.mldn.lxh.servlet.SimpleServlet我們就可以定位到這個servlet檔案。

以上是Servlet怎麼設定xml的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn