栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

从javascript到Java servlet的HTTP POST

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

从javascript到Java servlet的HTTP POST

我承认我的回答部分是预感(因为是我很久以前写的),但是使用JSP时,通常应将form action命名为在其中配置的servlet的名称。

web.xml

我认为您的 web.xml 应该是这样的:

<servlet>    <servlet-name>LoginServlet</servlet-name>    <servlet-class>pl..LogoutServlet</servlet-class></servlet><servlet-mapping>    <servlet-name>LoginServlet</servlet-name>    <url-pattern>/login</url-pattern></servlet-mapping>

并将您的 HTML 更改为此:

<form action="LoginServlet" method="POST"  id="loginForm">

对于Javascript部分,如果您使用jQuery提交表单,则可以修改参数以张贴和省略张贴密码(因为如果您希望将其以散列形式发送,则不需要密码),请参见以下使用代码:

Javascript(使用jQuery):

// Attach a submit handler to the form$("#loginForm").submit(function( event ) {    // Stop form from submitting normally    event.preventDefault();    // Get some values from elements on the page:    var $form = $( this );    // We want to customize what we post, therefore we format our data    var data = "login="+ $('#login').val() +"&passwordHash=" + CryptoJS.MD5($('#password').val());    // For debugging purposes... see your console:    // Prints out for example: login=myLoginName&passwordHash=a011a78a0c8d9e4f0038a5032d7668ab    console.log(data);    // The actual from POST method    $.ajax({        type: $form.attr('method'),        url:  $form.attr('action'),        data: data,        success: function (data) { console.log("Hey, we got reply form java side, with following data: "); console.log(data); // redirecting example.. if(data === "SUCCESS") {    window.location.replace("http://stackoverflow.com"); }        }    });});

最后,在Java端,您将需要

doPost()
捕获
login
passwordHash
赋值等方法。

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {    String login = request.getParameter("login");    String password = request.getParameter("passwordHash");   //   // Do what ever you want with login and passwordHash here...   //   // Because we are using ajax we need to respond to it stating whether we can redirect or not to new location, see lines below   // Content type of the response - You could also return application/json for example (which would be better in this case)   response.setContentType("text/plain"); // Using text/plain for example   response.setCharacterEncoding("UTF-8");   // Change this as you like - it can also be url or anything else you want...   response.getWriter().write("SUCCESS");}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/466561.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号