Radio button and request.getParameter - java

I have a radio button really simple in my html file:
<form role="form" method="post" action="jsp/site/Portal.jsp?page=mypage">
<input type="radio" id="radio_1" name="name_radio" value="value1" />
<input type="radio" id="radio_2" name="name_radio" value="value2" />
<button name="action_validateForm" type="submit">
Valider
</button>
</form>
But when i send the form it goes in function :
#Action( ACTION_VALIDATE_FORM )
public Page doValidateForm( HttpServletRequest request )
{
String valueGet = request.getParameter( "name_radio" );
if ( valueGet.equals( "value1" ) )
{
//Do action
}
else if ( valueGet.equals( "value2" ) )
{
//Do other action
}
}
The problem is that no matter the radio button I select before validate the form when I check request.getParameter( "name_radio" ) the value is always false. How can it be possible? it should be value1, value2 or null?

I think you need to add submit button or javascript code to submit your form, then try to fetch radio button value in JSP.
see i have added submit button.
<form role="form" method="post" action="jsp/site/Portal.jsp?page=mypage">
<input type="radio" id="radio_1" name="name_radio" value="value1" />
<input type="radio" id="radio_2" name="name_radio" value="value2" />
<button type="submit" value="Submit">Submit</button>
</form>

Related

Javascript + Thymeleaf doesn't find the form

On the input form, I perform a check of the entered cost value. But running the script can't find the form input input01.
That's how it works:
<form name="form01" th:method="POST" th:action="#{/add-car/new}" th:object="${carEntity}">
<input type="text" name="input01">
...
<button type="submit" class="btn btn-primary" onclick="check()">Save</button>
</form>
<script>
function check() {
let inputVal = document.forms["form01"]["input01"].value;
OK!!!
....
}
</script>
But not like this:
<form name="form01" th:method="POST" th:action="#{/add-car/new}" th:object="${carEntity}">
<input type="text" name="input01" th:field="*{cost}">
...
<button type="submit" class="btn btn-primary" onclick="check()">Save</button>
</form>
<script>
function check() {
let inputVal = document.forms["form01"]["input01"].value;
Where Error:
"Uncaught TypeError: document.forms.form01.input01 is undefined"
....
}
</script>
What am I doing wrong?
As per https://www.thymeleaf.org/doc/tutorials/2.1/thymeleafspring.html,
<input type="text" th:field="*{datePlanted}" />
is equivalent to
<input type="text" id="datePlanted" name="datePlanted" th:value="*{datePlanted}" />
Hence when you add th:field="*{cost}", the form element name and id is getting changed to name="cost" id="cost". so document.forms["form01"]s input element will look like
<input type="text" name="cost" id="cost">
Either access the element as
document.forms["form01"]["cost"]
Or add a form id like below and your existing code should work.
<input id="input01" type="text" name="input01" th:field="*{cost}">.
Hope that helps to solve your problem.

Pass an input string to different jsp page base on button clicked using nested form

I'm trying to pass a trackingNo to jsp page based on which button is pressed.
I created 2 buttons, addnew and search.
The addnew is supposed to get the input trackingNo from the input field and pass it to tracking.jsp if it is pressed,
and the search is supposed to get the input trackingNo from the input field and pass it to a home_student_result.jsp.
I'm not sure what is the correct way to do it, so I tried using a nested form with "add" id in one form and "srch" id in another.
After running it, only the top form works. The inner form doesn't work.
Can anyone please help me, or suggest a better way to do it please?
<div>
<form id="add" method="post" action="tracking.jsp">
<i class="fas fa-search"></i>
<form id="srch" method="post" action="home_student_result.jsp">
<input name="target" type="input" placeholder = "Search..." class = "text_search"/>
</form>
</form>
</div>
<button class="button_search" onclick="document.getElementById('add').submit()">
Add New
</button>
<button class="button_search" onclick = "document.getElementById('srch').submit();">
Search
</button>
You can use only one form and click of button you can change the action value to particular value depending on button click and then submit your form.
Demo Code :
function submit(value) {
console.log(value)
//if value is add
if (value == "add") {
//change action of form
document.getElementById('forms').action = 'tracking.jsp'
document.getElementById('forms').submit(); //submit
} else {
document.getElementById('forms').action = 'home_student_result.jsp'
document.getElementById('forms').submit();
}
}
<div>
<!--add id to form-->
<form id="forms" method="post" action="tracking.jsp">
<i class="fas fa-search"></i>
<input name="target" type="input" placeholder="Search..." class="text_search" />
</form>
</div>
<!--add function with parameter(value of button) -->
<button class="button_search" value="add" onclick="submit(this.value)">
Add New
</button>
<button class="button_search" value="srch" onclick="submit(this.value)">
Search
</button>
You can keep both the forms independently and set the value of 'target' field using javascript. something like below .I've added id attributes to your code to work with vanilla javascript.
<div>
<form id="add" method="post" action="tracking.jsp">
<i class="fas fa-search"></i>
<input id="addText" type="input" placeholder = "add text"/>
<button class="button_search" onclick="addToSearch()">
Add New
</button>
</form>
<form id="srch" method="post" action="home_student_result.jsp">
<input name="target" id="searchValue" type="input" placeholder = "Search..." class = "text_search"/>
<button class="button_search" onclick = "document.getElementById('srch').submit();">
Search
</button>
</form>
</div>
<script>
function addToSearch(){
var textValue = document.getElementById('addText').value;
document.getElementById('searchValue').value = textValue;
}
</script>

