最近看到有的朋友对 servlet 传值和取值有疑惑,针对次问题在此发表下在servlet中传值和取值操作
html代码:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<
html
>
<
head
>
<
title
>东北大亨 用户校验的ajax</
title
>
<
meta
http-equiv
=
"keywords"
content
=
"keyword1,keyword2,keyword3"
>
<
meta
http-equiv
=
"description"
content
=
"this is my page"
>
<
meta
http-equiv
=
"content-type"
content
=
"text/html; charset=UTF-8"
>
<!--<link rel="stylesheet" type="text/css" href="./styles.css">-->
<
script
type
=
"text/javascript"
src
=
"jslib/jquery.js"
></
script
>
<
script
type
=
"text/javascript"
src
=
"jslib/get.js"
>
</
script
>
</
head
>
<
body
>
用户名校验的ajax实例,请输入用户名:
<
input
type
=
"text"
id
=
"userName"
/>
<
input
type
=
"button"
value
=
"校验"
onclick
=
"verify()"
/>
<
div
id
=
"result"
>
</
div
>
</
body
>
</
html
>
测试 get.js
function
setou()
{
// document.getElementsByName("userName");
// document.getElementById("userName");
// alert("userName)");
// jquery的查找节点的值的方式
var
jqueryObj = $(
"#userName"
);
var
userName = jqueryObj.val();
// alert(userName);
// 这里传的参数为:name。这里可以根据需要定义自己需要的参数变量 // 这里传什么参数变量在
testServlet
中用什么参数名称接值。
$.get(
"testServlet?name="
+userName,
null
,callback);
}
function
callback(data)
{
// alert("服务器端的数据回来了");
// alert(data);
var
resultObj = $(
"#result"
);
resultObj.html(data);
alert(
""
);
}
testServlet.java
package
cn.itcast.project;
import
javax.servlet.http.HttpServlet;
import
javax.servlet.http.HttpServletResponse;
import
javax.servlet.http.HttpServletRequest;
import
java.io.IOException;
import
java.io.PrintWriter;
import
javax.servlet.ServletException;
public
class
testServletextends
HttpServlet{
/**
*
*/
private
static
final
long
serialVersionUID = 1L;
protected
void
doGet(HttpServletRequest request,HttpServletResponse response)
throws
ServletException,IOException
{
try
{
// request.setCharacterEncoding("UTF-8");
response.setContentType(
"text/html;charset=utf-8"
);
PrintWriter out = response.getWriter();
// 取值的参数根据赋值的参数进行取值。这里的参数用的是name
String name = request.getParameter(
"name"
);
if
(name ==
null
|| name.length() ==
0
)
{
out.println(
"用户名不能为空"
);
}
else
{
if
(name.equals(
"东北大亨(northesttycoon)"
))
{
out.println(
"用户名["
+name+
"]已经存在,请使用其他账户登录"
);
}
else
{
out.println(
"用户名["
+name+
"]尚未存在,可以使用该用户登录"
);
}
}
}
catch
(Exception ex)
{
ex.printStackTrace();
}
}
protected
void
doPost(HttpServletRequest request,HttpServletResponse response)
throws
ServletException,IOException
{
doGet(request,response);
}