Try calling JavaScript in Java

Introduction

This time, I will practice how to use JavaScript in a Java application. There are two ways to practice JavaScript in JSP and practice in Java files.

Development environment

eclipse tomcat java

Execute JS with JSP file

IndexServlet.java index.jsp main.js Will be created.

image.png

It is such a hierarchy.

servlet.IndexServlet.java


package servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class IndexServlet
 */
@WebServlet("/IndexServlet")
public class IndexServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public IndexServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.getWriter().append("Served at: ").append(request.getContextPath());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

Jakarta is OK with no touch. (Because the purpose is to execute JS with JSP)

index.jsp


<%@ page language="java" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>index</title>
</head>
<style>
.box1 {
    width: 200px;
    height: 200px;
    background-color: #ccffcc;
}
.box2 {
  width: 200px;
  height: 200px;
  background-color: #ddd;
}
</style>
<body>
	<h1>JS execution confirmation in JSP</h1>
	<div class="box1">box1</div>

	<div class="box2">box2</div>

	<form action="IndexServlet" method="post">
User ID:<input type="text" name="user_id" id="user_id">
password:<input type="password" name="pass" id="pass">
      <input type="submit" value="Login" id="btn">
  	</form>
  <input type="button" value="See password" id="passshow">
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="main.js"></script>
</body>
</html>

・ A box that changes color when clicked ・ Box that changes color with mouse hover ・ Login form validation We will implement the three.

main.js


/* ---------Processing when clicked---------*/
$('.box1').on('click', (e) => {
	$(e.target).css({'background-color': 'skyblue' });
});
/*  ------What to do when you hover your mouse----------*/
const onMouseenter = (e) => {
  $(e.target).css({
    'background-color': '#ff9999',
  });
};
const onMouseleave = (e) => {
  $(e.target).css({
    'background-color': '#dddddd',
  });
};
$('.box2')
  .on('mouseenter', onMouseenter)
  .on('mouseleave', onMouseleave);
/*--------Make your password visible--------------*/
$('#passshow').on('click', () => {
  $('#pass').attr('type', 'text');
});
/*----------Set validation at login(If it is blank, play)----------- */
$('#btn').on('click', (e) => {
  const id = $('#user_id').val();
  const pass = $('#pass').val();
  if(!id){
    e.preventDefault();
    console.log(id);
    alert('ID is blank');
  }
  if(!pass){
    e.preventDefault();
    console.log(pass);
    alert('Password is blank');
  }
})

I was able to implement JS as described above. (I was able to implement it exactly as it was in HTML.)

Run JS in Java file

Next, I will introduce one of the methods to execute JS in a Java file. All the explanations are in the code, so please have a look. .. ..

The code below describes the following pages of Oracle's Java Documentation Guide. https://docs.oracle.com/javase/jp/8/docs/technotes/guides/scripting/prog_guide/api.html

test.java


import java.io.File;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

public class test {

