这次本想尝试用ajax来提交表单来登录,但是遇到了很多问题,下面就是相关的总结。
登录界面:
ajax提交:
第一步:ajax提交给servlet数据,进过相关的处理后
第二步:servlet后可以通过下面的方法返回msg数据给前台
String msg= "error";
response.getWriter().write(msg);
返回信息!(如果是要转跳进行第三部,否则对返回的信息做相应的处理,如本例子的弹出提示框。)
第三部:通过前台中的js来实现页面跳转(如果是放在web-inf中jsp,jsp要在web.xml中部署后,这样的url才会有效,参考:http://blog.csdn.net/wanghaiping1993/article/details/23510411中关于web-inf中jsp如何访问)
window.location.href="${pageContext.request.contextPath}/main.jsp" ;
form提交:
第一步:写好form表单后,向servlet提交信息
第二部:通过下面的语句进行重定向来实现页面跳转(这样使用,在web-inf中jsp就不用在web-inf中进行部署了)
request.getRequestDispatcher("/WEB-INF/ jsp/***.jsp").forward(request,
response);
<%@ page language = "java" import= "java.util.*"pageEncoding= "utf-8" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://" +request.getServerName()+":" +request.getServerPort()+path+ "/";
%>
<! DOCTYPE HTML PUBLIC "-//W3C//DTD
HTML 4.01 Transitional//EN">
< html>
< head>
<base href = "<%= basePath%> " >
<title >My
JSP 'login.jsp' starting page </title >
< script type= "text/javascript" src= "js/jquery-1.8.0.min.js" ></script >
<script type = "text/javascript">
function ajax_submit(){
varusername=document.getElementsByName( "username" )[0].value;
var password=document.getElementsByName( "password" )[0].value;
/* //一定要加入jquery.js
*/
$.ajax({
url: '${pageContext.request.contextPath
}/Userservlet?method=login',
type: 'post',
data: 'username=' +username+'&password=' +password,
success: function (msg)
{
if ((msg=="error" ))
{
alert( "用户名或者密码错误!!" );
} else
if ((msg=="success" ))
window.location.href="${pageContext.request.contextPath}/main.jsp" ;
}
});
}
</ script>
</ head>
< body>
< div align= "center" style ="margin : auto;" >
<%-- <form action="" method="post">
--%>
<table >
<tr > 用户名: <input type = "text" name ="username" ></ tr> <br >
<tr > 密码:< input type ="password" name= "password" ></ tr> <br >
<tr > < input type= "submit" onclick ="ajax_submit()" value ="提交" ></ tr>
</table >
</ div>
<%-- </form>
--%>
</ body>
</ html>