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
Related
I have a requirement of designing a form within a StringBuffer.
I have a form with one text field and one delete button. the form will we submitted to the same jsp page and the value of text field is again populated in the text field.
The button Add Additional Info functionality is to add new row in the form that too is a one text field & delete button.
This is the form.
coding done for the form is as below:
buffer.append("<TR><TD class=\"formdata1\" align=\"center\" colspan=\"1\"><input name=\"_addInfo"+ rowValue +"\" type=\"text\" class=\"formdata2\"size=\"90\" maxlength=\"100\" value="+ **tempInfoValue** + " ></input>\n");
buffer.append("<input type=\"button\" class=\"button\" onClick=\"deleteLastAddInfoLine(" + formName +",'"+ rowValue + "'," +totalNumberOfRows+ ");\" value=\"Delete\" ></input></td>\n");
buffer.append(" </TR>\n");
rowValue++;
}
buffer.append(" <TR> <TD class=\"buttonrow\" class=\"formlabel\" colspan=\"6\" ><input type=\"button\" class=\"button\" onClick=\"addInfoLine(" + formName +",'"+ actionValue + "'," +totalNumberOfRows+ ");\" value=\"Add Additional Info\" ></input>\n ");
buffer.append(" </TR>\n");
buffer.append(" </table> ");
Issue is:
If input value is: abc'xyz then after clicking on Add Additional Info button the same value should be populated.
but the output value populated is: abc
'xyz -> this content is removed.
Here, this tempInfoValue is populated again.
So it can contain anything like '(singlecode/doublecode)/:/;/./ or etc.
So how should i write the code that when again it is populated then it will not change the value of text field.
I am working an an JavaFX Webbrowser that can autologin to some sites, i know how to set the data to username and password fields but how to i make it execute the login button click?
This is what i got so far:
String email = "document.getElementsByName('email')[0].value='MY_EMAIL';";
String pass = "document.getElementsByName('pass')[0].value='MY_PASSWORD';";
String login = "";
webEngine.executeScript(email);
webEngine.executeScript(pass);
webEngine.executeScript(login);
and this is the javascript code of the button it should click:
<label class="uiButton uiButtonConfirm" id="loginbutton" for="u_0_c"><input value="Aanmelden" tabindex="4" type="submit" id="u_0_c"></label>
this is a concentrated, non-specialized example... uses the dom.w3c.Node.* package
HTMLInputElement element = (HTMLInputElement)myWebView.getEngine().getDocument().getElementsByTagName("input").item(0);
element.click();
Find a way to handle the object you're looking for, and it will work.
I haven't tried that, but it should work. The idea is add jQuery to the loaded page and then to use it to click the button. This post explains how to do this with JS: How Do I Add jQuery To Head With JavaScript? So with Java it should be (I've copied the first answer into a string and executing it with the web engine):
String script = "script = document.createElement('script');\n" +
"\n" +
"script.onload = function() {\n" +
" // jQuery is available now\n" +
"};\n" +
"var head = document.getElementsByTagName(\"head\")[0];\n" +
"\n" +
"script.type = 'text/javascript';\n" +
"script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js';\n" +
"\n" +
"head.appendChild(script);";
webEngine.executeScript(script);
This should be done right when WebView is initialized (via webEngine.getLoadWorker().stateProperty().addListener(...)). Note: jQuery is loaded asynchronously.
Now you should be able to click a button with jQuery:
webEngine.executeScript("$('#buttonId')[0].click()");
This post should help you with debugging JS in a WebView: JAVAFX / WebView / WebEngine FireBugLite or Some other debugger?
First time post here, I hope its a valid question. I've been building a basic Java servlet which accepts 3 name/value pairs from a form on a page, sets those as 1. request attributes 2. session attributes and 3. cookie attributes. Cookies are then added to the response, and then the view (AccountSettings.jsp) is forwarded. The AccountSettings page is then supposed to use request.getCookies() to dump them into an array, then read the values from the array. All of this is supposed to happen every time I use this form.
My problem is that the cookie values are only correct the first time I use the form, then every time I use the form again, the cookies display the last value that was entered on page load. If I refresh the page, however, the cookies values will display correctly. I tried manually deleting the cookies in the Logout servlet (setMaxAge(0) then re-add to response) but this only produced a constant ArrayOutOfBoundsException at index 1, so I commented that portion out and leave the cookies alone.
I checked cookies associated with localhost in Chrome after the page is displayed, and the values are set correctly, so it seems to me like the JSP is drawn before the cookies are actually set correctly.
Any help on how to fix this would be appreciated. Here's my code.
Servlet:
public class Login extends HttpServlet {
private static final long serialVersionUID = 1L;
public Login() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
login(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
login(request, response);
}
private void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
// get a new or existing session
HttpSession session = request.getSession();
// Instantiate user and populate values
User user = new User();
user.setUser(request.getParameter("user"));
user.setPass(request.getParameter("pass"));
// Get last page
String referringUrl = request.getParameter("referringPage");
session.setAttribute("user", user.getUser());
session.setAttribute("pass", user.getPass());
session.setAttribute("lastPage", referringUrl);
Cookie cookie1 = new Cookie("user", user.getUser());
Cookie cookie2 = new Cookie("pass", user.getPass());
Cookie cookie3 = new Cookie("lastPage", referringUrl);
response.addCookie(cookie1);
response.addCookie(cookie2);
response.addCookie(cookie3);
request.setAttribute("user", user.getUser());
request.setAttribute("pass", user.getPass());
request.setAttribute("lastPage", referringUrl);
try{
if (user.authorize()){
session.setAttribute("name", user.getName());
session.setAttribute("authorized", "1");
}else{
session.setAttribute("authorized", "0");
}
}
catch(Exception e){
e.printStackTrace();
}
RequestDispatcher view = request.getRequestDispatcher("AccountSettings.jsp");
view.forward(request, response);
user.destroy();
}
}
View:
<div id="content">
<div class="padding">
<%
if (!loggedIn){
out.print(
"Oops! I'm not sure how you got here..."
);
}else{
Cookie[] cookies = request.getCookies();
out.print(
"<h2>Account Settings</h2><br><br>" +
"<table>" +
"<tr>" +
"<th>Source</th>" +
"<th>Username</th>" +
"<th>Password</th>" +
"<th>Last Page Visted</th>" +
"</tr>" +
"<tr>" +
"<th>Request</th>" +
"<td>" + request.getAttribute("user") + "</td>" +
"<td>" + request.getAttribute("pass") + "</td>" +
"<td>" + request.getAttribute("lastPage") + "</td>" +
"</tr>" +
"<tr>" +
"<th>Session</th>" +
"<td>" + session.getAttribute("user") + "</td>" +
"<td>" + session.getAttribute("pass") + "</td>" +
"<td>" + session.getAttribute("lastPage") + "</td>" +
"</tr>" +
"<tr>" +
"<th>Cookies</th>" +
"<td>" + cookies[1].getValue() + "</td>" +
"<td>" + cookies[2].getValue() + "</td>" +
"<td>" + cookies[3].getValue() + "</td>" +
"</tr>" +
"</table>"
);
}
%>
</div>
</div>
so it seems to me like the JSP is drawn before the cookies are actually set correctly
That's correct. You're adding new cookies to the response (so they're only available in subsequent requests on the same domain and path), but your JSP is attempting to read cookies from the current request.
You need either to send a redirect instead of a forward by replacing
RequestDispatcher view = request.getRequestDispatcher("AccountSettings.jsp");
view.forward(request, response);
by
response.sendRedirect("AccountSettings.jsp");
or to copy cookie values as request attributes, so that JSP can get them as request attributes (you already know how to do that).
Unrelated to the concrete problem, passing around the password in a cookie is a very bad idea. That's a huge security hole. For your concrete functional requirement, you're better off storing the logged-in user as a session attribute instead.
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.
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)