laura
laura

Reputation: 2135

How to use JSP on Servlet doPOst?

I just started to use JSP and Servlet and i am trying to make a controller for a device. A simple page with 4 buttons. Each time when one of the buttons is clicked, the user should see something displayed(according with the pressed button). I am trying to do that by using a Servlet and JSP. I am not sure if this is a good approach, but the problem is that i am not doing this well, because when i run my application, i can see the 4 buttons, but on click them nothing happens. What i am doing wrong? I would appreciate some suggestions for another approach.

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()%>

Upvotes: 2

Views: 9760

Answers (2)

Abhishek Nayak
Abhishek Nayak

Reputation: 3748

when i run my application, i can see the 4 buttons, but on click them nothing happens

because you have not provided any action to perform nor the buttons are inside form.

Also you have mapped your Servlet two times :

  1. using @WebServlet("/CheckTemperature")
  2. and using url-pattern in web.xml, choose one.

you learning in old way, i.e.

  • Avoid scriptlets(<% %>, <%= %>) instead use JSTL or other tag library's.

  • Instead of writing Java codes in jsp, use Model/Service class for keeping bussiness logic's separate from view. then you can easily DEBUG your code, while not in jsp.

  • don't hard code to generate html codes in servlets. instead create static HTML/jsp page .with a form by giving action value as Servlet url-pattern and method type as GET/POST, then after filling details submit the from, handle the form in servlet then, finally forward response to jsp/html page.


Solution:

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);
      }           
  }    
}

and in JSP use expression like: add

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

in top of jsp.

then

checkTemperature.jsp:

${temp} // get temperature value from request.

acState.jsp:

${acStatus} //get AC status value from request

turnOff.jsp:

${acTurnOnMsg} //get AC turn on status value from request

turnOfn.jsp:

${acTurnOffMsg} //get AC turn on status value from request

EDIT: 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

Upvotes: 0

coreJavare
coreJavare

Reputation: 1469

  • First of all rather than using servlet for creating dynamic content, you should use JSP
  • For working your code you need to add each submit but inside the form. Then only submit button will work.

Code sample:

 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>");     
    }

Upvotes: 1

Related Questions