STSからwebサーバー

サーバーにプロジェクトを追加
Pivotal tc Server Developer Edition…
Add and Remove

スタートアイコンよりサーバーを起動
http://localhost:8080/MySampleWebApp1/

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>org.springframework.samples.service.service</groupId>
  <artifactId>MySampleWebApp1</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  
    <properties>

		<!-- Generic properties -->
		<java.version>1.6</java.version>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		
		<!-- Web -->
		<jsp.version>2.2</jsp.version>
		<jstl.version>1.2</jstl.version>
		<servlet.version>2.5</servlet.version>
		

		<!-- Spring -->
		<spring-framework.version>3.2.3.RELEASE</spring-framework.version>

		<!-- Logging -->
		<logback.version>1.0.13</logback.version>
		<slf4j.version>1.7.5</slf4j.version>

		<!-- Test -->
		<junit.version>4.11</junit.version>

	</properties>
	
	<dependencies>
	
		<!-- Spring MVC -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${spring-framework.version}</version>
		</dependency>
		
		<!-- Other Web dependencies -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>${jstl.version}</version>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>${servlet.version}</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet.jsp</groupId>
			<artifactId>jsp-api</artifactId>
			<version>${jsp.version}</version>
			<scope>provided</scope>
		</dependency>
	
		<!-- Logging with SLF4J & LogBack -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>${slf4j.version}</version>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>ch.qos.logback</groupId>
			<artifactId>logback-classic</artifactId>
			<version>${logback.version}</version>
			<scope>runtime</scope>
		</dependency>
		
		<!-- Test Artifacts -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>${spring-framework.version}</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>${junit.version}</version>
			<scope>test</scope>
		</dependency>

	</dependencies>	
</project>

web.xml

<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         id="WebApp_ID" version="2.5">

    <display-name>MySampleWebApp1</display-name>
    
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring/application-config.xml</param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    
</web-app>
package jp.spring.websample1;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Component;

@Component
public class MyBean {
	private List<String> messages = new ArrayList<String>();
	
	public MyBean() {
		super();
		messages.add("This is Bean sample.");
	}
	
	public void addMessage(String message) {
		messages.add(message);
	}
	
	public String getMessage(int n) {
		return messages.get(n);
	}
	
	public void setMessage(int n, String message) {
		messages.set(n, message);
	}
	
	public List<String> getMessage(){
		return messages;
	}
	
	public void setMessages(List<String> messages) {
		this.messages = messages;
	}
	
	@Override
	public String toString() {
		String result = "MyBean [\n";
		for(String message : messages) {
			result += "\t'" + message + "'\n"; 
		}
		result += "]";
		return result;
	}
}

Create Spring Bean Configuration File

bean.xmlを生成します。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">


</beans>

beanを追加

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

<bean id="mybean1" class="jp.spring.sample1.MyBean">
	<property name="message" value="this is sample bean!"></property>
</bean>
</beans>

app.javaを書き換えます

package jp.spring.sample1;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class App {

	private static ApplicationContext app;
	
	public static void main(String[] args) {
		app = new ClassPathXmlApplicationContext("bean.xml");
		MyBean bean = (MyBean)app.getBean("mybean1");
		System.out.println(bean);
	}
}

spring beanの利用

classを作ります。

package jp.spring.sample1;

import java.util.Calendar;
import java.util.Date;

public class MyBean {
	private Date date;
	private String message;
	
	public MyBean() {
		super();
		this.date = Calendar.getInstance().getTime();
	}
	public MyBean(String message) {
		this();
		this.message = message;
	}
	
	public Date getDate() {
		return date;
	}
	
	public void setMessage(String message) {
		this.message = message;
	}
	
	@Override
	public String toString() {
		return "MyBean [message=" + message + ", date=" + date + "]";
	}

}

App.java

package jp.spring.sample1;

public class App {

	public static void main(String[] args) {
		MyBean bean = new MyBean("This is Bean Sample!");
		System.out.println(bean);
	}
}

console

