Use web service in background of HTML - java

I have a web service and a html page and i want to calculate two values and show on the third text field but this code shows me on the next page. Any one help me for my FYP.
My index.html
<!DOCTYPE html>
<html>
<head>
<title>TO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<h1>JAX-RS</h1>
<form action="http://localhost:8080/ConnectingToNode/webapi/myresource?ID" method="post" target="_self">
<p>
Number1 : <input type="text" name="number1" />
</p>
<p>
Number2 : <input type="text" name="number2" />
</p>
<p>
Number3 : <input type="text" name="number3" />
</p>
<input type="submit" value="Add" />
<p>
Total : <input type="text" name="number3" />
</p>
</form>
</body>
</html>
My web service
#Path("myresource")
public class MyResource{
HashMap<String, String> map= new HashMap<String, String>();
#POST
#Produces(MediaType.TEXT_PLAIN)
public Response addNumber(
#FormParam("number1") int number1,
#FormParam("number2") int number2
) {
int total=number1+number2;
return Response.status(200).entity("Total : " + total).build();
}
}

You want perform an ajax call instead of submitting the form. So just build a javascript function e.g. using Jquery:
$.post("<your servlet here>", $("#y<ourFormIdHere>").serialize(),callback);
Where callback is a function like this:
function(data){
console.log("Data",data); // do what you want with response data
}
Off course you have to bind the $.post function to your form button.

Related

Can't create post request in thymeleaf

I tried to create POST request to send my form to the Spring server, but I'm only getting this error:
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'form' available as request attribute
My controller content:
// Form post handler
#PostMapping("/")
public String home(#ModelAttribute Form form, BindingResult bindingResult, Model model) {
Gson g = new Gson();
Form form_new = g.fromJson(JavaWebApplication.runtimeJsonContent, Form.class);
model.addAttribute("form", form);
model.addAttribute("ip", form.IP);
model.addAttribute("gateway", form.Gateway);
model.addAttribute("port", form.Port);
model.addAttribute("IncomingConnections", form.IncomingConnections);
return "index";
}
Here is my Form model:
public class Form {
public String IP;
public String Gateway;
public int Port;
public boolean IncomingConnections;
public int QoSEnable = 0;
public Form(){}
public Form(String IP, String gateway, int port, boolean incomingConnections) {
this.IP = IP;
this.Gateway = gateway;
this.Port = port;
this.IncomingConnections = incomingConnections;
this.QoSEnable = 0; // Assert that 0 is default
ExportToJson(this);
}
public Form(String IP, String gateway, int port, boolean incomingConnections, int qosEnable) {
this.IP = IP;
this.Gateway = gateway;
this.Port = port;
this.IncomingConnections = incomingConnections;
this.QoSEnable = qosEnable;
ExportToJson(this);
}
}
And my index.html webpage bound on / :
<!DOCTYPE html>
<html xmlns:th="https://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" th:href="#{./styles/main.css}">
<title>Document</title>
</head>
<body>
<form method="post" action="#" th:action="#{/}" th:object="${form}">
<div id="container">
<img src="https://kable-swiatlowodowe.net.pl/wp-content/uploads/2017/08/mikrotik.png" width="20%" style="margin-bottom: 5%;">
<br>
<div id="input-el">
<div class="input-element"><input type="text" placeholder="IP" name="IP" th:value="${ip}" th:field="*{IP}" id="input-element-ip"></div>
<div class="input-element"><input type="text" placeholder="Gateway" th:value="${gateway}" th:field="*{Gateway}" name="Gateway" id="input-element-gateway"></div>
<div class="input-element"><input type="number" placeholder="Port" th:value="${port}" th:field="*{Port}" name="Port" id="input-element-port"></div>
</div>
<div id="checkbox-el">
Incoming connections:<br>
<label><input type="checkbox" th:checked="${IncomingConnections}" th:field="*{IncomingConnections}" name="conections" id="conections-el">Allow</label>
</div>
QoS Mode<br>
<label><input type="radio" name="qos-mode-el" id="input-radio-game-first" checked>Game First</label>
<label><input type="radio" name="qos-mode-el" id="input-radio-multimedia-first">Multimedia First</label>
<button type="submit">Save</button>
</div>
</form>
</body>
</html>
Sample Postman request:
Response for this request:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="./styles/main.css">
<title>Document</title>
</head>
<body>
<form method="post">
<div id="container">
<img src="https://kable-swiatlowodowe.net.pl/wp-content/uploads/2017/08/mikrotik.png" width="20%" style="margin-bottom: 5%;">
<br>
<div id="input-el">
<div class="input-element">
<input type="text" placeholder="IP" name="IP" value="" id="input-element-ip"></div>
<div class="input-element">
<input type="text" placeholder="Gateway" value=""name="Gateway" id="input-element-gateway"></div>
<div class="input-element">
<input type="number" placeholder="Port" value="0" name="Port" id="input-element-port"></div>
</div>
<div id="checkbox-el">
Incoming connections:<br>
<label><input type="checkbox" name="conections" id="conections-el">Allow</label>
</div>
QoS Mode<br>
<label><input type="radio" name="qos-mode-el" id="input-radio-game-first" checked>Game First</label>
<label><input type="radio" name="qos-mode-el" id="input-radio-multimedia-first">Multimedia First</label>
<button type="submit">Save</button>
</div>
</form>
</body>
</html>
Each value content is clear
Any idea how to make this binding work correctly?
you are not passing the form object to your thymeleaf template
Do this -
#GETMapping("/")
public String getHome(Model model){
model.addAttribute("form", new Form());
return "index";
}
This will return a Form object to your thymleaf and then it can process the data in your code --
<form method="post" action="#" th:action="#{/}" th:object="${form}">
// This will now receive form object
</form>

