如何从servlet类到java类获取变量

时间:2017-01-31 05:32:50

标签: java servlets

我有servlet类我需要从servlet类到java类的变量 怎么样

<script>  
 function showCoords(event) {     
        var x = event.clientX;
        var y = event.clientY;
        var coords = "X coords: " + x + ", Y coords: " + y;
        document.getElementById("demo").innerHTML = coords;      
 }
 </script>
 <form name="Coordinates" method="post" action="loginServlet1">
 
<input type="image"  src="graph2.jpg" onclick="showCoords(event)" height="800" width="600"></input>
<p><strong>Tip:</strong>
</p>
<p id="demo"></p>
</form>
</body>
</html>

@WebServlet("/loginServlet1")
public class LoginServlet1 extends HttpServlet {

  public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    // read form fields
    String width = request.getParameter("x");
    String heigth = request.getParameter("y");

    // System.out.println("Width: " + x);
    // System.out.println("Height: " + y);

    // do some processing here...

    // get response writer
    PrintWriter writer = response.getWriter();

    // build HTML code
    String htmlRespone = "<html>";
    htmlRespone += "<h2>Your Widthis: " + width + "<br/>";
    htmlRespone += "Your Height is: " + heigth + "</h2>";
    htmlRespone += "</html>";

    // return response
    writer.println(htmlRespone);

}

1 个答案:

答案 0 :(得分:0)

  • showCoords(event)中使用javascript或jquery添加变量 返回表单作为隐藏输入,然后使用普通的HTML提交按钮

  • in showCoords(event)使用jquery执行带有必要数据的表单提交