I am trying to create a servlet that displays a simple form with checkboxes , when the user selects the number of checkboxes he wants and clicks on a "confirm" the POST request in my servlet checks for which boxes have been checked and queries the database based .
I am unsure on how to do this in Java as the user may select either 1 or more checkboxes . if somebody could explain this with a small example this would be great.
I am very new to programming and would provide a code snippet if I knew how to do it .
<%# page language="java"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>JSP Multiple Checkbox</title>
</head>
<body>
<form name="form1" onsubmit="checkBoxValidation()">
<h3>Select your favorite Fruits</h3>
<p><input type="checkbox" name="fruit" value="Mango"/>Mango</p>
<p><input type="checkbox" name="fruit" value="Apple"/>Apple</p>
<p><input type="checkbox" name="fruit" value="Grapes"/>Grapes</p>
<p><input type="checkbox" name="fruit" value="Papaya"/>Papaya</p>
<p><input type="checkbox" name="fruit" value="Lychee"/>Lychee</p>
<p><input type="checkbox" name="fruit" value="Pineapple"/>Pineapple</p>
<p><input type="submit" value="submit"/>
</form>
<%String fruits[]= request.getParameterValues("fruit");
if(fruits != null){%>
<h4>I likes fruit/s mostly</h4>
<ul><%for(int i=0; i<fruits.length; i++){%>
<li><%=fruits[i]%></li><%}%>
</ul><%}%>
</body>
</html>
Run this sample jsp on your web container to get some basic idea on how it works. You need to move the display logic on this page that gets request parameter into your servlet code on form submission. This example can be found from here. Hope this would help.
This is actually the HTML form behavior question. When you check a few checkboxes with one "name" attribute and different "value" attributes and press submit button, your browser will send request to the server with checked checkbox values. So you can get value names from this url parameters.
For example:
<form name="input" action="html_form_action.asp" method="get">
<input type="checkbox" name="vehicle" value="Bike">I have a bike<br>
<input type="checkbox" name="vehicle" value="Car">I have a car
<br><br>
<input type="submit" value="Submit">
</form>
If you check both of checkboxes your server will receive this parameters like so:
http://example.com/your_page.jsp?vehicle=Bike&vehicle=Car
After that you can get values like this:
String checkboxValues = request.getParameter("vehicle");
checkboxValues gets all values separated by comma.
In your servlet you would use getParameter() like so:
request.getParameter( "id_of_checkbox" )
That function returns null if the the box is not checked. So you could do something like:
boolean myCheckBox = request.getParameter( "id_of_checkbox" ) != null;
Now myCheckBox is true if checked, false if not checked.
This one might be neater if you just want the output. Assuming you're using jstl libraries, which I prefer because it makes your pages cleaner:
<c:forEach var='fruitValue' items='${paramValues.fruit}'>
${fruitValue} <br>
</c:forEach>
Related
I'm making a form to add events to a list but I need to be able to see in that form the previous events from that list. I have a jsp that shows a list of events but it takes an attribute usually added by the controller when you access the list directly from the browser.
So how can I add the list jsp filling that attribute so it shows a list and not just the headers?
I have alreay included the jsp using
<jsp:include page="comp_list.jsp"></jsp:include>
And it shows the headers but as there is no attribute it shows no list. I tried adding attributes to the include like:
<jsp:include page="comp_list.jsp">
<jsp:attribute name="compensaciones">
${compensaciones}
</jsp:attribute>
</jsp:include>
But when I do it it shows an error telling me that this cannot be done.
Also tried params but that would not be the answer for me because params are treated in the controller and not in the jsp itself.
I'm just getting the header of the list which is fine, but i would like to see the list.
Edit: this is how i build the list in case you are wondering
<tbody>
<c:forEach var="comp" items="${compensaciones}">
<td>${comp.getSomething()}</td>
...
</c:forEach>
</tbody>
<jsp:include page="pagename.jsp" />
i thing you are not provide extension in your include tag
Sometimes since I've had prior experience back in the days with HTML and PHP, we simply just would include things like navigation and header for easier management.
I'm unsure for what purpose you're including JSP, but here's an example of how I've done it since I include JSP if a boolean is true.
The site that is accessed:
<div class="row">
<div class="col-lg-2">
</div>
<div class="col-lg-8">
<%
if (loggedin) {
%>
<%# include file="includes/profile.jsp" %>
<% } else {
out.println("<div><h2>You aren't logged in!</h2></div>");
}
%>
</div>
<div class="col-lg-2">
</div>
</div>
And the top and bottom of the JSP file I'm including doesn't contain things like head, title, html, body etc.
<%
User currUser = null;
currUser = (User) session.getAttribute("user");
%>
<div>
<h2>Du er logget ind, velkommen <% out.println(currUser.getUsername().toUpperCase()); %></h2> <br>
<h5>Din Saldo: <b><% if (currUser.getBalance() < 0) { out.println("<font color='red'>" + currUser.getBalance() + "</font>");} else { out.println("<font color='green'>" + currUser.getBalance() + "</font>");} %></b></h5>
<br>
<form class="form" method="post" action="#">
<h4>Oplysninger: </h4>
<h6>
For at ændre oplysninger skal du indtaste dit kodeord!
</h6>
Nuværende Kode: <input type="password" class="form-control" placeholder="kodeord" name="password" required>
<hr>
Email: <input type="text" class="form-control" value="<% out.println(currUser.getEmail()); %>" name="email"> <br>
Brugernavn: <input type="text" class="form-control" value="<% out.println(currUser.getUsername()); %>" name="username"> <br>
<input type="submit" class="btn btn-default" value="Indsend Oplysninger" />
</form>
</div>
When importing JSP into JSP, it's important to know that they will conflict if 1. Duplicate Local Variables. 2. Certain HTML tags aren't correct.
Your intended use seems very complicated to me since I'm not quite understanding it, sorry :3 but if you can't get it working consider to throw it to a session and if it's a one time use then remove it once you used it.
This is working from dacades
<%# include file="../scripts/standard_head_declaration.jsp" %>
I have a form has many divs and actions to a servlet to check whether user makes right or wrong every questions. Each div is a multiple choice question created by java code.
jsp file
<form id="doExam" name="doExam" action="CheckAnswer" method="POST">
<% for (int i = 0; i < NumofQuestions; i++) {
Question q = (Question) exam.get(i); %>
<div id="question">
<p> <b>Question <%=i+1%>:</b> <%=q.getContent()%></p>
<p> <b>A.</b> <input type="radio" name="<%=q.getId()%>" value="A"> <%=q.getAnswerA()%> </p>
<p> <b>B.</b> <input type="radio" name="<%=q.getId()%>" value="B"> <%=q.getAnswerB()%> </p>
<p> <b>C.</b> <input type="radio" name="<%=q.getId()%>" value="C"> <%=q.getAnswerC()%> </p>
<p> <b>D.</b> <input type="radio" name="<%=q.getId()%>" value="D"> <%=q.getAnswerD()%> </p>
</div>
<%
String selected = request.getParameter(q.getId()); // ****** //
list_answer.add(selected);
}
session.setAttribute("user_answer", list_answer); %>
<input type="submit" value="Finish Exam">
</form>
The variable selected (at the line has comment) always got null. So that all of the list_answer items are null too. Are there any ways to get the selected radio button of the question div?
What you are trying to achieve is that selecting a radio button and setting the value of it to String selected in the same jsp/Servlet file.
This is impossible using request.getParameter(q.getId()), since a HttpServletRequest is created once you submit the form.
After form submission, the request parameters will be set to request object and it is accessible to your action servlet/jsp CheckAnswer. That's why you are always getting nullin the current page.
One of the solution to set radio button value to session object can be done using javaScript.
Check this article Pass variables from client side to server side
I am sending a request to the servlet it returning some data from db am constructing table and check box with the resulted data in, servlet itself using out.println and now i need to do select the data for further manipulation using check box and now i dono how to get a value of selected text boxes.
here is my servlet code,
ps=connection.prepareStatement("select t.tc_name,s.scenario_name,t.scenario_id from testcase t, scenario s where t.scenario_id=s.scenario_id;");
ResultSet rs=ps.executeQuery();
out.println("<table>");
/*out.println(executionValues.append("<tr><td>").append("Test Case Name :").append("</td><td>").append("Scenario Name :").append("</td></tr>"));*/
while(rs.next()){
out.println("<li class='panel' value='"+rs.getInt("scenario_id")+"'><b>Scenario Name:</b>"+rs.getString("scenario_name")+"</li><b>Test Case Name:</b>"+rs.getString("tc_name")+"<input type=\"checkbox\" name=\"checkbox\"></li>");
}
you should remove the ;
your sql query:
("select t.tc_name,s.scenario_name,t.scenario_id from testcase t, scenario s where t.scenario_id=s.scenario_id;");
you should change like:
("select t.tc_name,s.scenario_name,t.scenario_id from testcase t, scenario s where t.scenario_id=s.scenario_id");
You're printing a whole new <html> and <form> around every single checkbox. Your HTML ends up in browser like as:
<html>
<head></head>
<body>
<html><body><form><input type="checkbox"></form></body></html>
<form><input type="submit"></form>
</body>
</html>
This is syntactically invalid HTML. You need to rewrite your code so that all checkboxes and the submit button ends up in the same form:
<html>
<head></head>
<body>
<form>
<input type="checkbox">
<input type="submit">
</form>
</body>
</html>
Then you also don't need those ugly JavaScript workarounds. You just give the checkboxes the same name, but a different value. This way you can just grab the checked values by HttpServletRequest#getParameterValues().
String[] users = request.getParameterValues("user");
For example:
<form name="input" action="html_form_action" method="get">
<input type="checkbox" name="vehicle" value="Bike">I have a bike<br>
<input type="checkbox" name="vehicle" value="Car">I have a car
<br><br>
<input type="submit" value="Submit">
</form>
If you check both of checkboxes your server will receive this parameters like so:
http://sitename.com/your_page.jsp?vehicle=Bike&vehicle=Car
After that you can get values like this:
String checkboxValues = request.getParameter("vehicle");
checkboxValues gets all values separated by comma.
Refer this link:
http://theopentutorials.com/examples/java-ee/servlet/getting-checkbox-values-from-html-form-in-servlet/
Dear suganth It is not appropriate now to put html code in servlet. Instead you use jsp pages.
but if you have to do in this way then You may provide
if(conditionMatch){
// code for checked box
}
else{
// code for unchecked box
}
Hope this helps
Good Morning all. I have an issue that I am trying to solve but I am stuck, partially due to me not having a full understanding of JSP/ Java platform, and not having a full understanding of what/ how to implement my code in the right way. I do have an ASP background, so I am a bit familiar with some concepts.
The issue I am running into is: I am trying to populate a dynamic label and text box to appear on a webpage (JSP). I have successfully been able to populate the textboxes with a piece of JavaScript code, however, when I submit the form (on Postback) my dynamic controls are gone but all of my static controls are still present. I need to find a way to keep my information in the dynamic control on submit as well. The form does not submit when I have errors but when the form finish rendering all information and dynamic text are all lost.
My Solution: I have decided to use hidden fields to hold this information but I am unable to fire off the hidden fields after form submit: Please have a look below
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<script type="text/javascript">
function validateForm(){
var x=document.forms["myForm"]["fname"].value;
if (x==null || x=="" && document.getElementById('two').value==1){
alert("EMPTY");
document.getElementById('text').style.display = "block";
return false;
}else{
document.myform.submit();
}
}
function display(el) {
if (el.value == "two") {
document.getElementById('text').style.display = "block";
}else {
document.getElementById('text').style.display = "none";
document.getElementById('dynbox').value = '';
}
}
</script>
</head>
<body>
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">
<label >First Name</label> <input type="text"/>
<div>
<input type="radio" name="radio1" id="one" value="one" onchange="display(this);"/>Eligible
</div>
<div>
<input type="radio" name="radio2" id="two" value="two" onchange="display(this);"/>Not Eligible
</div>
<div id="text" class="glassy" name="mytext" style="display:none;">Other: <input type="text" id="dynbox"/>
</div>
<div>
<input type="hidden" name="mytext" value="${mytext}" />
<br></br>
<input type="submit" onclick="validateForm()" value="Submit"/>
</div>
</form>
</body>
</html>
What I am trying to do is select the "Not Eligible" option and type some text in the text box 'mytext' then press submit. Once I press submit, and if the First Name textbox is not filled in, then I want to trigger my hidden textbox so that I won't loose my information in my dynamically created textbox.
I hope this makes sense. I am not sure of how to do in JSP. Can someone give guidance on how to get my expected results? Keeping dynamic controls after Postback?
Thanks in advance.
One thing first: don't let the names Java and Java-Script confuse you. They have (almost) nothing in common. What you are using here is Java-Script only (no Java, no JSP anywhere).
Anyway, I think it is the condition in your validateForm() function that does not work.
I tested it a little bit and it works with these changes:
your form
<form name="myForm" action="test.html" method="get" onsubmit="return validateForm();">
<label >First Name</label> <input type="text" id="firstName"/>
<div>
<input type="radio" name="radio1" id="one" value="one" onchange="display(this);"/>Eligible
</div>
<div>
<input type="radio" name="radio2" id="two" value="two" onchange="display(this);"/>Not Eligible
</div>
<div id="text" class="glassy" name="mytext" style="display:none;">Other: <input type="text" id="dynbox"/>
</div>
<div>
<input type="hidden" name="mytext" value="${mytext}" />
<br></br>
<input type="submit" value="Submit"/>
</div>
</form>
I simply changed the first input and gave it an ID (since I couldn't find the id 'fname' anywhere), so we can access it with JavaScript.
The next thing is your submit button. You had an additional onclick="validateForm()"; there – which indeed calls the validateForm function but does not listen to the returned value (it executes the function.. nothing more). So the onsubmit="return validateForm()" is enough.
your validate function
function validateForm() {
var x = document.getElementById('firstName').value;
if ((x == null || x == "")) {
alert("EMPTY");
// document.getElementById('text').style.display = "block";
return false;
} else {
return true;
}
}
x can now be retrieved by the element's id (which I find easier).. Anyway, the if condition was one of the problems. In your form you set the value of your radio button 'two' to two. But in the if condition you ask if could be 1... which (in my understanding) should never happen. I just removed it to show you that your function works like this. If you want to check the state of the second radio button, you can test it like this:
if(document.getElementById('two').checked == true)
or even better
if(document.getElementById('two').checked)
one last thing: in your else statement, you can simply return true instead of calling submit.. because here:
onsubmit="return validateForm();"
you ask your validateForm() function to give you either true and then submit or false and then stop submitting.
Oh, one last thing (it'S the last, promise): Java and Java-Script handle all && and || in the order: first ´x==null´ would be tested and then x=="" && document.getElementById('two').value==1 would be evaluated together (&& has a stronger binding than ||).. Just for your information :)
I am trying to submit the text field value and print it using the servlet. The index.jsp is my main page and I am using jsp:include to include the form which reside in another page which is login.html.
here is the code i have for login.html
<form id="f1" action="ControllerServlet" method="GET">
<p>username
<input class ="text-input" type="text" id="txtusername" />
</p>
<p>
<input type="submit" value="submit" />
</p>
the index.jsp
<div id="col3_content" class="clearfix">
<h1>H1 Heading</h1>
<jsp:include page="login.html"></jsp:include>
</div>
the controller servlet
String usrname = request.getParameter("txtusername").toString();
out.print(usrname);
The problem is this is throwing a null pointer exception. what am I doing wrong here ? any help appreciated. thanks
Please use name not id
<input class ="text-input" type="text" name="txtusername" />
The id is not used to identify the name of the input parameter. The right attribute for the parameter is name, currently you are using an input without a name. So use
<input class ="text-input" type="text" name="txtusername" id="txtusername" />
You need to define name attribute of input tag to get it in Servlet by name.
<input class ="text-input" type="text" id="txtusername" name="txtusername" />
Also make sure you are writing code in doGet or service method of servlet as you have GET as action in form tag.
Code for Login.html
<form action="ControllerServlet" method="GET">
<p>username :
<input type ="text" name="txtusername" /></p>
<p><input type="submit" value="submit" /> </p>
</form>
ControllerServlet.java
public void service(ServletRequest request, ServletResponse response)
{
String username = request.getParameter("txtusername");
PrintWriter out = response.getWriter();
out.println("User Name " + username)
I faced a similar situation, when I checked front end, the form seems to have all the value populated correctly. However, after form.submit, from server side using request.getParameter("the parameter") does not return the value populated. After tuning on the network traffic tab in browser, I see the parameter was there, but there was a typo.
Hopefully could save you some time if same thing happens to you.