如何在Servlet doPOst上使用JSP?

时间:2014-04-09 13:47:04

标签: java jsp servlets

我刚刚开始使用JSP和Servlet,我正在尝试为设备制作控制器。一个带4个按钮的简单页面。每次单击其中一个按钮时,用户应该看到显示的内容(根据按下的按钮)。我试图通过使用Servlet和JSP来做到这一点。我不确定这是不是一个好方法,但问题是我做得不好,因为当我运行我的应用程序时,我可以看到4个按钮,但点击它们没有任何反应。我做错了什么?我希望对另一种方法提出一些建议。

MainServlet

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 CheckTemperature
 */
@WebServlet("/CheckTemperature")
public class MainServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;


    /**
     * @see HttpServlet#HttpServlet()
     */
    public MainServlet() {
        super();      
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<html>");
        out.println("<head><title>Check tempetaure</title></head>");
        out.println("<body>");
        out.println("<input type=\"submit\" value=\"Check temperature\" name=\"button\"/>");
        out.println("<input type=\"submit\" value=\"Get AC state\" name=\"button\"/>");
        out.println("<input type=\"submit\" value=\"Turn ON AC\" name=\"button\"/>");
        out.println("<input type=\"submit\" value=\"Turn OFF AC\" name=\"button\"/>");
        out.println("</body>");
        out.println("</html>");     
    }
    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        String button = request.getParameter("button");
        if(button.equalsIgnoreCase("Check temperature")){
            request.getRequestDispatcher("/WEB-INF/jsps/checkTemperature.jsp").include(request, response);
        } else if(button.equalsIgnoreCase("Get AC state")){
            request.getRequestDispatcher("/WEB-INF/jsps/acState.jsp").include(request, response);
        } else if(button.equalsIgnoreCase("Turn ON AC")){
            request.getRequestDispatcher("/WEB-INF/jsps/turnOn.jsp").include(request, response);
        } else if(button.equalsIgnoreCase("Turn OFF AC")){
            request.getRequestDispatcher("/WEB-INF/jsps/turnOff.jsp").include(request, response);
        }           
    }    
}

的web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>ArduinoController</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <description></description>
    <display-name>ACController</display-name>
    <servlet-name>MainServlet</servlet-name>
    <servlet-class>ro.dnad.controller.MainServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>MainServlet</servlet-name>
    <url-pattern>/main</url-pattern>
  </servlet-mapping>
</web-app>

checkTemperature.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ page import="ro.dnad.controller.EthernetACDriver" %>

<%EthernetACDriver driver = new EthernetACDriver("localhost",8080); %>
<%double temp = driver.getTemperature() * 5; %>
<%=temp%>

acState.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ page import="ro.dnad.controller.EthernetACDriver" %>

<%EthernetACDriver driver = new EthernetACDriver("localhost",8080); %>
<%=driver.ACStatus()%>

turnOff.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ page import="ro.dnad.controller.EthernetACDriver" %>

<%EthernetACDriver driver = new EthernetACDriver("localhost",8080); %>
<%driver.sendMessage(3); %>
<%=driver.ACStatus()%>

turnOfn.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ page import="ro.dnad.controller.EthernetACDriver" %>

<%EthernetACDriver driver = new EthernetACDriver("localhost",8080); %>
<%driver.sendMessage(2); %>
<%=driver.ACStatus()%>

2 个答案:

答案 0 :(得分:1)

  • 首先,您应该使用JSP
  • 而不是使用servlet来创建动态内容
  • 要使用您的代码,您需要在表单中添加每个提交。然后只有提交按钮才能工作。

代码示例:

 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<html>");
        out.println("<head><title>Check tempetaure</title></head>");
        out.println("<body>");
        out.println("<form action='CheckTemperature' method='post'>");

        out.println("<input type=\"submit\" value=\"Check temperature\" name=\"button\"/>");
        out.println("<form />");
        out.println("<input type=\"submit\" value=\"Get AC state\" name=\"button\"/>");
        out.println("<input type=\"submit\" value=\"Turn ON AC\" name=\"button\"/>");
        out.println("<input type=\"submit\" value=\"Turn OFF AC\" name=\"button\"/>");
        out.println("</body>");
        out.println("</html>");     
    }

