Java Servlet: How can I retrieve selected radio button values? - java

I have created a simple servlet in which a user will be presented with 2 questions, answering either true or false. My problem lies in retrieving the answers selected by the user.
Code:
out.println("<FORM ACTION=\"Game\" METHOD = \"POST\">" +
"<b>Question 1: Are you over the age of 25? </b><br> <br>" +
"<input type = \"radio\" name = \"Q1rad1\" onclick = \"getAnswer('a')\"> True " +
"<input type = \"radio\" name = \"Q1rad2\" onclick = \"getAnswer('b')\"> False<br>" +
"<br><br><b>Question 2: Are you from earth?</b><br> <br>" +
"<input type = \"radio\" name = \"Q2rad1\" onclick = \"getAnswer('a')\"> True " +
"<input type = \"radio\" name = \"Q2rad2\" onclick = \"getAnswer('b')\"> False<br>" +
out.println("<Center><INPUT TYPE=\"SUBMIT\"></Center>");
);
Each question has 2 radio buttons, Q1rad1 & Q2rad2, for answering True or False. How can i know the value selected by each user when the submit button is pressed.
I understand it may be more efficient when using Javascript but for the purposes of this problem I must be using servlets.

You have to define the value you want to retrieve when the radio button is selected
The value setting defines what will be submitted if checked.
The name setting tells which group of radio buttons the field belongs to. When you select one button, all other buttons in the same group are unselected.
<input type="radio" name="Q2" onclick="getAnswer('b')" value="b">
<input type="radio" name="Q2" onclick="getAnswer('a')" value="a">
In your Servlet which will recieve the request you'll have something like
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// get the value of the button group
String q2 = request.getParameter("Q2");
// compare selected value
if ("a".equals(q2)) {
...
}
...
}

You haven't named your radio buttons correctly. Each radio option for the same question need the same name attribute. Also, you should have a value attribute on each <input type="radio">. I'm not sure you need the onclick handler at all. You should also have a </form> closer tag. Your form might look like this:
out.println("<form action=\"Game\" method=\"POST\">" +
"<b>Question 1: Are you over the age of 25? </b><br> <br>" +
"<input type = \"radio\" name = \"Q1\" value=\"True\"> True " +
"<input type = \"radio\" name = \"Q1\" value=\"False\"> False<br>" +
"<br><br><b>Question 2: Are you from earth?</b><br> <br>" +
"<input type = \"radio\" name = \"Q2\" value=\"True\"> True " +
"<input type = \"radio\" name = \"Q2\" value=\"False\"> False<br>" +
"<Center><INPUT TYPE=\"SUBMIT\"></Center>" +
"</form>"
);
And then in the doPost() method of servlet that handles the form submission, you can access the values using request.getParameter(). Something like this:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String q1 = request.getParameter("Q1");
String q2 = request.getParameter("Q2");
// more processing code...
}

Give the same name to the radios of the same question, and set different values.
Look at this page.
Then in the request you will get a parameter with the name of the radio group and the value selected.
After submit the servlet the receives the post can use:
String value = request.getParameter("radioName");

