Call a jsp function by submitting a form - html

I want to execute a jsp function when a submit button is clicked. Here's what I'm trying to do:
<form>
<input type="text" id="input">
<input type="submit" onClick="(I want the function to be here)">
</form>
<#!
public static void get(){
String s = request.getParameter("input");
System.out.println(s);
}
(I have simplified the code, if you don't understand please let me know.)
I don't really know if this is possible in anyway, I have been searching and I have seen suggestions on similar cases of using AJAX, but I'm not familiar with it and if there is a simpler solution it would be so much easier.
Edit: I just wanted to specify that the function I'm trying to call isn't this simple, I simplified. The actual function uses code that only Java can run (using a Java library).

This is how you can make a simple ajax request from your jsp file to some java code:
Returning String as plain text
The jsp page:
<!DOCTYPE html>
<html lang="en">
<head>
<title>SO question 4112686</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).on("click", "#somebutton", function() { // When HTML DOM "click" event is invoked on element with ID "somebutton", execute the following function...
$.get("someservlet", function(responseText) { // Execute Ajax GET request on URL of "someservlet" and execute the following function with Ajax response text...
$("#somediv").text(responseText); // Locate HTML DOM element with ID "somediv" and set its text content with the response text.
});
});
</script>
</head>
<body>
<button id="somebutton">press here</button>
<div id="somediv"></div>
</body>
</html>
Servlet doGet() method:
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String text = "some text";
//you can write whatever java code you want to have here, and you can pass the results to the jsp file through the response writer. (text) This will only work from simple strings. If you want to pass more complicated information like lists or objects you will need to convert it to a json object
response.setContentType("text/plain"); // Set content type of the response so that jQuery knows what it can expect.
response.setCharacterEncoding("UTF-8"); // You want world domination, huh?
response.getWriter().write(text); // Write response body.
}
If you want to do it in a form you can do it like this:
Ajaxifying an existing form
<form id="someform" action="someservlet" method="post">
<input type="text" name="foo" />
<input type="text" name="bar" />
<input type="text" name="baz" />
<input type="submit" name="submit" value="Submit" />
</form>
<script>
$(document).on("submit", "#someform", function(event) {
var $form = $(this);
$.post($form.attr("action"), $form.serialize(), function(response) {
// ...
});
event.preventDefault(); // Important! Prevents submitting the form.
});
</script>
Servlet:
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String foo = request.getParameter("foo");
String bar = request.getParameter("bar");
String baz = request.getParameter("baz");
//do some java stuff here
//then return whatever you want
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8"); /
response.getWriter().write("hello world");
}
Examples taken from: How to use Servlets and Ajax

The onClick() function is meant to be used for JavaScript or JavaScript frameworks, you can do what you are trying to do with JS.
In JS create a function with a parameter, then, the onClick() will look like this
onClick="(myFunction(variableName))"
Inside myFunction(variableName) should look like this
myFunction(variableName){
alert("The variable is: " +variableName);
}
alert("The variable is: " +variableName); will create like a pop up at the top of the webpage showing your variable value.

You can try with this code:
if(request.getParameter("btnSubmit")!=null) //btnSubmit is the name of your button, not id of that button.
{
java.util.Date d = new java.util.Date();
System.out.println(d.toString());
}
<input type="submit" id="btnSubmit" name="btnSubmit" value="Execute Test"/>
Source: onClick function call using scriptlet

Related

How can i get response coming from web server

i have a form, i am asking customer to enter few details,
<form id="redirectForm" accept-charset="UTF-8" method="post" action="https://test.test.com//api/v1/order/create" >
customerName: <input type="text" name="customerName" value=<%=customerName %> />
customerEmail: <input type="text" name="customerEmail" value=<%=customerEmail %> /><br><br>
customerPhone: <input type="text" name="customerPhone" value=<%=customerPhone %> /><br><br>
signature:<input type="text" name="signature" value=<%=signature %> />
On submit page redirect according to action of form and display a JSON type response(status + payment link).
response is like:
{"status":"OK","paymentLink":"https:\/\/test.test.com\/billpay\/order\/3ackwtoyn7oks4416fomn"}
Help me out with this
i am working in jsp.
thank you in advance.
Since this look like a simple Webservice answer (not a full HTML page), I would use Ajax to send the form and manage the response.
With JQuery, this is easy using $.ajax
$.ajax({
url: //the URL
data: //the form value
method: //GET/POST
success: function(response){
//decode the JSON response...
var url = $.parseJSON(response).paymentLink;
//then redirect / not sure since this could be cross-domain...
window.loacation = url;
},
error: function(error){
...
}
})
The only think is that the form should not be send with a submit input, you need to link a button to a function doing this Ajax call.
This can be done without JQuery but I can write this from memory ;)
If you can edit the JSP creating the response, you could generate an HTML to return the value directly.
<html>
<head>
<script>
window.location.href = '${paymentLink}';
</script>
</head>
<body>
Redirection ...
<br>If nothing happend, you can <a href='${paymentLink}'>click here</a> to be redirected.
</body>
</html>
Where ${paymentLink} is a EL that will print the value of this variable (well the name it has on the server) to complete the script with the URL.
Once it is received by the client, it will be executed.
Of course, this will not be cross-domain on every browser. If this is not, you will need to provide the link to the user with <a href='${paymentLink}'>Redirection</a> itsefl.
Try this...
while submitting the form write one JS function and get the URL value.
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
function check(){
//here you have to get value using element name or id (val1,val2,val3)
$.ajax({
type:'GET',
data: {customerName: val1, customerEmail: val2,customerPhone: val3},
url:'https://test.test.com/billpay/order/3ackwtoyn7oks4416fomn',// Replace with Your Exact URL
success: function(response){
alert(response);
var json = JSON.parse(response);
var values = json.values;
for(var i in values)
{
var New_redirect = values[i].address;
alert(values[i].address);
}
window.loacation=New_redirect;
}
});
})
}
</script>
</head>
i think you are looking for response message and redirecting to somewhere
if so you can use the following code
if(condition)
{
response.sendRedirect("urpage.jsp");
}
or
if(condition)
{
request.getRequestDispacher("page.jsp");//enter the name of page you want to redirect inside ""
}