How to call a method in HTML(Thymeleaf, Spring, Java)?

i'm beginner with Thymeleaf, but i want know how to call a method in HTML with Thymeleaf. I'm using Spring Boot with Spring MVC.
I want create a Button with a name like "Edit" and the user will edit the post of the blog, but if i want do that i have to know what's the ID from object Postagem.
My current code HTML: (blog.html)
<div th:each="postagem : ${postagens}">
<div class="blog-post">
<h2 class="blog-post-title" th:text="${postagem.titulo}"></h2>
<p class="blog-post-meta">25 de dezembro de 2019 publicado por Vitor</p>
<p th:text="${postagem.texto}"></p>
<form action="#" th:action="#{/blog}" th:object="${postagem}" method="post">
<button type="submit" class="btn btn-link" th:field="*{id}">Editar</button>
</form>
</div>
<!-- /.blog-post -->
</div>
My current method in Java: (PostagemController.java)
#PostMapping("/blog")
public String edit(Postagem postagem) {
for(Postagem post : postagens.findAll()) {
if(post.getId() == postagem.getId()) {
ModelAndView modelAndView = new ModelAndView("painel");
modelAndView.addObject("postagemEdit", post);
System.out.println("Id: " + post.getId());
System.out.println("Título: " + post.getTitulo());
System.out.println("Autor: " + post.getAutor());
System.out.println("Texto: " + post.getTexto());
break;
}
}
return "redirect:/painel";
}
My current code on "painel.html" where is my form that I want set the information
<form method="post" th:object="${postagemEdit}" th:action="#{/painel}" style="margin: 20px 0">
<div class="form-group">
<input type="text" class="form-control" placeholder="Título" th:field="*{titulo}" /> <br>
<input type="text" class="form-control" placeholder="Spoiler do artigo" th:field="*{spoiler}" /><br>
<input type="text" class="form-control" placeholder="Autor" th:field="*{autor}" /> <br>
<textarea id="mytextarea" th:field="*{texto}"></textarea> <br>
<button type="submit" class="btn btn-primary">Publicar</button>
</div>
</form>
It appears that you have not given the id a value in the html code. The default value for int in Java is 0 and that is possibly the reason why. Try to use 1 instead of *{id}.
If you are retrieving the blog post id and post content from the database which should be so then this problem will be solved.
issues
No name
Value not set
solution 1
<form action="#" th:action="#{/blog}" th:object="${postagem}" method="post">
<input type="hidden" name="id" class="btn btn-link" th:value="*{id}" />
<button type=submit class="btn btn-link">Editar</button>
</form>
solution 2
<form action="#" th:action="#{/blog}" th:object="${postagem}" method="post">
<button name="id" type=submit class="btn btn-link" th:value="*{id}">Editar</button>
</form>
solution 3
function myFunction(id) {
var f = document.createElement("form")
f.style.display="none"
f.action="/action_page.php"
f.method="get"
var inp = document.createElement("input");
inp.value=id
inp.name="id"
f.appendChild(inp);
document.body.appendChild(f);
f.submit();
}
<button type=submit class="btn btn-link" th:data-id="*{id}" onclick='myFunction(this.getAttribute("data-id"))'>Editar</button>
Following is the working code that i used in the html template to call java class function
<small th:text="${T(com.sample.util.UIclass).textContent(instr)}"> </small>
And below is the java class for the method :
package com.sample.util;
import com.sample.models.Instr;
public class UIclass {
public static String textContent(Instr instr)
{
return "Hello";
}
}
In case if you need to access same in javascript following is the code
let d = [[${T(com.sample.UIclass).textContent(instr)}]];
console.log(d);

How to make HTML Button perform action in Java?

