简体   繁体   中英

Java webpage execute script

I am new to Java, please help.

I wrote html page index.jsp that suppose to get value from user and execute a script with that value.

The code is-

 <body> <form name="Execute-Java" action=""> <p> <label for="s">IP- </label> <input type="text" name="server" value="xxxx"> </p><br> <input type="submit" value="Execute java" name="Submit"/> </form> </body> 

Also wrote a java code, compiled it using javac and ran it using java command-line successfully.

public class SendEmail {
  public static void main(String [] args){
  String from = "from@from.com";
  String to = "to@to.com";
  String subject = "Test Subject";
  String body_email = "Body test";
  String host = "x.x.x.x";

 //Get the session object
  Properties properties = System.getProperties();
  properties.setProperty("mail.smtp.host", host);
  Session session = Session.getDefaultInstance(properties);

 //compose the message
  try{
     MimeMessage message = new MimeMessage(session);
     message.setFrom(new InternetAddress(from));
     message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
     message.setSubject(subject);
     message.setText(body_email);

     // Send message
     Transport.send(message);
     System.out.println("message sent successfully....");

  }catch (MessagingException mex) {mex.printStackTrace();}

} }

Now i would like the index.jsp page to somehow execute the java code when user click submit using the host value given by the user.

Can it be done and what should i do?

If you want to do some calculations with user input from html (jsp) on server-side you should use Application-Layer protocol from OSI (HTTP, HTTPS fe) .

Approach - using Ajax send http request to Server (java-servlet resource, deployed on Tomcat or another servlet container). Or you may use default behavior of form.submit() .

Make SendEmail class an Servlet extending it from HTTPServlet, implement doPost method(or doGet), set address for servlet.

Set action and method attributes for form.

Submit form.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM