有一个文本字段传递输入,并在单击使用servlets和html页面将结果导入另一个文本框

时间:2016-08-07 13:53:21

标签: java html servlets

HTML page

单击计算按钮后,我需要在答案文本字段中打印答案,稍后我将编写业务逻辑,但首先我想检查它是如何工作的,通过传递一些文本,然后单击返回一些文本的答案字段。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form name = 'calculate' action="Calculator" method ="get">
<h1>Text Based Calculator</h1>
<p>
    <label>Equation</label>
    <input type ="text" style="font-size:10pt;height:20px;width:400px;"
           id ="textEquation"/>
    <input type="submit" style="height:25px;width:200px" name="Calculate" value="Calculate"">


</p>
<lable>Answer</lable>
<input type = "text" style="font-size:10pt;height:20px;width:400px;"
       id = "textAnswer"/>
</body>
</html>


this is servlet class 

package textbasedcalculator;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/Calculator")
public class Calculator extends HttpServlet {

    private static final long serialVersionUID = 1L;

    public Calculator() {
        super();

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        String Equation = request.getParameter("textEquation");






        }
}

1 个答案:

答案 0 :(得分:0)

在输入代码中使用name="textEquation"代替id="textEquation"。然后,您可以使用getParameter()方法拦截此输入值。 在Servlet中,将此值作为请求中的属性拦截并将请求转发回jsp页面。

 String equation = request.getParameter("textEquation");
request.setAttribute("answer",equation);
request.getRequestDispatcher("nameOfJspPage.jsp").forward(request,response);

现在在转发的jsp页面中添加以下行:

<lable>Answer</lable>
<input type = "text" style="font-size:10pt;height:20px;width:400px;"
       id = "textAnswer" value="${requestScope.answer}"/>

将显示您的答案。 Note:您的视图必须是jsp页面而不是html页面。您不能将html用于动态内容。 希望这会有所帮助。