Basically I'm creating an upvote/downvote system, Now I've created two buttons in HTML :
<button type="button" name="upvote"></button>
<br>
<input type="number" th:value = "${commentValue}" disabled>
<br>
<button type="button" name="downvote"></button>
First button with name attribute - "upvote" and second with "downvote" , Now I want to catch a click on button and change the commentValue accordingly, If user clicks upvote, comment value must incriment and on downvote it must decrement
I found some topics that said to implement ActionListener, Create JButton objects and etc. but isn't there any simpler way ?
This is my code right now, The buttons do nothing. :
Controller :
private int numberValue = 0;
#GetMapping("/check")
public String nuberCheck(Model model){
model.addAttribute("commentValue", numberValue);
return "numberCheck";
}
#PostMapping("/check")
public String upvote(Model model, #RequestParam String action){
if (action == "upvote"){
numberValue++;
model.addAttribute("commentValue", numberValue);
}else if (action == "downvote"){
numberValue --;
model.addAttribute("commentValue", numberValue);
}
return "numberCheck";
}
numberCheck :
<form action="#" th:action="#{/check}" method="post">
<button type="button" name="action" th:value="upvote" th:text = "upvote"></button>
<br>
<input type="number" th:value = "${commentValue}" disabled>
<br>
<button type="button" name="action" th:value = "dowvnote" th:text = "dowvnote"></button>
</form>
FIXED
Change button types to "submit" and then in controller :
#PostMapping("/check")
public String check(Model model,#RequestParam String action) {
System.out.println(action);
if (action.equals("upvote")) {
numberValue++;
model.addAttribute("numberValue", numberValue);
}
if (action.equals("dowvnote")) {
numberValue--;
model.addAttribute("numberValue", numberValue);
}
return "numberCheck";
}
#RequestParam String action "action" is the name attribute of button and "save" and "cancel" are the "value" attributes :) hope it helps
Sample:
HTML:
<form action="#" data-th-action="#{/action}" data-th-object="${model}" method="post">
<button type="submit" name="upvote"></button>
<button type="submit" name="downvote"></button>
</form>
Java:
#RequestMapping(value="/action", method=RequestMethod.POST)
public ModelAndView onClickAction() {}
Use the following and implement in your code
$(document).ready(function(){
$("#up").click(function(){
var up = $.post("/upvote", {changeBy: 1}, function(dataBack){
$("#upvote").text(dataBack);
});
});
$("#down").click(function(){
var down = $.post("/downvote", {changeBy: 1},
function(dataBack){
$("#downvote").text(dataBack);
});
});
});
You can use jquery for that. first add jquery library in your html page and write function like below inside script tag
function upVote(){
var counter= $('.comment').val();
counter++;
$('.coment').val(counter);
}
function downVote(){
var counter= $('.comment').val();
counter--;
$('.coment').val(counter);
}
<button type="submit" name="upvote" th:onclick="'upVote();'"></button>
<br>
<input type="number" class="comment"th:value = "${commentValue}" disabled>
<br>
<button type="submit" name="downvote" th:onclick="'upVote();'"></button>
There is one best way to solve this. When you click button trigger one event and at that event increase or decrease value. Use that value in an thymeleaf and pass it to the controller.

How to redirect to servlet when we have multiple buttons

I have 2 textboxes and 3 buttons and each button has specific action i.e. insert, update, delete.
But how to redirect it when specific button click ?
because i have used it in one form tag.
so what will it do when any button click ?
how it will get the action name ?
code :
<form action="Doaction" method="post">
First Name : <input type="text" id="fname" name="fname">
<br>
Last Name : <input type="text" id="lname" name="lname"><br>
<input type="button" value="Insert">
<input type="button" value="Update">
<input type="button" value="Delete">
</form>
any help please ?
in form : give name to buttons
First Name : <input type="text" id="fname" name="fname">
<br>
Last Name : <input type="text" id="lname" name="lname"><br>
<input type="button" value="Insert" name="button">
<input type="button" value="Update" name="button">
<input type="button" value="Delete" name="button">
</form>
String button_param = request.getParameter("button");
RequestDispatcher rd = null;
if(button_param .equals("Insert")
{
rd=request.getRequestDispatcher("InsertServlet");
}
else if(button_param .equals("Update"))
{
rd=request.getRequestDispatcher("UpdateServlet");
}
else if(button_param .equals("Delete"))
{
rd=request.getRequestDispatcher("DeleteServlet");
}
rd.forward(request, response);
you can create a common javascript function like submitForm('pass your action').
Here you can see that function has a parameter. you have to pass action based your requirement
for example :
<input type="button" value="Insert" onclick="submitForm('InsertURL');">
<input type="button" value="Update" onclick="submitForm('UpdateURL');">
Action function body like :
function submitForm(action){
//send Ajax Request to server...using action
}
Yes I have solved it.
I have given a common name to each button and in servlet i have first checked that from which button action call then as per it i have used if condition and inside it's block i have make a related code.
code :
<form action="Doreg" method="post">
First Name : <input type="text" id="fname" name="fname">
<br>
Last Name : <input type="text" id="lname" name="lname"><br>
<input type="submit" value="Insert" name="kb">
<input type="submit" value="Update" name="kb">
<input type="submit" value="Delete" name="kb">
</form>
java code :
String fname =request.getParameter("fname");
String lname =request.getParameter("lname");
String f = request.getParameter("kb");
if (f.equals("Insert"))
{
obj.connect();
String query ="insert into user(firstname,lastname) values('"+fname+"','"+lname+"')";
obj.passquery(query);
}
else if(f.equals("Delete"))
{
obj.connect();
String query ="delete user where firstname='"+fname+"' OR lastname='"+lname+"'";
obj.passquery(query);
}

Categories