将Java值发送到网页

时间:2014-02-01 08:26:20

标签: java string variables int

我的Java代码中有2个变量。 我的代码如下所示:

String user = "Example";
int score = "100"

现在我想要的是将这些发送到网页。 看起来像这样:

<table>
   <tr>
      <td>user</td>
      <td>score</td>
   </tr>
</table>

我将如何继续这个?

请原谅我的英语不足,如果你能提供帮助,那就太好了。

2 个答案:

答案 0 :(得分:4)

在Servlet类中:

public class TestServlet extends HttpServlet {
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      doPost(request, response);
  }

  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      String user = "Example";
      int score = 100;

      //Set your attribute in your request scope
      request.setAttribute("user", user);
      request.setAttribute("score", score);

      //Set your attribute in your Session scope
      //request.getSession().setAttribute("user", user);
      //request.getSession().setAttribute("score", score);



    //Other Stuffs
  }

}
在你的jsp页面中你可以用两种方式获取你的值:1-Scriplet 2-JSTL

<table>
    <tr>
        <td>user</td>
        <td>score</td>
    </tr>

    <tr>
        <td><%=request.getAttribute("user")%></td>
        <td><%=request.getAttribute("score")%></td>
    </tr>

    <!-- IF YOU HAVE JSTL NAMESPACE ENABLED YOU CAN FETCH IT LIKE THIS -->
    <%--  
    <tr>
        <td>${user}</td>
        <td>${score}</td>
    </tr>
    --%>
</table>

要在JSP中启用JSTL,您应该首先将JSTL库添加到项目中,然后在JSP页面的顶部添加此命名空间:

  

&LT; %@ taglib uri =“http://java.sun.com/jsp/jstl/core”prefix =“c”%&gt;

祝你好运!

答案 1 :(得分:2)

假设您正在使用servlet,可以使用request参数传递值

发送数据

  request.setAttribute("user ","Example");
  request.setAttribute("score ", 100);

接收数据

  request.getAttribute("user");
  request.getAttribute("score");