For your HTML Code the below lines are enough
protected void doPost(HttpServletRequest req,HttpServletResponse res){
String q1 = request.getParameter("Q1");
String q2 = request.getParameter("Q2");`
}
For example, Considering your HTML Code.
If Q1 is pressed
"TRUE"
then it would be our "Input" in Servlet.

Related

Java Spring Boot - use dropdown selection as variable

I have a dropdown which consists of options retrieved from a method. The user should be able to select one of these options, and press a submit button. Upon pressing the submit button, the button executes a method that takes the selected option and stores it in some other variable.
My drop-down form looks like this currenty:
sb.append("<p>"
+ "<div style='height:200px;width:500px;border:1px solid #ccc;font:16px/26px Georgia, Garamond, Serif;overflow:auto;'>"
+ "<form action='/Teacher' method='get'>"
+ "<input type='submit' value='Submit' action='/sendTest' method='post'>"
+ "<input type='submit' value='Reset' action='/resetCurrentTest' method='post'>"
+ "<a>Current Test for students: " + testcont.getActiveTest() + "</a>"
+ "<fieldset><p>"
+ "<label>Select test</label>"
+ "<select id = 'selection'>"
+ currentTestOptions() // input
+ "</select></p></fieldset>"
+ "</form>"
+ "</div>"
+ "</p>");
and the method the
"<input type='submit' value='Submit' action='/sendTest' method='post'>"
button should execute is:
#PostMapping("/sendTest")
#ResponseBody
public void sendTest(#RequestParam(value = "selection") HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException{
for(Test test : testcont.showAllTests()){
if(test.getName().equals("selection")){
testcont.SetActiveTest(test);
System.out.println(testcont.getActiveTest());
}
}
}
So currently, the buttons react on the click, and "refreshes" the page. However, the method is not executed, as the field which is supposed to store the "selected" value is not updated.
I basically need the correct mapping for the method to react to the button press. Any ideas? Am I going about this the wrong way?
add 'name' attribute to your select field like name=selection
and form action='/Teacher' should be sendTest not Teacher or formaction if you want to override form destination with input

Null pointer exception in passing checkbox value

I made an index page in which you take the value of checkbox and pass it on to a file named AddToWork.java but it is showing null pointer exception. There is some problem in passing the value of the checkbox. Kindly help. Here is the code snipped for index page
<td>
<center>
<form action="addtowork?id2=<%=mail.getTempToken()%>" method="post">
<input type="submit" value="Add to my work">
<input type="checkbox" name="flag" value="flag">High Priority</form>
</center></td>
for AddToWork.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
EmailDesc mail = new EmailDesc();
String imp = new String();
imp = (String) request.getParameter("flag");
String thisid = request.getParameter("id2");
Home home = new Home();
User user = new User();
user = (User) request.getSession().getAttribute("user");
mail = home.getEmail(thisid, user);
home.givePermanentToken(mail,thisid);
if (imp.equals("flag")){
System.out.println("Priority Changed to " + mail.getPriority() + "!");
}
response.sendRedirect("index1.jsp");
}
If I remove the if statement in addtowork.java, the code runs perfectly.
it is because your "imp" Object is pointing to nothing (null) & it is throwing an exception. use "Yoda notation" like so
if("flag".equals(imp)){
// your code
}
this removes the possibility of getting a null pointer exception
Case 1: name.equals("Java") Compare unknown value with known value.
We are comparing name(unknown) value with another string Java(known) value. name will be decided based on some database call, calling another method, etc... It may possible you get null value of name and possible chances of java.lang.NullPointerException or you have to check explicitly for null value of name.
Case 2: "Java".equals(name) Compare known value with unknown value.
We are comparing Java(known) value with another string name(unknown) value. Same way name will be decided based on some database call, calling another method, etc... But equals and equalsIgnoreCase method of String will handle the null value and you don't have to check explicitly for null value of name.
In your case
/* You are getting `null` for variable `imp` */
imp = (String) request.getParameter("flag");
Change
if (imp.equals("flag")){
System.out.println("Priority Changed to " + mail.getPriority() + "!");
}
to
if ("flag".equals(imp)){
System.out.println("Priority Changed to " + mail.getPriority() + "!");
}
Case I : When you are submitting the form with checking the check box , it will work because the value is set in request parameter flag
Case II : When you are submitting the form without checking the "priority" check box then the request parameter sets to null and later you calling the equal method on null on if condition. so please use
if("flag".equals(imp))
Note :- It's bad practice to create string using new
String imp = new String(); //bad don't use this
String imp = ""; //use in this way

How to reload a JSP with request.getAttribute values

I have this application where i want to populate a text file on the basis of entries entered from user interface.
I chose Struts1 for this and i have been able to complete most of the functionalities.But the part of keeping on populating the
text file on the basis of user entries in my JSP is something i am struggling with. The following are the flow of pages on user interface
1.'Accept user entries' http://www.image-share.com/ijpg-1178-104.html
2.'Ask for scan data on the basis of entries in page1' http://www.image-share.com/ijpg-1178-105.html
3.'Submit after entering the scandata. ' http://www.image-share.com/ijpg-1178-106.html
(I have been able to straighten the null values in the images via session variables. Thanks to Dave)
message is seen with null entries like this Post validation.
My questions is:
What should be used so that there is a scenario that the users enter the Scan Data on page 2 and can continue to enter
more scan data values by falling back on the same JSP . I was thinking on the lines of reloading the page using JavaScript
on the button click. Is it the right approach?
The relevant code for this is
<html:form action="txtwriter">
<% String itemname = (String)session.getAttribute("itemname"); %>
<% String lotnumber = (String)session.getAttribute("lotnumber"); %>
<% String godownname = (String)session.getAttribute("godownname"); %>
<br/>
<% String message = (String)session.getAttribute("message");
session.setAttribute( "theFileName", message ); %>
Filename : <%= message %>
<br/> Item Name :<%= itemname %>
<br/> Lot Number :<%= lotnumber %>
<br/> Godown Name :<%= godownname %>
<br/> <bean:message key="label.scandata"/>
<html:text property="scanData" ></html:text>
<html:errors property="scanData"/>
<br/>
<html:submit/>
/* How should the submit button handle the onClick event so that when the users click
after entering the text.
1. The entered text must be populated in the text file using a different action class. (I have this part working)
2.They must be on the same jsp with the scanData text box cleared waiting for the next user entry into that text
box so that this subsequest entry can also be entered into the text file.
Is there a way i can empty the 'scanData' textbox by accessing it by name inside my action so that i can empty it from my action class?
(I am looking for this answer)
*/
I used this inside the LoginAction.java
HttpSession session = request.getSession();
session.setAttribute("message", textFile);
session.setAttribute("itemname",loginForm.getItemName().trim());
session.setAttribute("lotnumber",loginForm.getLotNumber().trim());
session.setAttribute("godownname",loginForm.getStockGodown().trim());
(Not an answer; refactored but untested code for others trying to help.)
This is a refactored action, making it easier to see what's actually going on; the original code is difficult to reason about. The trim() functionality is moved to action form setters to avoid redundancy.
public class LoginAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
throws Exception {
LoginForm loginForm = (LoginForm) form;
if (invalidForm(loginForm)) {
return mapping.findForward("failure");
}
String fileName = createFile(loginForm);
request.setAttribute("message", fileName);
request.setAttribute("itemname", loginForm.getItemName());
request.setAttribute("lotnumber", loginForm.getLotNumber());
request.setAttribute("godownname", loginForm.getStockGodown());
return mapping.findForward("success");
}
private String createFile(LoginForm loginForm) throws IOException {
ServletContext context = getServlet().getServletContext();
String driveName = context.getInitParameter("drive").trim();
String folderName = context.getInitParameter("foldername").trim();
String pathName = driveName + ":/" + folderName;
new File(pathName).mkdirs();
String fileNamePath = pathName + createFileName(loginForm);
ensureFileExists(fileNamePath);
return fileNamePath;
}
private void ensureFileExists(String fileNamePath) throws IOException {
boolean fileExists = new File(fileNamePath).exists();
if (!fileExists) {
File file = new File(fileNamePath);
file.createNewFile();
}
}
private boolean invalidForm(LoginForm loginForm) {
return loginForm.getItemName().equals("")
|| loginForm.getLotNumber().equals("")
|| loginForm.getStockGodown().equals("");
}
private String createFileName(LoginForm loginForm) {
return loginForm.getItemName() + "_"
+ loginForm.getLotNumber() + "_"
+ loginForm.getStockGodown() + "_"
+ createFileNameTimeStamp() + ".txt";
}
private String createFileNameTimeStamp() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd G 'at' hh.mm.ss z");
String dateTime = sdf.format(Calendar.getInstance().getTime());
String[] tempDateStore = dateTime.split("AD at");
return tempDateStore[0].trim() + "_" + tempDateStore[1].trim();
}
}

Fill fields in webview automatically

I have seen this question floating around the internet, but I haven't found a working solution yet. Basically, I want to load my app and press a button; the button action will then fill in a username and password in a website already loaded in the webview (or wait for onPageFinished). Finally, the submit button on the login page will be activated.
From what I understand this can be done by doing a java injection with the loadUrl(javascript), but I don't know what the java commands would be to fill in the fields. The same question was asked for iOS, but the commands are slightly different.
Is it possible to do what I am asking with javascript in a webivew, or do I have to do a http-post without a webview like this or this?
Thank you so much for any help you can give!
Thanks all for your answer, it helped me, but didn't work.
It was allways opening a white page until i found this :
https://stackoverflow.com/a/25606090/3204928
So here complete solution, mixing all infos found here and there :
1) first of all you have to enable DOM storage, if you don't do that, .GetElementByXXX will return nothing (you have to do it before loading the page)
myWebView.getSettings().setDomStorageEnabled(true);
2)Your last Javascript call on GetElementByXXX MUST store the result in a variable
Exemple 1 :
_webview.loadUrl("javascript:var uselessvar =document.getElementById('passwordfield').value='"+password+"';");
here only one call (only one semi-colon) so we immediatly store the result in 'uselessvar'
Example 2 : see user802467 answer
here there is 3 calls (one for login field, one for password field, one to submit button), only the last call need to be store, it's done in 'frms'
Javascript programmers should easily explain this behaviour...
hope this will help
You don't need to use "java commands"... but instead JavaScript... for instance:
String username = "cristian";
webview.loadUrl("javascript:document.getElementById('username').value = '"+username+"';");
So basically, what you have to do is a big string of JavaScript code that will get those fields and put values on them; also, you can enable/disable the submit button from JavaScript.
This worked for me to fill form values and submitting the form:
webView.loadUrl("javascript: {" +
"document.getElementById('username').value = '"+uname +"';" +
"document.getElementById('password').value = '"+password+"';" +
"var frms = document.getElementsByName('loginForm');" +
"frms[0].submit(); };");
Here is complete code which works for me (Bitbucket):
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setDomStorageEnabled(true);
webView.loadUrl("http://example.com/");
webView.setWebViewClient(new WebViewClient(){
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
final String password = "password";
final String username = "username";
final String answer = 5;
final String js = "javascript:" +
"document.getElementById('password').value = '" + password + "';" +
"document.getElementById('username').value = '" + username + "';" +
"var ans = document.getElementsByName('answer');" +
"ans[0].value = '" + answer + "';" +
"document.getElementById('fl').click()";
if (Build.VERSION.SDK_INT >= 19) {
view.evaluateJavascript(js, new ValueCallback<String>() {
#Override
public void onReceiveValue(String s) {
}
});
} else {
view.loadUrl(js);
}
}
});
I tried #user802467 solution.But there was a different behaviour in 2 things
If I stored ONLY the last javascript call in a variable, it was not filling in the fields. Instead if I stored all the three calls in variables, it did
For some reason my form was not being submitted using submit(). But instead of submitting the form, if I clicked on the submit button using button.click(), I didnot need to store all the three calls and everything worked perfectly!
Here is what I used (but didnt work)
view.loadUrl("javascript: var x = document.getElementById('username').value = '" + username + "';" +
"var y = document.getElementById('password').value = '" + password + "';" +
"var form1 = document.getElementById('loginform');" +
"form1[0].submit(); ");
Here is the code that worked for me
view.loadUrl("javascript: document.getElementById('username').value = '" + username + "';" +
" document.getElementById('password').value = '" + password + "';" +
"var z = document.getElementById('submitbutton').click();"
);
It works for me
webView.loadUrl("javascript:var uselessvar =document.getElementById('regno').value='"+mob+"';",null);
webView.loadUrl("javascript:var uselessvar =document.getElementById('passwd').value='"+pass+"';",null);

Generating dynamic checkboxes through servlets?

I am using RestfbApi to fetch my friends' names and display on a web page. I also want a corresponding checkbox to each friend, since from the use of table tag , I have friend's name as well as corresponding checkbox.
As I generated checkboxes dynamically , how to make sure which checkboxes are checked when my app runs. The scenario is if I checked five friends and press post to wall button, a wall should be post to all five friends. I know how to post a wall just want to know how to map user selected friends(checked ones) to java code.
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException
{
User user = facebookClient.fetchObject("me", User.class);
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String docType =
"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " +
"Transitional//EN\">\n";
out.println(docType +
"<HTML>\n" +
"<HEAD><TITLE>Hello</TITLE></HEAD>\n" +
"<BODY BGCOLOR=\"#FDF5E6\">\n" +
"<H1></H1>\n" +
"</BODY></HTML>");
JsonObject accounts = facebookClient.fetchObject("me/friends",JsonObject.class);
JsonArray data = accounts.getJsonArray("data");
for(int i = 0; i < data.length(); i++)
{
String id = data.getJsonObject(i).getString("id");
Double int1 = Double.parseDouble(id);
String strName = data.getJsonObject(i).getString("name");
out.println("<table>");
out.println("<tr><td> <input type='checkbox' name='wahtevername' value='"+int1 +"'>"+strName+" </td></tr>");
out.println("</table>" );
}
}
out.println(docType +"<form method=\"GET\">"+"<input type=\"submit\" value=\"Post to wall\" name=\"option\">"+"</form>");
Use request.gatParameterValues("whatevername") to get an array of the values of selected checkboxes.
(Btw, it would be better to place the html code in JSP. Set the list as request attribute and then use JSTL's <c:forEach> to iterate)

Categories

Resources