我想在我的HTML页面上打印出我当前的变量值。我似乎无法弄清楚。在我的HTML页面上,我想打印出当前汇率。
这是我的HTML代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="US-ASCII">
<title>Calculator</title>
</head>
<body>
<form action="Converter" method="get" name="frm">
Amount:
<input name="amount" type="text" />
Rate:
<input name="conversionRate" type="text" />
<input type="submit" value="Convert!" />
<br>Current Rate:
</form>
</body>
</html>
我的Java代码
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;
/**
* Servlet implementation class Converter
*/
@WebServlet("/Converter")
public class Converter extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public Converter() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
String n2 = "1.0";
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
String n1 = request.getParameter("amount");
String tempStr;
tempStr = request.getParameter("conversionRate");
if(!tempStr.isBlank()) {
n2 = tempStr;
}
if(n2.equals("tempStr")){
out.println((Integer.parseInt(n1) / Double.parseDouble(n2)));
}
else if(n2.equals(n2)){
out.println("test");
out.println((Integer.parseInt(n1) / Double.parseDouble(n2)));
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
如何打印当前汇率。在这种情况下,HTML页面上的n2是哪个?我希望它在网站的每次加载时进行更新。但是我不知道如何通过HTML页面打印出变量值。
您可以使用您的PrintWriter实例将整个HTML打印到响应对象中,例如:
try (PrintWriter out = response.getWriter()) {
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Bla</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>");
out.println("Your current rate is: ");
//Your Java code here
String n1 = request.getParameter("amount");
String tempStr;
tempStr = request.getParameter("conversionRate");
if(!tempStr.isBlank()) {
n2 = tempStr;
}
out.println(n2);
out.println("</h1>");
out.println("</body>");
out.println("</html>");
}
希望有所帮助。