MyBean [message=This is Bean Sample!, date=Thu Jan 18 14:03:34 JST 2018]

maven class

\MySampleApp1\src\main\java\jp\spring\sample1

package jp.spring.sample1;

/**
 * Hello world!
 *
 */
public class App 
{
    public static void main( String[] args )
    {
        System.out.println( "Hello World!" );
    }
}

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>jp.spring.sample1</groupId>
  <artifactId>MySampleApp1</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>MySampleApp1</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
</project>

Java Springのコア機能

Dependency Injection
あるクラスの処理が、他の特定のクラスに依存している状態を解消することがDIの目的です。

それでは、mavenでプロジェクトを作成していきます。
コマンドプロンプトでmvnコマンドを実行します。

>mvn archetype:generate

Define value for property 'groupId': jp.spring.sample1
Define value for property 'artifactId': MySampleApp1
Define value for property 'version' 1.0-SNAPSHOT: :
Define value for property 'package' jp.spring.sample1: :
Confirm properties configuration:
groupId: jp.spring.sample1
artifactId: MySampleApp1
version: 1.0-SNAPSHOT
package: jp.spring.sample1
 Y: :
[INFO] ----------------------------------------------------------------------------
[INFO] Using following parameters for creating project from Old (1.x) Archetype: maven-archetype-quickstart:1.1
[INFO] ----------------------------------------------------------------------------
[INFO] Parameter: basedir, Value: C:\Users\***\Desktop
[INFO] Parameter: package, Value: jp.spring.sample1
[INFO] Parameter: groupId, Value: jp.spring.sample1
[INFO] Parameter: artifactId, Value: MySampleApp1
[INFO] Parameter: packageName, Value: jp.spring.sample1
[INFO] Parameter: version, Value: 1.0-SNAPSHOT
[INFO] project created from Old (1.x) Archetype in dir: C:\Users\***\Desktop\MySampleApp1
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 10:03 min
[INFO] Finished at: 2018-01-17T15:32:23+09:00
[INFO] Final Memory: 14M/75M
[INFO] ------------------------------------------------------------------------

Spring Framework 5.0とMaven

Springは、Apache Software Foundationが開発するJavaプロジェクト管理ツール「Apache Maven」に対応しています。Mavenは、コマンドラインでプロジェクト管理を行えるツールです。

Maven
https://maven.apache.org/

https://maven.apache.org/download.cgi
「Binary zip archive」のLink「apache-maven-3.5.2-bin.zip」からダウンロードします。

適当な場所に保存して、環境変数のpathに追加します。
C:\apache-maven-3.5.2\bin
※「\bin」を忘れずに

コマンドプロンプトで「mvn -v」でバージョンを確認してみましょう。

>mvn -v
Apache Maven 3.5.2 (138edd61fd100ec658bfa2d307c43b76940a5d7d; 2017-10-18T16:58:13+09:00)
Maven home: C:\apache-maven-3.5.2\bin\..
Java version: 1.8.0_121, vendor: Oracle Corporation
Java home: C:\Program Files\Java\jre1.8.0_121
Default locale: ja_JP, platform encoding: MS932
OS name: "windows 10", version: "10.0", arch: "amd64", family: "windows"

ヴァージョンが表示されれば、正常に動いています。

Spring Framework 5.0とSprint Tool Suiteのダウンロード

Spring5の対応JDKは、JDK8(ver 1.8)で、それ以前のversionは未対応となっています。コマンドラインで確認してください。

>java -version
java version "1.8.0_121"
Java(TM) SE Runtime Environment (build 1.8.0_121-b13)
Java HotSpot(TM) 64-Bit Server VM (build 25.121-b13, mixed mode)

続いて、Spring Tool Suite(STS)をダウンロードします。
https://spring.io/tools/sts

DOWNLOAD STSをクリックしてダウンロードします。


– sts-3.9.2.RELEASE がSTS本体フォルダ
– Pivotal-tc-server-develop-3.2.8…. が開発用のJavaサーバープログラム。STS内から起動して使う
– legalフォルダ ライセンス情報など