HTML file not working within a GWT/GXT project

The following code is working fine when I run it by itself but when I run it from within a widget in my project the alert does not show up. Am I doing something wrong or forgetting to do something?
<html>
<head>
<title>Upload</title>
<script>
function test() {
alert("Works");
}
</script>
</head>
<body>
<input type='file' size='30' id='fileDiag' maxlength='45'
name='fileDiag'>
<input type="button" onclick="test()" value="TEST" />
</body>
</html>
Try replacing the content of your widget's HTML with just this:
<input type='file' size='30' id='fileDiag' maxlength='45' name='fileDiag'>
<input type="button" onclick="test()" value="TEST" />
<script>
function test() {
alert("Works");
}
</script>
You also shouldn't place JavaScript function directly in your widget's html. You can either create it using a UiBinder and specify a handler using #UiHandler in your UiBinder class, or create a class that extends a Composite and then use a XTemplates as follows:
public interface WidgetTemplates extends XTemplates {
#XTemplate(source = "content.html")
SafeHtml content();
}
Then in your widget's constructor you can add the template's content:
WidgetTemplates templates = GWT.create(WidgetTemplates.class);
public class MyWidget extends Composite {
public MyWidget() {
HTMLPanel rootPanel = new HTMLPanel(templates.content());
initWidget(rootPanel);
sinkEvents(Event.ONCLICK);
}
public void onBrowserEvent(Event evt) {
// handler for all events
}
}
I didn't fully test the above code, but you might get the general idea. You want to code the GWT way, not to circumvent it.

Very simple spring MVC button click

I have the following code in my SampleController;
#Controller
public class SampleController {
#RequestMapping("home")
public String loadHomePage(Model m) {
m.addAttribute("name", "CodeTutr");
return "home";
}
#RequestMapping(value="/test", method=RequestMethod.GET)
public String handlePost(#RequestParam String action, Model m) {
if( action.equals("save") ){
//handle save
}
else if( action.equals("renew") ){
//handle renew
}
m.addAttribute("name", "change");
return "home";
}
}
on page load the attribute I set it successful shown on the web page. I am trying to get my head around button clicks on spring mvc below is my jsp code;
<!DOCTYPE HTML>
<html>
<head>
<title>Sample Application</title>
</head>
<body>
<h1>Hello, ${name}!</h1>
<input type="submit" name="action" value="save" />
</body>
</html>
My input does not do anything, the method handlePost is never hit. I was trying to change the attribute "name" to the word "change", I am not sure what I am doing incorrectly.
Your issue isn't with Spring, it's with HTML. You cannot submit a button. You can only submit a <form>.
Wrap your <input> element in a <form>
<form action="<c:url value="/test" />" method="GET">
<input type="submit" name="action" value="save" />
</form>
Where <c:url> is the url tag of the core taglib. Now, when you click the button, the browser will serialize your <input> elements as url-encoded form parameters and send them. They will appear as request parameters to your server/web application. Spring will deserialize them by name and inject them as arguments where you have a #RequestParam method parameter.
There needs to be a form encapsulating your input.
General FYI: Your "save" and "renew" use cases should be separate controller actions.
Also consider removing "POST" from your action name. Seeing as the action is decorated with GET, and the html is saying its GET

How to send JSON object/string (as 'POST') to a webservice using $resource in angularjs

