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>
The methods name is "sendMail", It's called on submit button I want to do the whole code in JSP only.
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 ).