将参数传递给Servlet

时间:2016-08-02 11:15:30

标签: javascript java jsp servlets

将参数传递给servlet时遇到了一些问题。特别是我想传递下拉选择的所选项的值。但问题是,当我单击选择的项目时,它不会发生任何事情(事实上,servlet应该调用jsp来可视化表)。此外,我如何在下拉选择下可视化这个jsp?我不想打开另一个窗口:你怎么看我有一个标签菜单(每个标签代表一个数据库上的操作,当我调用各种jsp时我不想打开其他窗口)

 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
        }

        }

我的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>

1 个答案:

答案 0 :(得分:1)

您显然要寻找的是能够修改页面片段而无需重新加载整个页面,这可以通过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>

此代码:

  1. 加载JQuery 3.1.0(此代码将与JQuery 1.x一起使用,因为它非常基本)
  2. 在脚本部分中,它添加了一个处理程序,该处理程序将向您的servlet发送select的值,并将响应放入div,其id为result,只要所选选项发生更改