如何将值从servlet传递到html页面

时间:2014-09-25 18:13:58

标签: java jsp servlets

我正在使用servlet(v3.0)和jetty v9开发Web服务器。我必须提供HTML页面,但在此之前,我需要修改页面上几个元素的CSS内联样式,具体取决于布尔变量的值。

我已经看了很多年的JSP教程和示例,我不觉得我更接近于搞清楚它。为了简化它,我正在尝试这样做:

page.jsp :(在/ WAR / html中)

<html>
    <head>My Page</head>
    <body>
        <p <% style="display:none" if variable is true %>></p>
    </body>
</html>

GetPage.java:

public class GetPage extends HttpServlet {
    public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        boolean decision = getDecision();
        // get the JSP page and process the JSP with the boolean variable...
        resp.setContentType("text/html");
        resp.getWriter().print(???);
    }
}

我已经使用Java多年但以前从未使用过JSP。我原以为这是JSP 101,但我不明白它是如何工作的。另外,我的真实用例与上面的例子并不太远。为此目的,JSP是否过度,如果有,是否有更好的选择?

2 个答案:

答案 0 :(得分:4)

如果没有JSP,您只需从servlet中编写html,如下所示:

 response.setContentType("text/html");  
 PrintWriter out = response.getWriter();  
 out.println("<html>");
 out.println("<body>");
 if(yourcondition){
   <p style="display:none;"></p>
 }else{
   <p></p>
 }
 out.println("</body>");
 out.println("</html>");

或者使用Jquery Ajax(没有jsp),您可以向servlet发送ajax请求并从servlet获取响应。这样,您就不需要将您的html页面编写在servlet中,如上所示。

HTML:

public void doGet(HttpServletRequest req, HttpServletResponse resp) 
  throws IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    out.println("yourvalue");
 }

<script>
 $(document).ready(function(){
    //sends ajax get request
    $.get( "myServlet", function( data ) {
        //Do your logic with the response
        if(data == "myvalue"){
            $("p").css("display", "none");
         }
    });
 });
</script>

使用jsp:

<强>的Servlet

public void doGet(HttpServletRequest req, HttpServletResponse resp) 
  throws IOException {
    request.setAttribute("myvalue",val);
    RequestDispatcher rd = sc.getRequestDispatcher("mypage.jsp");
    rd.forward(req, res);
 }

<强> JSP

<p <c:if test="${your condition}">style="display: none;"</c:if>></p>

OR

<p style="display: ${ var == 'myvalue' ? 'none': 'block'};"></p>

<强> Jquery的

 var myVal= '${val}'

 if(myVal == "none"){
    $("p").css("display", "none");
 }

答案 1 :(得分:2)

的Servlet

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    request.setAttribute("attrib", true);
    request.getRequestDispatcher("/page.jsp").include(request, response);
}

JSP

${ attrib ? 'none': 'block'}