Currency Exchange in Spring Boot - java

I'm writing code for currency exchanger in spring boot (I'm a begginer) and right now I'm stuck on thymeleaf template. Right now my template looks like this :
<div align="center">
<form th:action = "#{/postCurrency}" method = "POST">
<label for="firstNumber"></label>
<input id = "firstNumber" type="number" name = "fNumber"/>
<br/>
<br/>
<input type="submit" value="Submit">
</form>
</div>
So this means that I have one "box" where user types in number and now I want to have a second "box" where currency will be exchanged and automatically shown in that "box", How do I do that ?
EDIT : My template now looks like this (exchange.html):
<form th:action = "#{/postCurrency}" method = "POST">
<label for="firstNumber"></label>
<input id = "firstNumber" type="number" name = "fNumber"/>
<br/>
<br/>
<input type="submit" value="Submit">
<br/>
<br/>
<input type = "number" th:field="*{resultNumber}" disabled/>
</form>
My controller class :
#PostMapping("/postCurrency")
public String postExchange(#RequestParam Double fNumber , Model model){
Double number = exchangeLogic.exchange(fNumber);
model.addAttribute("resultNumber",number);
return "redirect:/exchange";
}
The problem is that thymleaf can't read the modelattribute , I need to take "resultNumber" and make it visible in form tag

In your controller try this.
#PostMapping("/postCurrency")
public String postExchange(#RequestParam Double fNumber , Model model){
Double number = exchangeLogic.exchange(fNumber);
model.addAttribute("resultNumber",number);
return "exchange";//your html page
}
and in your html page
<input type = "number" th:value="${resultNumber}" disabled/>
let me know if it works for you.

Related

servlet can't get option value from jsp

I'm doing a java web application using jsp and servlets.
I have a form and I retrieve different values from my db to populate an option. This is my form:
<form class="form" action ="<%=request.getContextPath()%>/aggiungiLibro" method ="post">
<div class="form__group">
<input type="text" placeholder="Titolo" class="form__input" name = "titolo"/>
</div>
<div class="form__group">
<input type="text" placeholder="Quantità disponibile" class="form__input" name="quantita" />
</div>
<div class="form__group">
<select class="form__input" name="autore">
<c:forEach items="${listaAutori}" var = "autore" >
<option value="${autore.idAutore}"><c:out value="${autore.nome} ${autore.cognome}" /></option>
</c:forEach>
</select>
</div>
<button class="btn btn-light" type="submit">Inserisci nuovo libro</button>
</form>
In the servlet I retrive my data with
String titolo = request.getParameter("titolo");
int quantita = Integer.parseInt(request.getParameter("quantita"));
int autore = Integer.parseInt(request.getParameter("autore"));
I get right values for 'titolo' and 'quantita' but I get the string '${autore.nome}' for 'autore'.
It seems like it doesn't replace the string with the actual value.
The field idAutore is spelt right.
(In the jsp page I see the correct values for ${autore.nome} ${autore.cognome})
Anyone can help me please? What I'm doing wrong?
I solved replacing this:
<option value="${autore.idAutore}">
with this:
<option value="<c:out value='${autore.idAutore}' />">

Hidden input in thymeleaf with wrong value

in GET method I'm adding these to the model:
model.addAttribute("team", team);
model.addAttribute("players", team.getPlayers());
model.addAttribute("inviting", new InvitingPlayerToTeam());
And a fragment of view with this model:
<div id="news" th:fragment="playerList">
<span>Nazwa: </span>
<span th:text="${team.name}">nazwa teamu</span>
<br>
<span th:each="player : ${players}" th:utext="${player.username} + '</br>'">-</span>
<br><br>
<form method="POST" th:action="#{/team/invitePlayer}" th:object="${inviting}">
Nazwa <input type="text" th:field="*{username}">
<input type="hidden" th:field="*{teamId}" th:value="${team.id}">
<br>
<input type="submit" value="Zaproś">
</form>
</div>
What is wrong? In post method field inviting.username has good value, but inviting.teamId is 0. Where is the problem?
Just remove th:value="${team.id}". You do not need to set this value again.
You should set up your form backing bean with the correct values in your controller.
inviting.setTeamId(...)

Receive different result from 2 empty form inputs

In a .jsp page I have a form (POST method):
<div class="form-group">
<div class="col-md-3">
<input type="text" list="materials" class="form-control" name="material"/>
<datalist id="materials"></datalist>
</div>
<div class="col-md-3 col-sm-3">
<input type="number" class="form-control" name="quantity" >
</div>
</div>
I delete the html5 element required from the input to see what happens if the user submit the form without filling these inputs. In my servlet, I get this:
String material = request.getParameter("material");
String quantity = request.getParameter("quantity");
System.out.println("material="+ material + "-quantity=" + quantity);
and I get:
material=-quantity=null
The fact that I receive an empty string and a null result is it because of the diferrent type in the input?

How to return an error HTML (Input Validation)

