jsp呼叫servlet的方法:先在JS裡面寫一個呼叫servlet的事件;然後利用「」標籤的「onload」呼叫這個事件,來實作jsp頁面呼叫servlett即可。
這篇文章使用方法:先在JS裡面寫一個呼叫servlet的事件(可以利用ajax),然後利用
標籤的onload調用這個事件。來進行jsp頁面呼叫servlet的目的。
推薦課程:Java教學。
程式碼如下:
jsp檔案程式碼如下:
nbsp;html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <meta> <title>Insert title here</title> <script></script> <script></script> <link> <!-- 3.0 --> <link> <script></script> <!-- 2.3.2 <link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet"> <script src="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.js"></script> --> <script> function a(){ $.ajax({ url:"LoaddataServlet",//servlet文件的名称 type:"GET", success:function(e){ alert("servlet调用成功!"); } }); } </script>
servlet檔案程式碼如下:
package com.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class LoaddataServlet */ @WebServlet(urlPatterns = "/LoaddataServlet",loadOnStartup = 1) public class LoaddataServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public LoaddataServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.getWriter().append("Served at: ").append(request.getContextPath()); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
結果圖:
#
以上是jsp怎麼調用servlet的詳細內容。更多資訊請關注PHP中文網其他相關文章!