STSプログラムは、sts-xxxフォルダ内にあるSTS.exeを起動して利用します。

loop

public void beep()

public boolean checkAlarm()

public void alarm(){
	boolean on = checkAlarm();
	while(on){
		beep();
		on = checkAlarm();
	}

}
String googol = "1";
int len = googol.length();
while(len < 101){
	googol = googol + "0";
	len = googol.length();
}

while loop

public int keepRolling(){
	int dice1 = rollDice();
	int dice2 = rollDice();
	int count = 1;
	while(!(dice1 == dice2)){
		dice1 = rollDice();
		dice2 = rollDice();
		count = count + 1;
	}
	return count;
}
public void raiseAlarm(int numOfWarnings){
	int i = 1;
	while(i <= numOfWarnings){
		System.out.println("warning");
		i = i + 1;
	}
}
public void raiseAlarm(int numOfWarnings){
	for (int i = 1; i <= numOfWarnings; i++){
		System.out.println("Warning");
	}
}

pyramid

public int countBlocks(int levels){
	int sum = 0;
	for(int i = 1; i <= levels; i++)
	{
		sum = sum + i * i; 
	}
    return sum;
}
public int martingale(){
	int money = 1000;
	int target = 1200;
	int bet = 10;
	while(money>bet){
		boolean win = play();
		if(win){
			money += bet;
			bet = 10;
		}
		else {
			money -= bet;
			bet *= 2;
		}
	}
	return money;
}

Function

public void println(String x){
	if(x == null){
		x = "null";
	}
	try {
		ensureOpen();
		textOut.write(x);
	} catch(IOException e){
		trouble = true;
	}
	newLine();
}
boolean playButton; 

public void playMusic(){
    if (playButton){
        System.out.println("Music is playing");
    } else {
    	System.out.println("Music is paused");
    }
}

parameter and argument

public void greeting(String location){
	System.out.println("Hello, " + location);
}
public int likePhoto(int currentLikes, String comment, boolean like){
	System.out.println("Feedback: "+ comment);
	if(like){
		currentLikes = currentLikes + 1;
	}
	System.out.println("Number of likes: " + currentLikes);
	return currentLikes;
}
public double makeChange(double itemCost, double dollarsProvided){
	double change = dollarsProvided - itemCost;
	return change;
}

random number

double randomNumber = Math.random();
randomNumber = randomNumber * 10;
int randomInt = (int) randomNumber;
public int rollDice(){
	double randomNumber = Math.random();
	randomNumber = randomNumber * 6 + 1;
	int randomInt = (int) randomNumber;
	return randomInt;
}

java documentation
https://docs.oracle.com/javase/8/docs/api/java/lang/package-summary.html

Math.random()
https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#random–

self driving car

boolean isLightGreen = true;
boolean isLightYellow = false;

if(isLightGreen){
	double carSpeed = 100;
	System.out.println("Drive!");
	System.out.println("Speed is:" + carSpeed);
} else if(isLightYellow) {
	System.out.println("Slow down.");
} else {
	System.out.println("Stop.");
}

museum ticket

int ticketPrice = 10;
int age = ;
boolean isStudent = ;

if (age <= 15){
	// age is less than or eaual to 15
	ticketPrice = 5;
} else if(age > 60) {
	ticketPrice = 5;
} else if(isStudent) {
	ticketPrice = 5;
}
System.out.println(ticketPrice);

logical operators
age <= 15 || age > 60 || isStudent

if(action && romance){

	System.out.println("this movie include action and romance")
	if(comedy || horror){
		System.out.println("this movie include comedy or horror")
	}
}

switch

int passcode = ;
String coffeeType;
switch(passcode){
	case 555: coffeeType = "Espresso";
		break;
	case 312: coffeeType = "Vanilla latte";
		break;
	case 629: coffeeType = "Drip coffee";
		break;
	default: coffeeType = "Unknown";
		break;
}
System.out.println(coffeeType);