获取servlet属性而不加载当前的jsp页面
在我的servlet上我有这段代码:
on my servlet I have this code :
processRequest(...,...){
String page = "";
if(true){
String str = "hello";
request.setAttribute("str",str);
page = "currentPage#";
}
else{
page = "otherPage";
}
RequestDispatcher rd = requestDispatcher("/",page);
}
在我的JSP上,为了获取servlet属性,我用这个:
on my JSP, to get the servlet attribute,I use this :
<input type = "text" value = "<c out>${str}</c out>">
这会发生什么,
当我使用 currentPage#
当前页面无法加载,但输入
标记的值始终为 null
,
when I use currentPage#
the current page do not load, but input
tag always have a value of null
,
但如果我使用 currentPage
(没有#),我得到页面加载的hello值,我不希望这样,因为页面及其内容将刷新。
but if I used currentPage
(without the #), I get the "hello" value the page loads,which i do not want to happen because the page and it contents will refresh.
有人可以帮我拿到 str属性
而无需加载当前页面或有什么办法吗?
Can somebody help me to get str attribute
without loading the currentpage or is there any way?
使用jQuery,您可以通过jQuery.ajax()完成此操作;
假设你有一个文本输入:
use jQuery and you could simply get this done via jQuery.ajax(); Let's say you have a text input:
<input type="text" id="search">
从您的Servlet中,返回您需要的字符串:
From your Servlet, return your required String:
String empName = "Test Coder";
PrintWriter out = response.getWriter();
out.println(empName);
你可以像这样调用你的onClick函数:
and you can call your onClick function like this:
$("#search").on("click", function() {
$.ajax({
type: "POST",
url: "YOUR SERVLET NAME",
data: "{empid: " + empid + "}", // what ever the data you need to pass to server to generate yout "String"
success: function(result) {
alert(result.empName); // this should be your String parameter returned from the Servlet.
$("search").val(str); // setting the String value on your text input
console.log(result);
},
error: function(error) {
console.log("error" + error);
}
});
});
这只是一个示例,我没试过..希望这会给你一条明确的道路来实现你的目标..!试着告诉我们。
This is just a sample, I did not try it.. hope this will give you a clear path to achieve your target..! try and let us know.