I am currently developing a web site (Part of a university assignment)
I just put some input validation, although when I redirect due to an error from validation,
For example:
var x = document.getElementById("age").checked;
var y = document.getElementById("agreement").checked;
var z = document.getElementById("sex").value;
if(x != true & y != true & z == null)
{
response.sendRedirect("Register.jsp");
}
I was looking to have some sort of error message appear above the form, to tell the user that they have created an error within the form. (For example, if they did not enter their Gender or did not agree to either of the checkboxes). Also noted, I will change the validation code slightly to be more specific to the error in which the person has made.
Form:
<h3>Register as user</h3>
<form method="POST" action="Register">
<ul>
<li>First Name: <input type="text" name ="firstName"></li>
<li>Last Name: <input type = "text" name = "lastName"></li>
<li>Email Address: <input type = "email" name = "email"></li>
<li>Gender: Male <input type ="radio" name ="sex" value="male">
Female <input type ="radio" name ="sex" value="female"></li>
<li>User Name <input type="text" name="username"></li>
<li>Password <input type="password" name="password"></li>
<li>You must be 12 or over to register to this web site. Please check if you are over 12: <input type = "checkbox" name="age"></li>
<li>Please check this box to agree to the Terms and Conditions <input type ="checkbox" name="agreement"></li>
</ul>
<br/>
<input type="submit" value="Register">
</form>
Thank you for any help or advice you can give me, I really appreciate it as I am rather new to web development and I want to improve and understand techniques that web developers use.
var validate = function(form) {
var errors = [];
if (!form.sex[0].checked && !form.sex[1].checked) {
errors.push('Please select a gender');
}
if (!form.agreement.checked) {
errors.push('Please agree to T&C');
}
if (errors.length) {
alert(errors.join('\n'));
return false;
}
return true;
};
<h3>Register as user</h3>
<form method="POST" action="Register.jsp" onsubmit="return validate(this);">
<ul>
<li>First Name:
<input type="text" name="firstName">
</li>
<li>Last Name:
<input type="text" name="lastName">
</li>
<li>Email Address:
<input type="email" name="email">
</li>
<li>Gender: Male
<input type="radio" name="sex" value="male">Female
<input type="radio" name="sex" value="female">
</li>
<li>User Name
<input type="text" name="username">
</li>
<li>Password
<input type="password" name="password">
</li>
<li>You must be 12 or over to register to this web site. Please check if you are over 12:
<input type="checkbox" name="age">
</li>
<li>Please check this box to agree to the Terms and Conditions
<input type="checkbox" name="agreement">
</li>
</ul>
<br/>
<input type="submit" value="Register">
</form>
I did something like this. I have an html element which is hidden by default.
It is red and take the whole width of the div I put into.
And I've a function to manage errors :
var manageError = function(message) {
$("#element").val(message); // or $("#element").html(message) I guess
$("#element").clearQueue();
$("#element")slideDown(200).delay(10000).slideUp(200);
};
Does it help ?
use jQuery to do this. since you are learning..it will be more helpful for you.
first thing I noticed there, you have used response.sendRedirect(...); in side your javascript which is a wrong approach.
And in your form, don't use un-ordered list like approach, simply use div tags.
I will give a simple example:
<h3>Register as user</h3>
<form method="POST" action="Register.jsp" id="formId">
First Name:
<input type="text" name="firstName">Last Name:
<input type="text" name="lastName">
<div id="errMsg"></div>
<input type="button" value="submit" id="submtBtn">
</form>
and in your javascript file, use it with jQuery:
< !DOCTYPE html >
< html >
< head >
< script src = "http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js" > < /script>
</head >
< script >
$("submtBtn").click(function({
var errorMsg = "";
if ($("firstName").val === '' || $("lastName").val === '') {
errorMsg = "<b>firstName and LastName can not be empty!<b>";
$("errMsg").html(errMsg);
return;
}
$("#formId").submit();
});
< /script>
you can follow above approach.... if you're using Servlets, you could follow jQuery Ajax to submit your values. try and see...hope it will give you an idea..!
First put the validation code in a function and call that function.
function validate(){
..........write your validation code
}
Call this from submit button via onclick or onchange or onblur attribute of input tag.
You can always use HTML 5. With the required action. They can never leave anything blank if this is in. Be aware that it might work with a space in it or something.
Try this:
<li>First Name: <input type="text" name ="firstName" required></li>

Java spring #RequestParam JSP

current controller code:
#RequestMapping(value = "/city", method = RequestMethod.POST)
public String getWeather(#RequestParam("city") int city_id,
#RequestParam("text") String days, //this gives errrors, when i remove this line, then it is okay
Model model) {
logger.debug("Received request to show cities page");
//int city =
// Attach list of subscriptions to the Model
model.addAttribute("city", service.getCity(city_id));
// This will resolve to /WEB-INF/jsp/subscribers.jsp
return "city";
}
this is my JSP file(view):
<form method="post" action="/spring/krams/show/city">
Vali linn
<select name="city">
<c:forEach items="${cities}" var="city">
<option value="<c:out value="${city.id}" />"><c:out value="${city.city}" /></option>
</c:forEach>
</select><br>
Vali prognoos N päeva kohta(kirjuta 1 hetkese ilma jaoks)
<input type="text name="text">
<input type="submit" value="Test" name="submit" />
</form>
i want to get a value from the textbox named TEXT, but when i press the submit button then i get
HTTP Status 400 - The request sent by the client was syntactically incorrect ().
I am adding this answer so that you can accept it, as it was suggested by Bozho :)
There seems to be a problem in the HTML:
<input type="text name="text">
Change it to
<input type="text" name="text"> and try .
I think syntactically incorrect means the names specified in the #RequestParam annotations don't match with the request param names... possibly because of the above error in HTML.

Categories