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 ).
Related
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">
I'm working on a simple java web app that displays a page in which you can add a new client and then it shows another pages that presents the client newly added but i keep getting this error:
HTTP Status 404 - /LearningJSP/AddClient
type Status report
message /LearningJSP/AddClient
description The requested resource is not available.
I don't get where the problem is.
Here are the files of my app.
the "add new client" .jsp
<%# page pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Création d'un client</title>
</head>
<body>
<div>
<form method="get" action="AddClient">
<fieldset>
<legend>Informations client</legend>
<label for="nomClient">Nom <span class="requis">*</span></label>
<input type="text" id="nomClient" name="nomClient" value="" size="20" maxlength="20" />
<br />
<label for="prenomClient">Prénom </label>
<input type="text" id="prenomClient" name="prenomClient" value="" size="20" maxlength="20" />
<br />
<label for="adresseClient">Adresse de livraison <span class="requis">*</span></label>
<input type="text" id="adresseClient" name="adresseClient" value="" size="20" maxlength="20" />
<br />
<label for="telephoneClient">Numéro de téléphone <span class="requis">*</span></label>
<input type="text" id="telephoneClient" name="telephoneClient" value="" size="20" maxlength="20" />
<br />
<label for="emailClient">Adresse email</label>
<input type="email" id="emailClient" name="emailClient" value="" size="20" maxlength="60" />
<br />
</fieldset>
<input type="submit" value="Valider" />
<input type="reset" value="Remettre à zéro" /> <br />
</form>
</div>
</body>
</html>
Servlet
package Controllers;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import Model.Client;
/**
* Servlet implementation class ClientServ
*/
public class ClientServ extends HttpServlet {
private static final long serialVersionUID = 1L;
public static final String Add = "/affichierClient.jsp";
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String Nom = request.getParameter("nomClient");
String Prenom = request.getParameter("prenomClient");
String Adresse = request.getParameter("adresseClient");
String Telephone = request.getParameter("telephoneClient");
String Email = request.getParameter("emailClient");
String message;
if(Nom.trim().isEmpty() || Adresse.trim().isEmpty() ||
Telephone.trim().isEmpty()) {
message="Vous n'avez pas rempli tous les champs";
}
else {
message="Client crée avec succès";
}
Client client = new Client();
client.setNom(Nom);
client.setPrenom(Prenom);
client.setAdresse(Adresse);
client.setEmail(Email);
client.setTelephone(Telephone);
request.setAttribute("client", client);
request.setAttribute("message", message);
this.getServletContext().getRequestDispatcher(Add).forward(request, response);
}
}
The jsp page to display the newly added client
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Affichage de client</title>
</head>
<body>
<p class="info"> ${message} </p>
<p>Nom: ${client.Nom}</p>
<p>Prenom: ${client.Prenom}</p>
<p>Adresse: ${client.Adresse}</p>
<p>Numéro de télephone: ${client.Telephone}</p>
<p>Email: ${client.Email}</p>
</body>
</html>
web.xml file
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<display-name>WebApp</display-name>
<servlet>
<servlet-name>AddClient</servlet-name>
<servlet-class>Controllers.ClientServ</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>AddClient</servlet-name>
<url-pattern>/AddClient</url-pattern>
</servlet-mapping>
</web-app>
It is likely that the problem comes from that line:
<form method="get" action="AddClient">
As you give a relative URL instead of an absolute one, it is used to build a full URL starting from the current one.
So if the previous URL was /LearningJSP the following request is sent to /LearningJSP/AddClient when it should use /AddClient ending in a normal 404 error.
Fix: just use an absolute URL:
<form method="get" action="/AddClient">
Read about how to create breakpoints in eclipse.
Place a breakpoint here
String Nom = request.getParameter("nomClient");
Read about how to start a debugging session in eclipse.
Start one. If The execution never stops at the breakpoint means the configuration is wrong. If it does stop, means that the 404 is thrown in a subsequent request.
If you only have doGet(...) handling requests then you probably have url path issues
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.
I'm unable to perform "delete" from the HTML form. This is my HTML, what's incorrect here? , also included the RESTservice method that performs deletion. I see the POST is getting invoked after every button click. Any inputs or suggestions ?
create_todo.html
<!DOCTYPE html>
<html>
<head>
<title>Form to create a new resource</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script>
document.getElementById("delete").addEventListener("click", function () {
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://localhost:8080/com.dcr.jersey.first/rest/todos", true);
xhr.setRequestHeader("Content-Type", "application/xml");
xhr.setRequestHeader("X-HTTP-Method-Override", "DELETE"); //X-HTTP-Method-Override
xhr.send();
},true);
</script>
</head>
<body>
<form id= "myForm" action="../com.dcr.jersey.first/rest/todos" method="post" >
<label for="id">ID</label>
<input name="id" />
<br/>
<label for="summary">Summary</label>
<input name="summary" />
<br/>
Description:
<TEXTAREA NAME="description" COLS=40 ROWS=6></TEXTAREA>
<br/>
<input type="submit" id="submit" value="Submit" /> <br/>
<button id="delete">Delete</button>
</form>
</body>
</html>
REST method for DELETE from form
#DELETE
#Produces(MediaType.TEXT_HTML)
#Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public void delTodo(#FormParam("id") String id,
#Context HttpServletResponse servletResponse) throws IOException {
Todo c = TodoDao.instance.getModel().remove(id);
if(c==null)
throw new RuntimeException("Delete: Todo with " + id + " not found");
else servletResponse.sendRedirect("../create_todo.html");
}
RESTResourceClient to post and delete which works fine
Form form = new Form();
form.param("id","45");
form.param("summary","Summary for id 45");
response = target.path("rest").path("todos").request().post(Entity.form(form));
System.out.println("\nPost by FORM response code is "+ response.getStatus()+"\n");
response = target.path("rest").path("todos/45").request().delete();
I am working in spring mvc, I am doing some jsp with showing multiple dropdowns in a single pages....
I seen an example to show drop down from database by using the following example.
<%# page import="java.util.*" %>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<jsp:useBean id="state" scope="session" class="src.StateDAO"/>
<html>
<head>
<title></title>
</head>
<body>
<form id="test" method="POST" action="">
<input name="state" type="radio" value="Australia" id="state-aus">Australia
<input name="state" type="radio" value="NewZealand" id="state-new">NewZealand
<input name="state" type="radio" value="India" id="state-oth" >India
<Select name="othStates" size="1" id="oth-states">
<c:forEach items="${state.stateList}" var="st">
<option value="1"><c:out value="${st.name}"/></option>
</c:forEach>
</select>
<br>
<input type="Submit" name="cmdSub" value="SUBMIT">
<input type="Reset" name="cmdReset" value="RESET">
</form>
</body>
</html>
Is this right way to do this to get dropdowns in jsp using Spring mvc?
I think that a better option is to use the spring tags for jsp
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
...
<form:select path="country">
<form:option value="NONE" label="--- Select ---" />
<form:options items="${countryList}" />
</form:select>
See full example here: http://www.mkyong.com/spring-mvc/spring-mvc-dropdown-box-example/
Edit:
$('#stateSelect').change(function() {
$.ajax({
type:"GET",
url : "/getCitiesForState",
data : { state: $('#stateSelect').val()},
success : function(data) {
$('#citySelect').empty(); //remove all child nodes
for(var i = 0; i < data.length; i++){
var newOption = $('<option value=data[i].value>data[i].text</option>');
$('#citySelect').append(newOption);
}
},
error: function() {
alert('Error occured');
}
});
});
On the server side you need an endpoint that respondes on the url(/getCitiesForState in the example) and returns a list of objects that have value and text properties.
Edit(add controlelr):
#Controller
public class HelloController{
#RequestMapping("/getCitiesForState")
#ResponseBody
public List<City> printHello(#RequestParam long state) {
List<City> cities = //get from the some repository by state
return cities;
}
}
public class City{
private String value;
private String text;
//getters setters
}