index.jspを作成する

index.jspファイルをつくります。なんだこれ、さすがに *.jsp は初めでだぞ。
つーか、なんだこれ、charsetがcharset=ISO-8859-1で、html4だ。

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!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>Hello, Java World!</title>
</head>
<body>
	<%= new java.util.Date() %>
</body>
</html>

JSPファイルはWebサーバ(ホームページのファイルを置くサーバ)上でお仕事をするJavaのプログラムで、HTMLファイルとJavaのプログラムが合体したもの

java server page そのままやんけ。
JSPファイルは基本的にはHTMLファイル
ただし、その中に、好きなようにJavaのコードを埋め込むことができる。

なるほど。
Java Servletが普通のJavaっぽい書き方になるのに対し、JSPファイルはPHPっぽい書き方になる。

なるほど、なるほど。

JSPファイルはjava servletに変換されるのね。

JSP Servletを動かそう

http://localhost:8080/TodoServlet3/HelloServlet

package todo.controller;

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 HelloServlet
 */
@WebServlet("/HelloServlet")
public class HelloServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public HelloServlet() {
        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);
	}

}

とりあえず、apache tomcatで動いています。
tomcatはJava Servletを動かすときに必要なソフト(サーブレットコンテナ)
chromeでも同じように動きます。

jdbc

JDBC (Java Database Connectivity) は、MySQLやPostgreSQLといった数々のSQLデータベース、あるいはスプレッドシートなどのデータファイルにJavaからアクセスするためのAPI。
アクセス先ごとに専用のドライバが提供されているため、事前にインストールしておく必要がある。

本家のサイトからMySQL Connectorsを押下する。

eclipseでweb開発をする

helpから行きます。

これでいいのかな?

入りました!!

servletの作成

run on servlet
tomcatが起動する。localhost:8080は404

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    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=UTF-8">
<title>Hello, World!</title>
</head>
<body>
    <%= new java.util.Date() %>
</body>
</html>

何故だ?ようわからん。。

Eclipseを使おう

txtファイルのエンコーディングを設定します。

Caluclation.java


package myPackage.calc;

public class Calculation {
protected int value = 0;
protected int result = 0;

/*
* 計算に使用する値を取得します。
* @return
*/
public int getValue() {
return value;
}
/*
* 計算に使用する値を設定します。
* @param value計算に使用する値
*/

public void setValue(int value) {
this.value = value;
}
/**
* 計算結果をコンソールに出力します。
*/

public void output(){
System.out.println(this.result);
}

}
[/java]

package myPackage.calc;

public class Square extends Calculation {
	
	/*
	 * 値を二乗します。
	 */
	public void calculate(){
		this.result = this.value * this.value;
		this.output();
	}

}
package myPackage.main;

import myPackage.calc.Square;

public class Program {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		Square square = new Square();
		
		square.setValue(Integer.parseInt(args[0]));
		square.calculate();

	}

}

Android studioにやや似ているから助かってるが、これどーしろっていうんだろう。。

Hash set

import java.util.*;

public class MyApp {

	public static void main(String[] args){
		// HashSet
		HashSet<Integer> sales = new HashSet<>();

		sales.add(10);
		sales.add(20);
		sales.add(30);
		sales.add(10);

		System.out.println(sales.size());

		for(Integer sale: sales){
			System.out.println(sale);
		}

		sales.remove(30);

		for(Integer sale: sales){
			System.out.println(sale);
		}
	}
}

[vagrant@localhost java]$ javac MyApp.java
[vagrant@localhost java]$ java MyApp
3
20
10
30
20
10

import java.util.*;

public class MyApp {

	public static void main(String[] args){
		
		// HashMap<String, Integer> sales = new HashMap<>();
		Map<String, Integer> sales = new HashMap<>();

		sales.put("tom", 10);
		sales.put("bob", 20);
		sales.put("steve", 30);

		System.out.println(sales.get("tom"));
		System.out.println(sales.size());

		for (Map.Entry<String, Integer> sale: sales.entrySet()){
			System.out.println(sale.getKey() + ":" + sale.getValue());
		}

		sales.put("tom", 100);
		sales.remove("steve");

		for (Map.Entry<String, Integer> sale : sales.entrySet()){
			System.out.println(sale.getKey() + ":" + sale.getValue());
		}
	}
}
import java.util.*;

public class MyApp {

