0

I have a jsp file with a form of radiobuttons. With POST I read this form once submitted.

However, after submitting the form the answers given in the form dissapear and I would like to have them displaying.

How to do it? I've been walking round the internet and I can't seem to find a resolution.

I have been trying with req.setAttribute("q" + i, "yes"); in a loop since the values taken from this form I keep in an array.

I have also thought of JS but have no experience with it.

No success. Could you please help?I just need a hint or something to start with.

EDIT:

In my JSP (keywords.jsp) file, there is a search form:

<form method="POST" action="keywords">
                    <p>
                        Are you looking for an urgent email?
                        <label><input type="radio" name="q0" value="yes" class="q0">Yes</label>
                        <label><input type="radio" name="q0" value="no" class="q0">No</label><br/>
                    </p>
                    <p>
                    Are you looking for a business email?
                        <label><input type="radio" name="q1" value="yes" class="q1">Yes</label>
                        <label><input type="radio" name="q1" value="no"  class="q1">No</label><br/>
                    </p>
input class="btn btn-warning" type="submit" value="Search Keywords">

So when I click Submit - in doPost I get values for these radiobuttons. t page reloads and the form shows again along with the search results. After reloading, in the form, no answer is checked.

What I want is that I want to have answers in the form checked after the reload of the form. Answers that were given before reload and should be displayed after reload are in ArrayList.

I my Servlet I have:

for(int i = 0; i < keywords.getAnswersIDs().size(); i++) {
    if("1".equalsIgnoreCase(keywords.getAnswersIDs().get(i))) {
        req.setAttribute("q" + i, "checked");
        LOGGER.info(MARKER, "For element " + i + " is yes.");
    } else {
        req.setAttribute("q" + i, "no");
        LOGGER.info(MARKER, "For element " + i + " is no.");
    }
}

at the end I also have this:

RequestDispatcher dispatcher = req.getRequestDispatcher("/keywords.jsp");
        LOGGER.info(MARKER, "Dispatcher to keywords.jsp");
        try {
            dispatcher.forward(req, response);
        } catch (ServletException e) {
            LOGGER.debug(MARKER, "Caught ServletException " + e);
            e.printStackTrace();
        } catch (IOException e) {
            LOGGER.debug(MARKER, "Caught IOException " + e);
            e.printStackTrace();
        }

I hope this helps.

Karolina
  • 185
  • 1
  • 2
  • 9

1 Answers1

2

Well you set some attributes in your post handler but do not do anything in the JSP to indicate that they are selected. You would need to add some mark up to set the relevant option as being checked (perhaps by using a JSP EL expression - see references at the bottom):

Assign an initial value to radio button as checked

So:

<input type="radio" name="q1" value="yes" ${someAttributeTrue ? 'checked' :''}>

Let's make the whole thing a bit cleaner by creating some classes to hold the question data.

Note I have not compiled and run this so it may not be perfect but you get the general idea. You will need to go through the Servlet to render the initial form as well rather than hitting keywords.jsp directly.

Some Model Classes:

public class Questionnaire{
    private List<Question> questions;

    public Questionnaire(){
        questions = new ArrayList<>();
        questions.add(new Question("Are you looking for an urgent email?", false));
        questions.add(new Question("Are you looking for a business email?", true));
    }

    public List<Question> getQuestions(){
        return questions;
    }
}

public class Question{
    private String question;
    private boolean selected;

    // boolean specifies the default on initial page load
    public Question(String question, boolean selected){
        this.question = question;
        this.selected = selected;
    }

    public String getQuestion(){
        return question;
    }

    public boolean isSelected(){
        return selected;
    }
}

Servlet:

public class MyServlet extends HttpServlet{

    public void doGet(HttpServletReqest request, HttpServletResponse response){
        //set a default questionnaire for initial render of JSP
        request.setAttribute("questionnaire", new Questionnaire());

        RequestDispatcher dispatcher = req.getRequestDispatcher("/keywords.jsp");
        dispatcher.forward(request, response);
    }

    public void doPost(HttpServletReqest request, HttpServletResponse response){
        Questionniare questionnaire = new Questionnaire();

        for(int i = 0; i < questionnaire.getQuestions().size(); ++ i){
            //set selected based on incoming parameter
            boolean selected = request.getParameter("q"+i).equals("yes")
            questionnaire.getQuestions().get(i).setSelected(selected);  
        }

        //set the updated form as a request attribute for re-render of JSP
        request.setAttribute("questionnaire", questionnaire);
        RequestDispatcher dispatcher = req.getRequestDispatcher("/keywords.jsp");
        dispatcher.forward(request, response);
    }
}

The JSP:

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

<form method="POST">
    <!--Iterate all questions and render the inputs-->
    <!--On initial load should show the defaults -->
    <!--After post should show the selections!-->
    <c:forEach items="${questionnaire.questions"} var="question" varStatus="loop">
        <p>
            ${question.question}
            <label><input type="radio" name="q{loop.index}" value="yes" 
                class="q0" ${question.selected ? 'checked' : ''}/>Yes</label>
            <label><input type="radio" name="q{loop.index}" value="no" 
                class="q0" ${! question.selected ? 'checked' : ''}/>No</label>
            <br/>
        </p>
    </c:forEach>
    <input class="btn btn-warning" type="submit" value="Search Keywords"/>
</form>

References:

The Java Standard Tag Library (JSTL): http://docs.oracle.com/javaee/5/tutorial/doc/bnakc.html

JSP Expression Language (EL) http://docs.oracle.com/javaee/1.4/tutorial/doc/JSPIntro7.html

Community
  • 1
  • 1
Alan Hay
  • 22,665
  • 4
  • 56
  • 110