答案 1 :(得分:0)

  

当我运行我的应用程序时,我可以看到4个按钮,但点击它们   没有任何反应

因为你没有提供任何动作来执行,也没有按钮在表格内。

此外,您已将您的Servlet映射两次:

  1. 使用@WebServlet("/CheckTemperature")
  2. 并在web.xml中使用url-pattern,选择一个。
  3. 你以旧的方式学习,即

    • 避免scriptlets(<% %>, <%= %>)使用JSTL或其他标记库。

    • 不是在jsp中编写Java代码,而是使用Model/Service类来保持业务逻辑与视图分离。然后你可以轻松调试你的代码,而不是在jsp。

    • 没有硬编码在servlet中生成html代码。而是通过将HTML/jsp值设为form url-pattern,方法类型为action来创建静态Servlet页面。GET/POST,然后填写详细信息后提交from,然后在servlet中处理表单,最后将响应转发到jsp/html页面。


    解决方案:

    的Servlet

    /**
    * Servlet implementation class CheckTemperature
    */
    @WebServlet("/CheckTemperature")
    public class MainServlet extends HttpServlet {
        private static final long serialVersionUID = 1L;
    
      /**
       * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
       */
      protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
          PrintWriter out = response.getWriter();
          String button = request.getParameter("button");
    
          EthernetACDriver driver = new EthernetACDriver("localhost",8080);
    
          if(button.equalsIgnoreCase("Check temperature")){
             double temp = driver.getTemperature() * 5;
             request.setAttribute("temp", temp);// add temperature value to request
             RequestDispatcher dispatcher =
                     request.getRequestDispatcher("/WEB-INF/jsps/checkTemperature.jsp");
             dispatcher.forward(request,response);
          } else if(button.equalsIgnoreCase("Get AC state")){
             request.setAttribute("acStatus", driver.ACStatus()); // add AC status value to request
             RequestDispatcher dispatcher =
                     request.getRequestDispatcher("/WEB-INF/jsps/acState.jsp");          
             dispatcher.forward(request,response);
          } else if(button.equalsIgnoreCase("Turn ON AC")){
             driver.sendMessage(3);
             request.setAttribute("acTurnOnMsg", driver.ACStatus());// add AC turn on status value to request        
             RequestDispatcher dispatcher =
                     request.getRequestDispatcher("/WEB-INF/jsps/turnOn.jsp");                
             dispatcher.forward(request,response);
          } else if(button.equalsIgnoreCase("Turn OFF AC")){
             driver.sendMessage(3);
             request.setAttribute("acTurnOffMsg", driver.ACStatus()); //AC turn off status value to request
             RequestDispatcher dispatcher =
                     request.getRequestDispatcher("/WEB-INF/jsps/turnOff.jsp");      
             dispatcher.forward(request,response);
          }           
      }    
    }
    

    并在JSP中使用表达式: 添加

    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
    

    在jsp的顶部。

    然后

    checkTemperature.jsp:

    ${temp} //从请求中获取温度值。

    acState.jsp:

    ${acStatus} //从请求中获取AC状态值

    turnOff.jsp:

    ${acTurnOnMsg} //从请求中获取AC启用状态值

    turnOfn.jsp:

    ${acTurnOffMsg} //从请求中获取AC启用状态值

    修改 JSP:

    <c:url value="/CheckTemperature" var="postUrl"/>
    <form action="${postUrl}" method="POST">
        <input type="submit" value="Check temperature" name="button"/>
        <input type="submit" value="Get AC state" name="button"/>
        <input type="submit" value="Turn ON AC" name="button"/>
        <input type="submit" value="Turn OFF AC" name="button"/>
    </form>
    

    get JSTL here