	public static void main(String[] args){
		
		List<Integer> sales = new ArrayList<>(Arrays.asList(12, 30, 22, 4, 9));
		sales
			.stream()
			.filter(e -> e % 3 == 0)
			.map(e -> "(" + e + ")")
			.forEach(System.out::println);

		System.out.println();
	}
}
import java.time.*;
import java.time.format.DateTimeFormatter;

public class MyApp {

	public static void main(String[] args){
		LocalDateTime d = LocalDateTime.now();
		System.out.println(d.getYear());
		System.out.println(d.getMonth());
		System.out.println(d.getMonth().getValue());
		System.out.println(d.plusMonths(2).minusDays(3));
		DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy!MM!dd!");
		System.out.println(d.format(dtf));
	}
}

[vagrant@localhost java]$ javac MyApp.java
[vagrant@localhost java]$ java MyApp
2018
SEPTEMBER
9
2018-11-13T23:12:54.812
2018!09!16!

スレッド


class MyRunnable implements Runnable{
@Override
public void run(){
for (int i = 0; i < 500; i++){ System.out.print('*'); } } } public class MyApp { public static void main(String[] args){ MyRunnable r = new MyRunnable(); Thread t = new Thread(r); t.start(); for (int i = 0; i < 500; i++){ System.out.print('.'); } } } [/java] [vagrant@localhost java]$ java MyApp ..............................................................................................................................................******************************************************************************...................................................................................................................................................**********************************************************************************************************************************************************************************************************************************************...................................................................................................................................................................................................................**************************************************************************************************************************************************************************************** String class [java] public class MyApp { public static void main(String[] args){ String s = "abcdef"; System.out.println(s.length()); System.out.println(s.substring(2, 5)); System.out.println(s.replaceAll("ab", "AB")); String s1 = "ab"; String s2 = "ab"; if (s1.equals(s2)){ System.out.println("same!"); } String ss1 = new String("ab"); String ss2 = new String("ab"); if(ss1 == ss2){ System.out.println("same!same!same!"); } } } [/java] [java] public class MyApp { public static void main(String[] args){ int score = 50; double height = 165.8; String name = "yokoi"; System.out.printf("name: %s, score: %d, height: %f\n", name, score, height); System.out.printf("name: %-10s, score: %10d, height: %5.2f\n", name, score, height); } } [/java] [java] public class MyApp { public static void main(String[] args){ double d = 53.234; System.out.println(Math.ceil(d)); System.out.println(Math.floor(d)); System.out.println(Math.round(d)); System.out.println(Math.PI); } } [/java] [vagrant@localhost java]$ javac MyApp.java [vagrant@localhost java]$ java MyApp 54.0 53.0 53 3.141592653589793 Random処理 [java] Random r = new Random(); System.out.println(r.nextDouble()); System.out.println(r.nextInt(100)); System.out.println(r.nextBoolean()); [/java] [java] import java.util.*; public class MyApp { public static void main(String[] args){ // ArrayList sales = new ArrayList<>();
List sales = new ArrayList<>();

sales.add(10);
sales.add(20);
sales.add(30);

for(int i = 0; i < sales.size(); i++){ System.out.println(sales.get(i)); } sales.set(0, 100); sales.remove(2); for(Integer sale : sales){ System.out.println(sale); } } } [/java] [vagrant@localhost java]$ javac MyApp.java [vagrant@localhost java]$ java MyApp 10 20 30 100 20

イニシャライザー

class User {
	private String name;
	private static int count;

	static {
		User.count = 0;
		System.out.println("Static initializer");
	}

	public User(String name){
		this.name = name;
		User.count++;
		System.out.println("Constructor initializer");
	}

	{
		System.out.println("Instance initializer");
	}

	public static void getInfo(){
		System.out.println("# of instances: " + User.count);
	}
}

public class MyApp {

	public static void main(String[] args){
		User.getInfo();
		User tom = new User("Tom");
		User.getInfo();
		User john = new User("John");
		User.getInfo();
	}
}

[vagrant@localhost java]$ javac MyApp.java
[vagrant@localhost java]$ java MyApp
Static initializer
# of instances: 0
Instance initializer
Constructor initializer
# of instances: 1
Instance initializer
Constructor initializer
# of instances: 2

final は継承できない。

final class User {
	protected String name;
	private static final double VERSION = 1.1;

	static {
		this.name = name;
		User.VERSION = 1.2;
	}

	public final void sayHi{
		System.out.println("Hi! " + this.name);
	}

	public static void getInfo(){
		System.out.println("# of instances: " + User.count);
	}
}

抽象クラス

// 抽象クラス -> 具象クラス

