0

I'm writing a jsp file code that creates dropdown menus dynamically; the entries on the menus are dinamically inserted after a query executed in dao.QueriesDAO java class. Additionally, there is a search bar.

I want all the selected voices from the menus, plus the string inserted in the search bar, are sent to the servlet SearchServelt.java, contained in src/controller/SearchServlet.java, after the Search button it's clicked.

JSP file (in WebContent/jsp/homeView.jsp):

<%@ page language="java" contentType="text/html; charset=UTF-8"
  pageEncoding="UTF-8" import="java.util.List, java.util.Iterator" %>

<!DOCTYPE html>

<html>

    <head></head>

    <body>

        <jsp:include page="_header.jsp"></jsp:include>
        <jsp:include page="_menu.jsp"></jsp:include>

        <div style = "text-align: center">

            <form action="/Search" method="post">

            Search <input name="search"> <input type="submit" value="Search"/>

            </form>

        </div>

        <div style = "text-align: center">

            <%-- select value brand from drop-downlist --%>
            <div style = "display: inline-block">
            <%
                List<String> brands = dao.QueriesDAO.getBrands();
                Iterator<String> iterBrands = brands.iterator();
            %>
            <form name="f1" method="post" action="/Search">
                Select brand:
                <select name="brand">
                    <option value="All">All</option>
                    <%  while(iterBrands.hasNext()){ %>
                    <option><%= (String) iterBrands.next() %></option>
                     <% } %>
                </select>
            </form>
            </div>

            <%-- select value of instrument type from drop-downlist --%>
            <div style = "display: inline-block">
            <%
                List<String> instrumentTypes = dao.QueriesDAO.getInstrumentType();
                Iterator<String> iterInstrumentTypes = instrumentTypes.iterator();
            %>
            <form name="f2" method="post" action="/Search">
                Select instrument type:
                <select name="instrumentType">
                    <option value="All">All</option>
                    <%  while(iterInstrumentTypes.hasNext()){ %>
                    <option><%= (String) iterInstrumentTypes.next() %></option>
                     <% } %>
                </select>
            </form>
            </div>

            <%-- select value used from drop-downlist --%>
            <div style = "display: inline-block">
            <form name="f3" method="post" action="/Search">
                Select used status:
                <select name="used">
                    <option value="0">All</option>
                    <option value="false">Not used</option>
                    <option value="true">used</option>
                </select>
            </form>
            </div>

            <%-- select value product type from drop-downlist --%>
            <div style = "display: inline-block">
            <form name="f4" method="post" action="/Search">
                Select product type:
                <select name="productType">
                    <option value="All">All</option>
                    <option value="2">Professional product</option>
                    <option value="1">Scholastic product</option>
                    <option value="0">Classic product</option>
                </select>
            </form>
            </div>

        </div>

        <jsp:include page="_footer.jsp"></jsp:include>

    </body>

</html>

Servlet file:

package controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(urlPatterns = { "/search"})
public class SearchServlet extends HttpServlet {

    private static final long serialVersionUID = -1953084286713579746L;

    public SearchServlet() {
        super();
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 

        String searchParameters= request.getParameter("search"); 

        String brandSelected= request.getParameter("brand"); 
        String selectedInstrumentType= request.getParameter("instrumentType"); 
        String selectedUsedStatus= request.getParameter("used"); 
        String selectedProductType= request.getParameter("productType");

        System.out.println("Inserted: " + searchParameters + ", "
                            + brandSelected + ", "
                            + selectedInstrumentType + ", "
                            + selectedUsedStatus + ", "
                            + selectedProductType + ".");


    }

}

I want to be able to work with the values from the servlet and then eventually call other java methods and/or jsp files.

I don't know what is wrong, because I've seen similar questions on stackoverflow and I utilized the solution proposed.

I'll like to know what do I do of wrong and what should be a good approach to a problem like this, thank you very much.

The homeView.jsp file is called from a different servlet, HomeServlet.java. Should I use that servlet instead of a new servlet SearchServlet.java? What is better?

