怎么在一个servlet中实现多个功能 ?如何使一个Servlet处理多个请求?



就是一个登陆和注册用同一个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 register(HttpServletRequest request, HttpServletResponse response)  throws ServletException, IOException
    {

        //这里写有关注册的代码
}
    
}

猜你喜欢

转载自blog.csdn.net/qq_36957587/article/details/80213867