Very simple spring MVC button click - html

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

Related

Call a jsp function by submitting a form

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

Polymer- using custom element in other projects like angular and Java jsp

I am trying to create custom form element which I am trying to reuse in other applications developed in angular and jsp page of Java
my-element.js:
class MyElement extends HTMLElement {
// This gets called when the HTML parser sees your tag
constructor() {
super(); // always call super() first in the ctor.
this.msg = 'Hello, World!';
}
// Called when your element is inserted in the DOM or
// immediately after the constructor if it’s already in the DOM
connectedCallback() {
this.innerHTML = `<form action="/action_page.php">
<div class="container">
<label><b>Name</b></label>
<input type="text" placeholder="Enter Email" name="email" required>
<label><b>Age</b></label>
<input type="text" placeholder="Enter Age" name="age" required>
<div class="clearfix">
<button type="button" class="cancelbtn">Cancel</button>
<button type="submit" class="signupbtn">Add</button>
</div>
</div>
</form>`;
}
}
// This registers your new tag and associates it with your class
window.customElements.define('my-element', MyElement);
my-element.html:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script src="https://cdn.rawgit.com/download/polymer-cdn/1.5.0/lib/webcomponentsjs/webcomponents-lite.js"></script>
<link rel="import" href="https://cdn.rawgit.com/download/polymer-cdn/1.5.0/lib/polymer/polymer.html">
<link rel="import" href="https://cdn.rawgit.com/download/polymer-cdn/1.5.0/lib/iron-ajax/iron-ajax.html">
<script src="my-element.js"></script>
<!-- <link rel="import" href="add-form.html"> -->
</head>
<body>
<my-element></my-element>
</body>
</html>
Two issues I am struggling with now are below
1.Can i incude both the files as below to my angular and java jsp page and use custom tag to work?
<link rel="import" href="my-element.html">
<script src="my-element.js"></script>
<my-element></my-element>
I am trying to pass below json object as an attribute to custom form element and trying to render custom form elements
[
{
"name":"Name",
"type":"text",
"size":"20",
"readyOnly": false,
"validateFunction":"onlyText"
},
{
"name":"Age",
"type":"number",
"size":"3",
"readyOnly": false,
"validateFunction":"onlyNumber"
}
]
I tried using below way to inject json data to custom element to render form elements based on json but no luck and there are no console errors
<my-element form-data="{{data}}"></my-element>
ad 1) yes you can use your element with every server system you would like. It's "just html" that the beauty in it :)
ad 2)
HTMLElement won't do anything automatically. So if you wish to access your json you will have to do something like this
<my-element form-data="{'name': 'Name', 'type': 'text'}""></my-element>
connectedCallback() {
let rawData = this.getAttribute('form-data');
let jsonData = JSON.parse(rawData.replace(/'/g, '"'));
}
Notice that in the form-data json there are ' instead of ". So we have to replace them before using JSON.parse.
it looks like this is using a web component as opposed to a polymer component. The native web component API does not include data binding, although angular and polymer both do (but implemented in different ways).
Native web components and polymer components can be used with Angular as well as other frameworks.
Depending on whether you are using Angular.js(1) or Angular(2+), setting up the data object to be passed into the DOM will vary, but in general the data should be "set up" so to speak in the JS and passed into the DOM. Otherwise as #daKmoR said, the data would need to be declared as he did in his example.
There are packages that assist in implementing data 2-way binding between polymer's data bindings and angulars bindings if that is needed.
Trey

Store value in session variable in java script function on button click

I want to store rating value in jsp session variable inside the java script function for using in testOpeartion page
I tried this way but not storing any value "UserRating" session variable
<html>
<head>
<title>Registration Page</title>
<script type="text/javascript">
function SetRating()
{
var rating = document.getElementById("ratingValue").value;
<%
request.setAttribute("UsaerRating",rating);
%>
}
}
</script>
</head>
<body>
<form method="post" action="testOperation">
<input type="text" id="ratingValue" onclick="doDisplay(this);" />
<input type="Button" onclick="SetRating();" value="Set Rating"/>
<input type="submit" value="Submit"/>
</form>
</body>
</html>
From this link
It's not possible to set any session variables directly from
javascript as it is purely a client side technology. You can use AJAX
though to asyncronously send a request to a servlet running on the
server and then add the data to the session from within the servlet.
So you wouldn't be using javascript to do the actual setting of
session variables but it would look like it is.
You can also get more details from THIS LINK

Passing data from one page to another page using POST ASP

I want to pass the data from page to another using POST and display first name & last name on my second page. But instead of names it does display the actual code. PLease see the code below:
<html>
<head>
</head>
<body>
<FORM action="RetrieveData_Post.asp" id=form1 method=post name=form1>
First Name:
<br>
<INPUT id="txtFirstName" name="txtFirstName" >
<br>
Last Name:
<br>
<INPUT id="txtLastName" name="txtLastName" >
<br>
<INPUT type="submit" value="Submit">
</FORM>
</body>
</html>
This is the first page and the second page is:
<%# Language=VBScript %>
<html>
<head>
</head>
<body>
<%
Response.Write("First Name: " & Request.Form("txtFirstName") & "<br>")
Response.Write("Last Name: " & Request.Form("txtLastName") & "<br>")
%>
</body>
</html>
Create an html page Gatherdata_post.htm
<html>
<head>
</head>
<body>
<FORM action="RetrieveData_Post.asp" id=form1 method=post name=form1>
First Name:
<br>
<INPUT id="txtFirstName" name="txtFirstName" >
<br>
Last Name:
<br>
<INPUT id="txtLastName" name="txtLastName" >
<br>
<INPUT type="submit" value="Submit">
</FORM>
</body>
</html>
Save the page
Create an page Retrievedata_post.asp
<%# Language=VBScript %>
<html>
<head>
</head>
<body>
<%
Response.Write("First Name: " & Request.Form("txtFirstName") & "<br>")
Response.Write("Last Name: " & Request.Form("txtLastName") & "<br>")
%>
</body>
</html>
Run Gatherdata_post.htm by right-clicking the page and selecting View in browser.
In this way you can pass values
First, this assumes that you are running this on a server running IIS and not just double-clicking the HTML file. You need a server to process the actual code, and IIS is the most common server that will process Classic ASP.
Second, you need to make sure that ASP is enabled. Classic ASP is not enabled by default on IIS6+ (Technet)
In IIS Manager, expand the local computer, and then click Web Service Extensions.
In the details pane, click Active Server Pages, and then click Allow.
It may be a little different depending on the version of IIS you are running.
Source Page
The Source Page has an HTML Button with a jQuery Click event handler. When the Button is clicked, an HTML Form is created and appended to the BODY Tag of the page. The action is set to the Destination page (Page2.aspx). Using the AddParameter function values of the Name TextBox and the Technology DropDownList is appended to the Form as Hidden Fields and then the Form is submitted
<input type="button" id="btnPost" value="Send" />
<script type="text/javascript">
$(function () {
$("#btnPost").bind("click", function () {
//Create a Form
var $form = $("<form/>").attr("id", "data_form")
.attr("action", "Page2.aspx")
.attr("method", "post");
$("body").append($form);
//Append the values to be send
AddParameter($form, "name", $("#txtName").val());
AddParameter($form, "technology", $("#ddlTechnolgy").val());
//Send the Form
$form[0].submit();
});
});
function AddParameter(form, name, value) {
var $input = $("<input />").attr("type", "hidden")
.attr("name", name)
.attr("value", value);
form.append($input);
}
</script>
Destination Page
On the Destination page (Page2.aspx), in the Page Load event of the ASP.Net Page the values of the two posted fields are fetched and are printed on the page. The below code has been done in C# but similar can be done for other technologies.
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
if (!string.IsNullOrEmpty(Request.Form["name"]) && !string.IsNullOrEmpty(Request.Form["technology"]))
{
Response.Write("<u>Values using Form Post</u><br /><br />");
Response.Write("<b>Name:</b> " + Request.Form["name"] + " <b>Technology:</b> " + Request.Form["technology"]);
}
}
}
Pros:
Best in class as there is 100% guarantee of data being send that too in hidden form.
Pros: Best in class as there is 100% guarantee of data being send that too in hidden form.
Cons:
Requires Server side technology for fetching posted data.Requires Server side technology for fetching posted data.

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">