abstract class User {
	public abstract void sayHi(); // 抽象メソッド
}

class JapaneseUser extends User {
	@Override
	public void sayHi(){
		System.out.println("こんにちは!");
	}
}

class AmericanUser extends User {
	@Override
	public void sayHi(){
		System.out.println("Hi");
	}
}

public class MyApp {

	public static void main(String[] args){
		AmericanUser tom = new AmericanUser();
		JapaneseUser aki = new JapaneseUser();
		tom.sayHi();
		aki.sayHi();
	}
}

[vagrant@localhost java]$ javac MyApp.java
[vagrant@localhost java]$ java MyApp
Hi
こんにちは!

interface

interface Printable{
	// 定数
	double VERSION = 1.2;
	// 抽象メソッド
	void print();
	// default メソッド
	public default void getInfo(){
		System.out.println("I/F ver. " + Printable.VERSION);
	} 
	// static メソッド

} 

class User implements Printable {
	@Override
	public void print(){
		System.out.println("Now printing user profile...");
	}
}

public class MyApp {

	public static void main(String[] args){
		User tom = new User();
		tom.print();
		tom.getInfo();
	}
}

[vagrant@localhost java]$ javac MyApp.java
[vagrant@localhost java]$ java MyApp
Now printing user profile…
I/F ver. 1.2

列挙型

enum Result {
	SUCCESS,
	ERROR,

}


public class MyApp {

	public static void main(String[] args){
		Result res;

		res = Result.ERROR;

		switch (res){
			case SUCCESS:
				System.out.println("OK!");
				System.out.println(res.ordinal());
			break;
			case ERROR:
				System.out.println("NG!");
				System.out.println(res.ordinal());
				break;
		}

		
	}
}

[vagrant@localhost java]$ java MyApp
NG!
1

例外処理

public class MyApp {

	public static void div(int a, int b){
		System.out.println(a / b);
	}

	public static void main(String[] args){
		div(3, 0);
	}
}

[vagrant@localhost java]$ java MyApp
Exception in thread “main” java.lang.ArithmeticException: / by zero
at MyApp.div(MyApp.java:13)
at MyApp.main(MyApp.java:17)

例外処理

class MyException extends Exception {
	public MyException(String s){
		super(s);
	}
}

public class MyApp {

	public static void div(int a, int b){

		try {
			if (b < 0){
				throw new MyException("not minux!");
			}
			System.out.println(a / b);
		} catch (ArithmeticException e){
			System.err.println(e.getMessage());
		} catch(MyException e){
			System.err.println(e.getMessage());
		}		
	}
	public static void main(String&#91;&#93; args){
		div(3, 0);
		div(5, -2);
	}
}
&#91;/java&#93;

Wrapper Class
&#91;java&#93;
public class MyApp {

	public static void main(String&#91;&#93; args){
		// Integer i = new Integer(32);
		// int n = i.intValue();
		Integer i = 32; // auto boxing
		i = null;
		int n = i; // auto unboxing
		System.out.println();
	}
}
&#91;/java&#93;

&#91;vagrant@localhost java&#93;$ javac MyApp.java
&#91;vagrant@localhost java&#93;$ java MyApp
Exception in thread "main" java.lang.NullPointerException
        at MyApp.main(MyApp.java:14)

型を後程指定するジェネリック
&#91;java&#93;
class MyData<T> {
	public void getThree(T x){
		System.out.println(x);
		System.out.println(x);
		System.out.println(x);
	}
}

public class MyApp {

	public static void main(String[] args){
		MyData<Integer> i = new MyData<>();
		i.getThree(32);
	}
}

[vagrant@localhost java]$ javac MyApp.java
[vagrant@localhost java]$ java MyApp
32
32
32

パッケージをコンパイルしよう

インポートって、要するに違うファイルからの読み込みね。すっかり忘れてる or スルーしてた。

package jp.hpscript.myapp;
import jp.hpscript.myapp.model.User;
import jp.hpscript.myapp.model.AdminUser;

public class MyApp {

	public static void main(String[] args){
		User tom = new User("Tom");
		// System.out.println(tom.name);
		tom.sayHi();

		AdminUser bob = new AdminUser("bob");
		// System.out.println(bob.name);
		bob.sayHi();
		bob.sayHello();
	}
}
package jp.hpscript.myapp.model;

public class User {
	protected String name;

	public User(String name){
		this.name = name;
	}

	public void sayHi(){
		System.out.println("hi!" + this.name);
	}
}
package jp.hpscript.myapp.model;

