怎么在一個servlet中實現多個功能 ?如何使一個Servlet處理多個請求?


自學javaweb一直不知道一個servelt可以有多個功能!看了別人代碼才知道這個可以有!

平時你建立servelt時候你會吧doget和dopost這兩個勾上,要想實現多個功能,你不必要勾選doget和dopost方法只勾選service即可!此時你復寫service方法就行!

你不寫doget和dopost,寫service  ,這個servelt被調用會先執行service  ,即使你同時寫了post和get和service調用這個servelt也會先調用service方法!service不管何時就會被先調用!

下面是一個簡單的例子(簡單的過分)!!!!

就是一個登陸和注冊用同一個servelt怎么實現?

大白話 意思就是jsp頁面在寫的時候傳入一個值在servelt頁面根據傳入的值的不同調用不同的方法,selvelt 里面寫所有你想寫的方法!!!不清楚看代碼!!!小例子別指望直接運行

 

 

先說jsp代碼:

這里面有一些ajax代碼,不用關注這些細節,意思就是登陸使用了ajax發送到servelt中的(當然只要你能傳值過去就行,不管用什么),注冊按鈕使用了form表單提交,其實思路很簡單就是這兩個按鈕被點擊跳轉頁面時分別傳入了一個讓服務器知道調用哪個方法的參數,這個你隨便定義你傳1或2都行,傳過去你要分的清楚。
<html>
<head>
<script type="text/javascript" src="${pageContext.request.contextPath}/scripts/jquery-3.3.1.js"></script>
<script type="text/javascript"> function tiJiao(){ var username = $("#username").val();//獲取登錄的名字
        var password = $("#password").val();//獲取登陸的密碼
        if(username == null || username.length == 0 || password == null || password.length == 0 ){ alert("填寫不完整");//判斷是不是賬號密碼為空!
            return false;} var url="${pageContext.request.contextPath}/all";//這個地址是你要判斷用戶是否存在的后台
    var args={"method":"login","username":username,"password":password,"time":new Date()};//這個參數是把編輯框里的內容傳過去給后台了
    $.post(url,args,function(data){$("#message").html(data);});//登錄按鈕被點擊使用ajax傳值到后台傳值login } </script>
</head>
<body>
<form action="${pageContext.request.contextPath}/all?method=zhuce" method="post">//注冊按鈕被點擊使用form表單提交傳值zhuce
 <div align="center"> 賬號:<input type="text" id="username" name="username" style="width:200px; height:25px;" ><label id="message"></label></div><br>
<div align="center">密碼:<input type="password" id="password" name="password" style="width:200px; height:25px;"></div>&nbsp; <div align="center"><input type="button" value="登陸" onclick=" tiJiao()" style="width:70px; height:30px;" />
<input type="submit" value="注冊"  style="width:70px; height:30px;" />
</div> 
</form>
</body>
</html>
servelt代碼...................................................................................................................................................................................................

protected
void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub String method=request.getParameter("method");//得到傳入的值下面根據傳入的值執行不同的方法!! System.out.println("method"+method); if(method.equals("login")) { login(request, response);//執行login代碼 } else { zhuce(request, response);//執行注冊代碼 } } private void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //這里寫有關登錄的代碼 } private void zhuce(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //這里寫有關注冊的代碼 } }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM