Passing value from controller to html in spring - java

Hello I have a simple web page where I have a button and a text near to button. I need to change text when button clicked and get the new text from code.
This is controller class from where I need to pass response:
#GetMapping("/stream")
public String openStream(Model model) {
String response = service.openStream();
model.addAttribute("stream", response);
return "mainpage";
}
And here my html page, the value from controller must be instead of question marks:
<div id="container">
<button class="button"
onclick="window.location.href = '/stream';">Stream</button>
<p align="center">?????</p>
</div>
Thanks in advance for your help.
Edit:
I tried ${stream}
but getting it as text not value, please see screenshot:
Edit 2:
I need pass String from the text area to doc variable in the controller. Please help.
HTML:
<div>
<textarea rows="10" cols="100" name="description"></textarea>
button class="button" onclick="window.location.href ='/send';">Send</button>
</div>
Controller:
#GetMapping("/send")
public String send(String doc) {
service.sendDoc(doc);
return "mainpage";
}

Change
<p align="center">?????</p>
To
<p align="center">${stream}</p> OR <p th:text="${stream}"></p>
How it is working?
You can access variables value by ${key}.
Example
model.addAttribute("key", value);
Get value by ${key} in HTML
In Thymeleaf, these model attributes (or context variables in
Thymeleaf jargon) can be accessed with the following syntax:
${attributeName}, where attributeName in our case is stream. This
is a Spring EL expression. In short, Spring EL (Spring Expression
Language) is a language that supports querying and manipulating an
object graph at runtime.
UPDATE
The th:field attribute can be used on input, select, or, textarea.
Replace <p align="center">?????</p> with
<input type="text" id="stream" name="stream" th:value="${stream}" />
OR
<input type="text" th:field="*{stream}" />`
OR
<input type="text" id="stream" name="stream" th:field="*{stream}" th:value="${stream}" />
Also try <p th:inline="text">[[${stream}]]</p>; <p data-th-text="${stream}" />
Thymeleaf Document Thymeleaf Document Inputs
UPDATE 2
Get value from Thymeleaf to Spring Boot
<form th:action="#{/send}" method="get">
<textarea th:name="doc" rows="10" cols="100" name="doc"></textarea>
<button type="submit">Send</button>
</form>
#GetMapping("/send")
public String send(#RequestParam(name="doc", required = false) String doc) {
//change required = false as per requirement
System.out.println("Doc: "+doc);
return "textarea-input";
}
Note: use "th:field" for Entity/Model

Thank you for your help. Below shown line helped:
<p th:inline="text">[[${stream}]]</p>

Try these : <p align="center">${stream}</p> or <p th:text="${stream}"></p>
This tag may be causing a problem :
<button class="button"
onclick="window.location.href = '/stream';">Stream</button>
Please check it by removing this.

So i solve it like that :
let said i want to pass int ValueIwantToPass=5
in my controller i put
#GetMapping("/tasks")
public String listTasks(Model model) {
model.addAttribute("value", ValueIwantToPass);
}
and in my HTML file it look
<h1>i wanted to pass [[${value}]]</h1>

Related

Thymeleaf insert text in html code?

I want to insert an Attribute into the html Code.
I tried this, but it's not working:
<div id="${var}"> ... </div>
I think you know what I mean. The attribute 'var' should be the id. I didn't find a solution...
You just need to use the th:attr attribute. It is explained in the reference documentation 5.1:
5.1 Setting the value of any attribute
Enter then the th:attr attribute, and its ability to change the value
of attributes of the tags it is set in:
<form action="subscribe.html" th:attr="action=#{/subscribe}">
<fieldset>
<input type="text" name="email" />
<input type="submit" value="Subscribe!" th:attr="value=#{subscribe.submit}"/>
</fieldset>
</form>
The
concept is quite straightforward: th:attr simply takes an expression
that assigns a value to an attribute. Having created the corresponding
controller and messages files, the result of processing this file will
be:
<form action="/gtvg/subscribe">
<fieldset>
<input type="text" name="email" />
<input type="submit" value="¡Suscríbe!"/>
</fieldset>
</form>
Use this
<div th:attr="id=${var}"> ... </div>
Thymeleaf only evaluates attributes that are prefixed with th:. Here is a list of the attributes that are evaluated:
http://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html#setting-value-to-specific-attributes
In your case, th:id is already built in so you can simply do <div th:id="${var}"> ... </div> and it will work. th:attr, is used to define attributes that thymeleaf doesn't normally support.

Get element by cssSelector in Selenium (Java)

<html>
<body>
<div id="login-box" class="form-box">
<form id="frmlogin" class="form" name="frmlogin" method="post">
<div class="body">
<div class="form-group">
<input id="email" class="form-control" type="text" maxlength="50" value="dfsf#gmail.com" placeholder="Email" name="email">
<span class="red">Please provide a valid email address</span>
</div>
<div class="form-group">
<input class="form-control" type="password" maxlength="15" placeholder="Password" name="password">
<span class="red">Password must not be empty</span>
</div>
</div>
</form>
</div>
</body>
</html>
I need to get "Please provide a valid email address" and "Password must not be empty" using nth-child in cssSelector.
I tried the below snippet:
//Case 2
driver.findElement(By.name("email")).clear();
driver.findElement(By.name("email")).sendKeys("");
String a=driver.findElement(By.cssSelector("form#frmlogin div.form-group:nth-child(1)>span")).getText();
System.out.println(a);
if(a.contains("valid email address"))
{
System.out.println("Login test case2 Passed");
}
else
{
System.out.println("Login test case2 Failed");
}
It results in NoSuchElementFound.
You can use it by element selector
By.cssSelector("input[name=email]")
Try these codes below:
1- For returning 'Please provide a valid email address':
String a = driver.findElement(By.cssSelector("form#frmlogin div.form-group:nth-child(1)>span")).getText();
System.out.println(a);
2- For returning 'Password must not be empty':
String a = driver.findElement(By.cssSelector("form#frmlogin div.form-group:nth-child(2)>span")).getText();
System.out.println(a);
If you don't have to you could also use XPath selectors which are in my opinion easier to use when you have to select the nth element of something. Try this one:
For E-Mail:
By.xpath("//div[#class='form-group'][1]/span")
For the password:
By.xpath("//div[#class='form-group'][2]/span")
But could you also provide the full HTML page you are working with? Maybe the form is inside an iframe and therefore Selenium has problems locating the element
You need to add .getText() method in order to get the text inside the tag.
Have you tried something like object.getAttribute("innerHTML"), literally with "innerHTML", like this ?
I had a similar problem getting a text from a span tag

How to keep dynamicly added controls ater postback? Javascript, JSP

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 :)

How to send label parameter from JSP to servlet?

I have a jQuery dialogue box which contains values as checkboxes. On selecting the checkboxes I am storing the selected values into label. Next I have to send these values from label as parameter through form to servlet but I don't know how to complete it.
Here is my code:
<form action="CallTimer" method="GET">
<label class="button2">Set Date: </label>
<input type="text" name="date" id="date" size="4">
<input type="Submit" name="Submit" value="Submit" id="Submit">
<br/>
Select Reporting Level
<label class="button2" style="display:none" id="depart"> Department</label>
</form>
I am retrieving these parameters in my Servlet as:
String reportname=request.getParameter("depart");
System.out.println(reportname);
But it is returning null values. Please help me.
Thanks in advance.
You have to use hidden input field:
<input type="hidden" name="depart" />
You need to understand what gets passed on form submission and what is not. In a nutshell, only values of the input fields get sent to the server. You have several ways to solve your problem:
Write value to a hidden input field
Modify the query string (what gets sent after ? in your GET request) during form submission (using java script):
?...&depart=xxx

form values not submitted to the servlet

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.

Categories