将参数传递给Servlet
当我将一个参数传递给我的servlet时,出现了一些问题。特别是我想传递下拉选择的选定项目的值。但问题是,当我单击选择的项目时,它不会发生任何事情(实际上,servlet应该调用jsp来可视化表)。此外,我怎样才能在下拉选择下可视化这个jsp?我不想打开另一扇窗:如何查看我有一个选项卡菜单(每个标签代表了一个数据库的操作,我不想打开另一个窗口,当我打电话的各种JSP)将参数传递给Servlet
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
String i = request.getParameter("choose");
PrintWriter out = response.getWriter();
if(i.equals("products")){
ArrayList<Products> list = new ArrayList<Products>();
list = bDBean.listProduct();
request.setAttribute("list", list);
String arg = "/" + this.getServletName() + ".jsp";
RequestDispatcher dispatcher = this.getServletContext().getRequestDispatcher(arg);
dispatcher.forward(request, response);
}
if(i.equals("login")){
// something
}
}
MY JSP
<script type="text/javascript">
function passingParameter(form1){
var choose = document.getElementById("choose");
var selectedValue =choose.options[choose.selectedIndex].value;
}
</script>
<div class="tab-content">
<div id="operation 1" class="tab-pane fade in active">
<h3>OPERATION 1</h3>
<div class="form-group">
<label for="scelta">Select the table you want to see:</label>
<form name=form1 action="NewServlet" method="post">
<select id="choose" class="form-control" name="choose"onchange="passingParameter(this.form)">
<option value="products">Products</option>
<option value="login">Login</option>
</select>
</form>
</div>
</div>
<div id="add" class="tab-pane fade">
<h3>OPERATION 2</h3>
</div>
<div id="OPERATION 2" class="tab-pane fade">
<h3>OPERATION 2</h3>
<p>Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam.</p>
</div>
<div id="OPERATION 3" class="tab-pane fade">
<h3>OPERATION 3</h3>
<p>Eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo.</p>
</div>
</div>
显然你是要找的是能够修改一个页面片段无需重新加载,可以用AJAX(异步JavaScript和XML)来完成整个页面。常见的方法是使用JQuery,这里是一个简单的代码,你将需要适应一点点地被集成到您的代码:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.1.0.min.js"></script>
</head>
<body>
<form>
<select id="choose" class="form-control" name="choose">
<option value="products">Products</option>
<option value="login">Login</option>
</select>
</form>
<div id="result"></div>
<script>
$("#choose").change(function(event) {
$.post("NewServlet", "choose=" + $("#choose").val(), function(data) {
$("#result").empty().append(data);
});
});
</script>
</body>
</html>
此代码:
- 加载的JQuery 3.1.0 (这段代码将与JQuery 1.x协同工作,因为它非常基本)
- 在脚本部分,它添加了一个处理程序,该程序会将select的值传递给servlet,并将响应放入其ID为result的任何时间选定的选项更改
好吧它的工作原理!但是这个电话打开另一个窗口。我想保持在同一页 – blinkettaro
这很奇怪我不明白为什么,它不应该也许它是一个导航问题? –
尝试在表单级别添加target =“_ self” –
尝试在onchange之前添加空格,如此名称=“选择”onchange –
您永远不会将表单发送到servlet(不提交按钮)。想想你要找的是ajax – Jens
@NicolasFilotto在我的代码中有一个空间。这是我在这里粘贴代码的错误 – blinkettaro