How to fix "Exception evaluating SpringEL expression" error after submitting a variable Spring/Thymeleaf

I am using Spring Boot/Thymeleaf to create a form that accepts an email address, redirects to a results page that displays the accepted email and sends it to a third party API (authenticated with Oauth2). I am having trouble with the form portion, I am attempting to use Thymeleaf to accept the input to display it on the result.html page. I am receiving an error when trying to display it on the results page, full error is:
[THYMELEAF][http-nio-8080-exec-4] Exception processing template "result.html": Exception evaluating SpringEL expression: "signup.email" (template: "result.html" - line 10, col 4)
I was attempting to follow the examples provided here:
https://spring.io/guides/gs/handling-form-submission/
I have attempted to modify the controller from #PostMapping and #GetMapping to #RequestMapping and add commenting described in a workaround such as:
<!--/*#thymesVar id="signup" type="com.mainconfig.controller1"*/-->
Here is the signup.html code containing the form:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<html>
<head>
<title>My Jmml</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body style="background-color: #2B2B2B">
<br /><br />
<h2 style="text-align:center">Contact Information</h2>
<!-- Input Form -->
<!--/*#thymesVar id="signup" type="com.mainconfig.controller1"*/-->
<form action="#" th:action="#{/signup}" th:object="${signup}" method="post">
<div align="center">
<label>Email Address</label><br /><br />
<!--/*#thymesVar id="email" type="String"*/-->
<input type="text" th:field="*{email}" placeholder="Email" required />
<br />
<br />
<input class="submitbutton" type='submit' value='Submit'/>
<br />
</div>
</form>
</body>
</html>
Results page that should display the email (result.html):
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Thank you for your submission!</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<h1>Thank you for your submission!</h1>
<p th:text="'Email: ' + ${signup.email}" />
Submit another message
</body>
</html>
Controller:
#Controller
public class controller1 {
#RequestMapping (value = "/home")
public String home(Model model) {
return "index.html";
}
#RequestMapping(value = "/signup", method= RequestMethod.GET)
public String signupForm(Model model) {
model.addAttribute("signup", new emailInput());
return "signup.html";
}
#RequestMapping(value = "/signup", method= RequestMethod.POST)
public String signupSubmit(#ModelAttribute("email") emailInput email) {
return "result.html";
}
}
Expected output should be the email variable displayed on the results page after it being gathered in the signup form.
If you have a recommendation on how to better do what I am attempting, I am open to suggestions! I am very new to Spring/Thymeleaf but have had experience with Java/Jsp. Thank you for any help, please let me know if you need anything else to help!
Hopefully this will be a starting point for you.
Make sure you place the html files under /resources/templates.
I changed a bit your signup html and result.html as follows, they are still not perfect(avoid using inline styles and use an external stylesheet!):
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<head>
<title>My Jmml</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body style="background-color: #2B2B2B">
<br /><br />
<h2 style="text-align:center">Contact Information</h2>
<!-- Input Form -->
<!--/*#thymesVar id="signup" type="com.mainconfig.controller1"*/-->
<form th:action="#{/signup}" th:object="${signup}" method="post">
<div align="center">
<label>Email Address</label><br /><br />
<!--/*#thymesVar id="email" type="String"*/-->
<input type="text" th:field="*{email}" placeholder="Email" />
<br />
<br />
<input class="submitbutton" type="submit" value="Submit"/>
<br />
</div>
</form>
</body>
and the result.html looks like this
<!DOCTYPE HTML>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<head>
<title>Thank you for your submission!</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<h1>Thank you for your submission!</h1>
<p th:text="'Email: ' + ${email}" />
Submit another message
</body>
</html>
I also created a form object, add additional fields here if you want
public class SignUpForm {
//you can put some annotations here if you want for validating the email
//for e.g #NotEmpty or a #Pattern(regexp to validate the email)
private String email;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
and in the end your Controller. I pass the email from the signup post request to the result.html via a flash attribute:
#Controller
public class Controller1 {
#RequestMapping(value = "/signup", method= RequestMethod.GET)
public String signupForm(#ModelAttribute("signup") SignUpForm form) {
return "/signup";
}
#RequestMapping(value = "/signup", method= RequestMethod.POST)
public String signupSubmit(#ModelAttribute("signup") SignUpForm form, RedirectAttributes redirectAttributes) {
//validate form first -> check bindingResult documentation
//do what you need with your form object
redirectAttributes.addFlashAttribute("email", form.getEmail());
return "redirect:/result";
}
#RequestMapping(value = "/result", method= RequestMethod.GET)
public String result() {
return "/result";
}
}

eventpreventDefault() not working I need to show the results on same page

I have added the java script file in the html for a form and it is connected to the java file I want to show data on same page after submit i.e index.html but after the submission it takes me to the register page.
html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<title>Register form</title>
</head>
<body>
<form method="post" action="register">
Name:<input type="text" name="name" /><br/>
Email ID:<input type="text" name="email" /><br/>
Password:<input type="text" name="pass" /><br/>
<input type="submit" value="submit" />
<script type='text/javascript'>
/* attach a submit handler to the form */
$("#register").bind('submit',(function(event) {
/* stop form from submitting normally */
event.preventDefault();
/* get the action attribute from the <form action=""> element */
var $form = $( this ),
url = $form.attr( 'action' );
/* Send the data using post with element id name and name2*/
var posting = $.post( url, { name: $('#name').val(), email: $('#email').val(),pass: $('#pass').val() } );
/* Alerts the results */
posting.done(function( data ) {
alert('success');
});
});
</script>
</form>
</body>
</html>
The forms needs an id in order to be called with the query selector #register.
<form method="post" action="register" id="register">

(Unnecessary) markup in a Wicket form

While generating a simplistic form page using Wicket (version 7.5.0), I'm getting extra markup which seems unnecessary (a hidden field placed into a <div> with inline CSS):
<!DOCTYPE html>
<html xmlns:wicket="http://wicket.apache.org">
<head>
<meta charset="utf-8" />
<title>Apache Wicket Quickstart</title>
<link href='http://fonts.googleapis.com/css?family=Yanone+Kaffeesatz:regular,bold' rel='stylesheet' type='text/css' />
<link rel="stylesheet" href="mystyle.css" type="text/css" media="screen" title="Stylesheet"/>
</head>
<body>
<form method="post" wicket:id="ItemForm" id="ItemForm1" action="./tf?1-1.IFormSubmitListener-ItemForm">
<div style="width:0px;height:0px;position:absolute;left:-100px;top:-100px;overflow:hidden">
<input type="hidden" name="ItemForm1_hf_0" id="ItemForm1_hf_0" />
</div>
<p>
<label for="name">
<span>Item name:</span>
</label>
<input type="text" name="p::name" wicket:id="name" value="">
</p>
<p>
<label for="price">
<span>Item price:</span>
</label>
<input type="text" name="price" wicket:id="price" value="0">
</p>
<section>
<input type="submit" value="Submit">
</section>
</form>
</body>
</html>
The relevant Java class is:
// Package name and imports omitted
public final class ItemFormPage extends WebPage {
#EJB(name = "ejb/item")
Item it;
public ItemFormPage() {
Form f = new Form("ItemForm") {
#Override
public void onSubmit() {
setResponsePage(new ItemDisplay());
}
};
f.setDefaultModel(new CompoundPropertyModel(it));
f.add(new TextField("name"));
f.add(new TextField("price"));
add(f);
}
}
I'm new to Wicket, as is probably evident from the code. Is there a way to avoid generating the aforementioned seemingly unnecessary markup? In other words, am I missing something or should I report a bug?
This hidden input is used to submit the form with anchor-based components like SubmitLink.
For example, you have a Form and you want to have two ways to submit it (with different 2 buttons):
Form<Void> form = new Form<Void>("form") {
#Override
protected void onSubmit() {
// central form onSubmit
}
};
SubmitLink submitter1 = new SubmitLink("submitter1") {
#Override
public void onSubmit() {
System.out.println("submitter 1 called");
}
};
form.add(submitter1);
SubmitLink submitter2 = new SubmitLink("submitter2") {
#Override
public void onSubmit() {
System.out.println("submitter 2 called");
}
};
form.add(submitter2);
When you click any of the two submitters, its name will be put to that input, and Wicket will find the correct SubmitLink component and call its onSubmit().

Calling method onClick of Jsp form Jsp

I wish to call a method in JSP onClick, the method is on the same JSP inside scriptlet.
How should I archive this?
<%# page import="java.io.*,java.lang.*,java.util.*,java.net.*,java.util.*,java.text.*"%>
<%# page import="javax.activation.*,javax.mail.*,org.apache.commons.*"%>
<%# page import="javax.servlet.http.*,javax.servlet.*"%>
<%!
public String sendMail(String to, String sub, String msg) {
String res = null;
System.out.println("HI");
return res;
}%>
<html>
<head>
<title>Send Email using JSP</title>
</head>
<body>
<center>
<h1>Send Email using JSP</h1>
</center>
<form>
<label>Email To</label><br />
<input type="text" name="to" /><br />
<label>Subject</label><br />
<input type="text" name="sub" /><br />
<label for="body">Message</label><br />
<input type="text" name="msg" /><br />
<input type="submit" onClick="sendMail( to, sub, msg )"/>
</form>
</body>
</html>
Note
The methods name is "sendMail", It's called on submit button
I want to do the whole code in JSP only.
The onclick event occurs when the user clicks on an element. This attribute has the ability to call JS functions (front end)
In your case, you want to call a JAVA function (server side) so the best way is to move the java code to a servlet and use it.
Anyway if you want to keep the JAVA function in the jsp, you can do this via ajax in this way
<script type="text/javascript">
$(document).ready(function() {
$('#sendMailBtn').click(function (){
$.ajax({
type: "post",
url: "/path",
data: "email=" + $('#email').val() + "&subject="+$('#subject').val() + "&msg=" + $('#msg').val(),
success: function(msg){
//
}
});
});
});
</script>
AJAX is a developer's dream, because you can
Update a web page without reloading the page
Request data from a server - after the page has loaded
Receive data from a server - after the page has loaded
Send data to a server - in the background
Check the full code here
<%# page import="java.io.*,java.lang.*,java.util.*,java.net.*,java.util.*,java.text.*"%>
<%# page import="javax.activation.*,javax.mail.*,org.apache.commons.*"%>
<%# page import="javax.servlet.http.*,javax.servlet.*"%>
<%!
public String sendMail(String to, String sub, String msg) {
String res = null;
System.out.println("HI");
return res;
}
%>
<html>
<head>
<title>Send Email using JSP</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
</head>
<body>
<center>
<h1>Send Email using JSP</h1>
</center>
<form>
<label>Email To</label><br />
<input id="email" type="text" name="to" /><br />
<label>Subject</label><br />
<input id="subject" type="text" name="sub" /><br />
<label for="body">Message</label><br />
<input id="msg" type="text" name="msg" /><br />
<input id="sendMailBtn" type="submit" />
</form>
</body>
<script type="text/javascript">
$(document).ready(function() {
$('#sendMailBtn').click(function (){
$.ajax({
type: "post",
url: "/path",
data: "email=" + $('#email').val() + "&subject="+$('#subject').val() + "&msg=" + $('#msg').val(),
success: function(msg){
//
}
});
});
});
</script>
</html>
For more information check
AJAX Introduction: http://www.w3schools.com/xml/ajax_intro.asp
onclick Event: http://www.w3schools.com/tags/ev_onclick.asp
JSP- Executes on Server.
JavaScript - executes in browser.
No you cannot call that JSP magically from JS. However you can send an Ajax request or post the form to jsp. BTW, I strongly suggest you to move the java code to a servlet and use it.
This is what I ended up doing
<%# page import= "java.io.*,java.lang.*,java.util.*,java.net.*,java.util.*,java.text.*"%>
<%# page import="javax.activation.*,javax.mail.*,org.apache.commons.*"%>
<%# page import="javax.servlet.http.*,javax.servlet.*"%>
<%!
public String sendMail(String to, String sub, String msg) {
String res = null;
System.out.println("HI");
return res;
}
%>
<%
String a = request.getParameter("to");
if(a != null){
sendMail(request.getParameter("to"),request.getParameter("sub"),request.getParameter("msg"));
}
%>
<html>
<head>
<title>Send Email using JSP</title>
</head>
<body><center>
<form action="#" method="post">
<label>Email To</label><br />
<input type="text" name="to" /><br /> <br />
<label>Subject</label><br />
<input type="text" name="sub" /><br /> <br />
<label for="body">Message</label><br />
<input type="text" name="msg" /><br /> <br />
<input type="submit"/>
</form>
</center></body>
</html>
The action="#" reloads the page, and there is a if condition which calls the required method if the parameter is not blank( Please keep in mind that by default on first call the parameter will be null ).

Categories

Resources