	public static void main(String[] args) throws Exception{
		//Create a ScripteEnginManager instance
		ScriptEngineManager factory = new ScriptEngineManager();
		//Specify the JS script engine with the getEngineByName method of the ScripteEngineManager instance
		ScriptEngine engine = factory.getEngineByName("JavaScript");

		//Utilization of JS engine---------------------------------
		//Display on console ・ Evaluate script as JS statement
		engine.eval("print('Hello World')");

	//Class java for reading character files.io.You can execute each JS file by using FileReader
		//When the same package is in the same hierarchy
		File file1 = new File("src/test.js");
		engine.eval(new java.io.FileReader(file1));
		//When in the resources folder at the same level as src
		File file2 = new File("resources/test.js");
		engine.eval(new java.io.FileReader(file2));

		//put (key name,You can save the source code in the key name with (source code)
		engine.put("file", file1);
		//Get absolute path with getAbsolutePath ・ Evaluate script as JS statement
		engine.eval("print(file.getAbsolutePath())");

		//Functions can be assigned to variables
		String script1 = "function helle(name) { print('Hello' + name);}";
		//Call by variable name(Stored in engine)-Evaluate the script as a JS statement
		engine.eval(script1);
		//Call a function or method stored in engine. → Functions can be executed * Invocable means that it can be called
		Invocable inv1 = (Invocable) engine;
		//This time it's a function, so invokeFunction("Function name to be called", "argument")Can be executed with
		inv1.invokeFunction("helle", "Taro");

		//"obj"Create an object called"obj"Also define the method of the object
		String script2 = "var obj = new Object(); "
				+ "obj.goodbye = function(name){print('Goodbye' + name + 'Mr.');}";
		//Save to engine ・ Evaluate script as JS statement
		engine.eval(script2);
		//Make engine callable
		Invocable inv2 = (Invocable) engine;
		//Get the object that has the method you want to call (make it workable)
		Object obj1 = engine.get("obj");
		//This time it's a method, so invokeMethod(Object name, "Method name", "argument")Run on
		inv2.invokeMethod(obj1, "goodbye", "Jiro");

	//Script functions can be handled as methods of the Runnable interface ・ Can be used globally
		//Function generation with no arguments
		String script3 = "function run() { print('java.lang.Call the Runnable interface'); }";
		//Make the script evaluateable and callable as a JS statement
		engine.eval(script3);
		Invocable inv3 = (Invocable) engine;
		//Get Runnable (interface) and implement script function (inv3) as method r1
		Runnable r1 = inv3.getInterface(Runnable.class);
		//Create by passing method r1 to Thread object (where Runnable interface is implemented)
		Thread th1 = new Thread(r1);
		//Start execution
		th1.start();


		//Method generation with no arguments
		String script4 = "var obj = new Object();"
				+ "obj.run = function() {print('Calling the Runnable method');}";
		//Evaluated as a script
		engine.eval(script4);
		//Allow obj to be treated as an object
		Object obj2 = engine.get("obj");
		//Make it callable
		Invocable inv4 = (Invocable) engine;
		//Get Runnable (interface) and implement script function (inv4) as method r2
		Runnable r2 = inv4.getInterface(obj2, Runnable.class);
		//Created by passing method r1 to Thread object (where Runnable interface is implemented)
	    Thread th2 = new Thread(r2);
	    th2.start();

	}
}

Finally

If you can combine Java and JS as introduced this time, it seems that you can create more dynamic pages.

Recommended Posts

Try calling JavaScript in Java
Try calling the CORBA service in Java 11+
Try using RocksDB in Java
Try developing Spresense in Java (1)
Try functional type in Java! ①
Try calling synchronized methods from multiple threads in Java
Try implementing Android Hilt in Java
Java, JavaScript, C # (difference in assignment)
Try running Selenuim 3.141.59 in eclipse (java)
Try an If expression in Java
Try running AWS X-Ray in Java
Try to implement Yubaba in Java
Try to solve Project Euler in Java
Partization in Java
Try to implement n-ary addition in Java
Call Java method from JavaScript executed in Java
Try using the Stream API in Java
Try Java 8 Stream
Changes in Java 11
Let's try WebSocket with Java and javascript!
Using JavaScript from Java in Rhino 2021 version
Rock-paper-scissors in Java
Try using JSON format API in Java
Use "Rhino" which runs JavaScript in Java
Java and JavaScript
Try making a calculator app in Java
Try calling Nim from Java via JNI
Pi in Java
Roughly try Java 9
FizzBuzz in Java
Try scraping about 30 lines in Java (CSV output)
Try to create a bulletin board in Java
Try calling the CORBA service from Spring (Java)
Second decoction: Try an If expression in Java
Try using Sourcetrail (win version) in Java code
Try using GCP's Cloud Vision API in Java
Differences in writing Java, C # and Javascript classes
Try using Sourcetrail (macOS version) in Java code
Try using the COTOHA API parsing in Java
Interpreter implementation in Java
Make Blackjack in Java
Rock-paper-scissors app in Java
Constraint programming in Java
Put java8 in centos7
NVL-ish guy in Java
"Hello World" in Java
Callable Interface in Java
Try using JSON format API in Java
Comments in Java source
Azure functions in java
Try LetCode in Ruby-TwoSum
Format XML in Java
Simple htmlspecialchars in Java
Boyer-Moore implementation in Java
Hello World in Java
Use OpenCV in Java
webApi memorandum in java
Type determination in Java
Ping commands in Java
Various threads in java
Heapsort implementation (in java)