EDIT:

I resolved with <form action="${pageContext.request.contextPath}/search" method="get"> in the JSP page (and modified in having a single form), and accordingly I changed the SearchServlet.java method from doPost to doGet.

Pleasant94
  • 471
  • 2
  • 8
  • 21

1 Answers1

0

You need to add a form to the search input

    Search <input name="search"> <input type="submit" name="submit" value="Search"/>

When the user clicks on the search button, it gets submitted to the post request of the servlet "SearchServlet". There you get the "search" parameter name which will contain the input from the user.

    <form action="SearchServlet" method="post">

            Search <input name="search"> 
            <input type="submit" value="Search"/>

// here you can add other inputs like brand selected, instrumentType, productType etc...

    </form>

Then from the servlet you query the database with the user input and set the results.

   protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 

        String brandSelected= request.getParameter("search"); 
        //if you add more options in the form you can get those also

       //query database and get arraylist of instrumentTypes by brand. 
       List<String> instrumentTypes = dao.QueriesDAO.getInstrumentType(brandSelected);


        //set attribute for jsp
        request.setAttribute("instrumentTypes", instrumentTypes);

       //add the name of the jsp file you want to view the attribute you just set
      RequestDispatcher rd = request.getRequestDispatcher("searchview.jsp");
        rd.forward(request, response);


    }

}

to view the attribute in JSP, do:

${instrumentTypes}
Jonathan Laliberte
  • 2,672
  • 4
  • 19
  • 44
  • To do this asynchronously (without a page refresh) i suggest you first learn how to do this synchronously (with page refresh), because judging by the code and question, that's something you need to learn how to do first. – Jonathan Laliberte Aug 22 '17 at 18:56
  • I have updated the question and the code; should I use the same servlet that calls the jsp file for the response? Is this a better approach? How do I get the values in the servlet after the button is selected? For now, that code doesn't seems to work; when I click the Search button, error 404 appears. – Pleasant94 Aug 24 '17 at 08:33
  • It's up to you. It's good practice to separate the logic though. If you have a search view page with options that the user selects from, it would be more organized to then have a results view page that the Servlet will forward the request attributes to. You get the values from the servlet after a form is submitted by doing: ' String search = request.getParameter("search"); ' It gets the 'name' parameter from the input fields in your form. The inputs you want to get must be within the form. 404 happens because your servlet is mapped on @WebServlet(urlPatterns = { "/search"}) – Jonathan Laliberte Aug 24 '17 at 15:39
  • If my answer is helping you, please accept it as the answer (with the tick button). Let me know if you need to know anything else. – Jonathan Laliberte Aug 24 '17 at 15:40
  • I don't know why, but still it shows error 404; I used
    , and even in web.xml file the servlet is set.
    – Pleasant94 Aug 25 '17 at 15:25
  • what is the url before you submit? @Pleasant94 – Jonathan Laliberte Aug 25 '17 at 15:55
  • I tried without setting `@WebServlet(urlPatterns = { "/search"})`, with /search and /Search. None of them works. In web.xml the servlet `SearchServlet` is set with the url /search, still doesn't work. – Pleasant94 Aug 26 '17 at 16:16
  • 1
    url mapping for a servlet only applies to GET requests. If it's not a GET request, you must use the name of the Servlet to post. Try changing your code to a get request instead: – Jonathan Laliberte Aug 26 '17 at 16:26
  • 1
    Thank you very much for all the help! I opted for the GET request, I think it's better for a query that doesn't need security nor privacy. I resolved the problem with `
    `; apparently, the error was that pressing the search button, the browser was addressing to `localhost:8080/search` instead of `localhost:8080/websiteURL/search`. I don't know why I had to explicitly add the address tough.
    – Pleasant94 Aug 28 '17 at 08:41
  • interesting, yeah that's very weird. Maybe it has something to do with your setup, normally that is not required. Glad you finally found the solution in the end. Mark my post as an answer with the 'tick' if it helped you. Have a nice day. – Jonathan Laliberte Aug 28 '17 at 08:51