public class AdminUser extends User {
	public AdminUser(String name){
		super(name);
	}

	public void sayHello(){
		System.out.println("hello!" + this.name);
	}
	@Override public void sayHi(){
		System.out.println("[admin]hi!" + this.name);
	}	
}

[vagrant@localhost java]$ javac jp/hpscript/myapp/MyApp.java
[vagrant@localhost java]$ java jp.hpscript.myapp.MyApp
hi!Tom
[admin]hi!bob
hello!bob

setter, getter

class User {
	private String name;
	private int score;

	public User(String name, int score){
		this.name = name;
		this.score = score;
	}

	public int getScore(){
		return this.score;
	}

	public void setScore(int score){
		if(score > 0){
			this.score = score;
		}	
	}
}

public class MyApp {

	public static void main(String[] args){
		User tom = new User("Tom", 65);
		tom.setScore(85);
		tom.setScore(-22);
		System.out.println(tom.getScore());
	}
}
// static

class User {
	private String name;
	private static int count = 0;

	public User(String name){
		this.name = name;
		User.count++;
	}

	public static void getInfo(){
		System.out.println("# of instances: " + User.count);
	}
}

public class MyApp {

	public static void main(String[] args){
		User.getInfo();
		User tom = new User("Tom");
		User.getInfo();
		User john = new User("John");
		User.getInfo();
	}
}

java method

public static void sayHi(){
		System.out.println("Hi!");
	}

	public static void main(String[] args){
		sayHi();
	}
public static void sayHi(String name){
		System.out.println("Hi!" + name);
	}

	public static void main(String[] args){
		sayHi("Tom");
		sayHi("Bob");
	}

[vagrant@localhost java]$ javac MyApp.java
[vagrant@localhost java]$ java MyApp
Hi!Tom
Hi!Bob

public static String sayHi(String name){
		return "Hi!" + name;
	}

	public static void main(String[] args){
		String msg = sayHi("Steve");
		System.out.println(msg);
	}

[vagrant@localhost java]$ javac MyApp.java
[vagrant@localhost java]$ java MyApp
Hi!Steve

classを使ってみよう

class User {
	String name = "Me!";

	void sayHi(){
		System.out.println("hi!");
	}

}

public class MyApp {

	public static void main(String[] args){
		User tom;
		tom = new User();

		System.out.println(tom.name);
		tom.sayHi();
	}
}

[vagrant@localhost java]$ javac MyApp.java
[vagrant@localhost java]$ java MyApp
Me!
hi!

なるほど。

コンストラクタ

class User {
	String name;

	User(String name){
		this.name = name;
	}

	void sayHi(){
		System.out.println("hi!" + this.name);
	}

}

public class MyApp {

	public static void main(String[] args){
		User tom;
		tom = new User("Tom");

		System.out.println(tom.name);
		tom.sayHi();
	}
}

[vagrant@localhost java]$ javac MyApp.java
[vagrant@localhost java]$ java MyApp
Tom
hi!Tom

なるほど、何故か急に分かってきた。
classの継承

class User {
	String name;

	User(String name){
		this.name = name;
	}

	void sayHi(){
		System.out.println("hi!" + this.name);
	}
}

class AdminUser extends User {
	AdminUser(String name){
		super(name);
	}

	void sayHello(){
		System.out.println("hello!" + this.name);
	}	
}

public class MyApp {

	public static void main(String[] args){
		User tom = new User("Tom");
		System.out.println(tom.name);
		tom.sayHi();

		AdminUser bob = new AdminUser("bob");
		System.out.println(bob.name);
		bob.sayHi();
		bob.sayHello();
	}
}

@override 継承した時に親クラスのメソッドを使う

class User {
	String name;

	User(String name){
		this.name = name;
	}

	void sayHi(){
		System.out.println("hi!" + this.name);
	}
}

class AdminUser extends User {
	AdminUser(String name){
		super(name);
	}

	void sayHello(){
		System.out.println("hello!" + this.name);
	}
	@Override void sayHi(){
		System.out.println("[admin]hi!" + this.name);
	}	
}

public class MyApp {

	public static void main(String[] args){
		User tom = new User("Tom");
		System.out.println(tom.name);
		tom.sayHi();

		AdminUser bob = new AdminUser("bob");
		System.out.println(bob.name);
		bob.sayHi();
		bob.sayHello();
	}
}

[vagrant@localhost java]$ javac MyApp.java
[vagrant@localhost java]$ java MyApp
Tom
hi!Tom
bob
[admin]hi!bob
hello!bob
ほうほう