I'm an absolute newbie in angularjs and don't have any idea about web services either.
My requirement is something like this:
I'll have a basic login page (to be designed using html and angularjs) which is going to ask for my credentials (Username and Password). On providing a set of credentials and clicking on the "Submit" button, my code needs to process the form data and pass the information on to a webservice. I just have the url of the webservice with me and nothing else.
Thus my principal objective would be to send across the username and password to the webservice (preferably as a JSON object) and check whether its working properly or not. So far, I've successfully managed to:
1> Hit the webservice (I've used $resource for doing the same.)
2> Store the username and password as a JSON object.
Now I need to accomplish two things:
1> send this data as "POST" and most importantly, 2> send this JSON data(as an object or string) to the webservice.
I'm absolutely clueless...Please help me out by modifying my code.
Thanks in advance. Here's my JS file:
var app = angular.module('angularjs-starter', ['ngResource']);
app.controller('MainCtrl', function ($scope,$http,$resource) {
$http.defaults.useXDomain = true;
$scope.checkUsername = function(){
var USERNAME = $scope.inputUsername;
var PASSWORD = $scope.inputPassword;
var f = JSON.stringify({USERNAME: USERNAME, PASSWORD: PASSWORD });
var result= JSON.parse(f);
var Something = $resource("/some url/:id", {id: "#id"},
{
post:{
method:"POST",
isArray:false
},
});
$scope.something = Something.get({id:1});
$scope.alertMessage = "Web service has been successfully hit!";
};
});
And here's my HTML file:
<!DOCTYPE html>
<html ng-app="angularjs-starter">
<head lang="en">
<meta charset="utf-8">
<title>Authentication</title>
<script src="C:\Users\Rup\Desktop\POC2\js\angular.js"></script>
<script src="C:\Users\Rup\Desktop\POC2\js\angular-resource.js"></script>
<script src="C:\Users\Rup\Desktop\POC2\experiment_2.js"></script>
<link rel="stylesheet" href="style.css">
</head>
<body ng-controller="MainCtrl">
<h1>Hello</h1>
<form name="form1" class="form-horizontal">
<label class="control-label" for="inputUsername">Username</label> <input
type="text" id="inputUsername" placeholder="Username"
ng-model="inputUsername"> <br /> <label
class="control-label" for="inputPassword">Password</label> <input
type="password" id="inputPassword" placeholder="Password"
ng-model="inputPassword"> <br /> <span class="help-block">{{alertMessage}}</span>
<br />
<!--<a class="btn">Sign in</a>-->
<button ng-click="checkUsername()">Submit</button>
</form>
</body>
</html>
The good news is that this should be fairly straight forward. You have the right idea, you just need to extend the resource object as you have done with "post" method, and when you call it - pass in your JSON object. Angular will then append the passed in JSON object as post parameters automatically. It's a good idea (I've read), to create this User resource as a service/factory so that you can inject it into your controllers to abstract the calls to the server. As an example - something I have done would be to create the service like so (with a dependency on the angular $resource):
var myApp = angualar.module('myApp', []);
myApp.factory('UserService', ["$resource",
function UserService($resource) {
var UserService = $resource('/rest/user', {}, {
search: {
method: 'POST',
url: window.location.origin +'/yourServer/rest/search' //custom url of your service to be called
}
});
return UserService;
}
])
Then in your controller, you inject the service to be used, and create a method that then calls your shiny new service:
myApp.controller("myAppController", ["$scope", "UserService",
function myAppCtrl($scope, UserService) {
$scope.search = function () {
var params = {
param1: "searchValue1",
param2: "searchValue2"
}
var response = UserService.search(params);
response.$promise.then(
function success() {
//celebrate!
},
function fail(err) {
//comiserate
}
);
}
}
The response object from the call to the service method is a promise, which you attach your success or fail functions to be called when the call successfully returns or fails.

HTML file not posting GET parameters in a GET request

I am trying a simple program with Java Servlet wherein a HTML page with a text box and a submit button will be displayed. Once the user enters the data and submits it, the next page will display a Hello . Calling the servlet URL with the GET parameter directly shows that it works fine. But when I open the HTML file and submit data from there, the GET request isn't formed properly, i.e. the parameters are not getting passed in the address of the 'action' URL.
Here is the HTML code:
<!DOCTYPE html>
<html>
<head>
<title>Hello</title>
</head>
<body>
<form action="/TestServlt/TestClass" name="myform" method="get">
Enter your name: <input type="text name="username">
<br />
<input type="submit" value="Go">
</form>
</body>
</html>
and the servlet code:
package in.lguruprasad;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class TestClass extends HttpServlet implements Servlet {
static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter output = response.getWriter();
response.setContentType("text/html");
String name = request.getParameter("username");
output.println("Hello "+name+"!");
output.flush();
output.close();
}
}
The servlet is mapped to /TestServlt/TestClass URL and the form submit redirects http://localhost:8080/TestServlt/TestClass instead of http://localhost:8080/TestServlt/TestClass?username=<user input> which would work fine. The output I get is 'Hello null!'.
In all the browsers the form submits without the get parameter. I tried writing a similar doPost method, but that didn't work as well.
What is the issue here and how to fix it?
I am using Eclipse 3.1.2, Apache Tomcat 5.5, JDK 1.6.25 if that helps.
You are missing a quote in the html input:
Enter your name: <input type="text name="username">
should be
Enter your name: <input type="text" name="username">