1. 啟動STS
2. File > New > Other
3. Spring > Spring Project > Next
4. 選擇 Spring MVC Project,並給定Project name
5. 最後給予package name就可以完成專案的建立了
6.為了執行這個專案,需要啟用Server
Window > Show View > Servers
7. 就會浮現Servers視窗了
8. 要使用Apache Tomcat, 至下載頁面http://tomcat.apache.org/download-70.cgi
下載apache-tomcat-7.0.56.exe
因為小編的電腦是windows 7 64bit,所以選了
9. 下載完apache-tomcat-7.0.56.exe後點兩下安裝起來,要記得安裝到哪個目錄去了
10. 回到STS
File > New > Other
11. 這會兒要設定Tomcat。選擇Server > Server > Next
12. Apache > Tomcat v7.0 Server > Add
13. 按下Browse選擇剛剛安裝apache-tomcat-7.0.56.exe的目錄 > Finish
14. 再次File > New > Other
15. 再次Server > Server > Next
16. Apache > Tomcat v7.0 Server > Next
17. 將Spring MVC Project加入Configured清單 > Finish
18. 在Servers視窗出現我們所需要的東西了
19. 在Tomcat v7.0 Server at localhost上滑鼠按右鍵 > Start
20. 若Start後出現像下面這樣的錯誤訊息,表示Tomcat已經被開啟使用了,在此我們無法用它
21. 找到被使用中的Tomcat,關掉它
在工作列右下角打開箭頭,Tomcat的icon滑鼠按右鍵,「Stop service」
22. 回到步驟19.再次執行,如果沒跳錯誤的話
23.開一個瀏覽器,url輸入http://localhost:8080/mvc2/
總網頁瀏覽量
基礎Note
☪About Me
(1)
免費軟體
(2)
教學
(4)
教學文件
(42)
會計軟體
(1)
電腦系統
(1)
Adapter
(8)
Adobe Premiere
(1)
AlertDialog
(7)
Android App 介紹
(1)
Animation
(1)
API
(2)
APP範例
(1)
Array
(1)
AsyncTask
(1)
Auto Test Case
(32)
AutoCompleteTextView
(1)
Bitmap Drawable
(3)
BroadcastReceiver
(4)
Button
(1)
Codility
(2)
Contact
(4)
DB
(1)
Dialog
(2)
Documents
(1)
Eclipse
(3)
Ellipsize
(1)
File
(4)
Focus
(2)
Fragment
(4)
Gallery
(2)
GIT
(4)
GitHub
(1)
GridView
(8)
HashMap
(1)
HorizontalScrollView
(6)
IIS
(1)
Intent
(3)
IntentService
(1)
Internet
(2)
KeyEvent
(1)
Layout
(1)
ListView
(11)
Log
(1)
Mac / iOS
(11)
Manifest
(1)
Marquee
(2)
Math
(1)
MediaPlayer
(5)
MediaRecorder
(5)
MSMQ
(1)
onClick
(1)
PackageManager
(6)
PHP
(1)
PIS
(3)
PowerManager
(1)
Progress
(2)
SCREEN
(1)
Search
(6)
Service
(1)
SharedPreferences
(3)
SimpleDateFormat
(1)
SonarQube
(1)
Sound Recorder
(1)
Spinner
(2)
SQL server Management
(16)
SQLite
(13)
String
(1)
STS
(5)
SVN
(1)
Thread
(1)
Toast
(3)
Typeface
(1)
Uri
(2)
VB.NET
(17)
VMware
(1)
關於我自己
2014年10月30日 星期四
2014年10月20日 星期一
JUnit4 淺淺入門教學
→前置作業:安裝STS&可建立Gradle Project←
(STS&Gradle Project非絕對必要,在此僅以此建立範例)
一、專案建立
(1) File > New > Project
(2) Gradle > Gradle Project
(3) 輸入Project name(自取),Sample project選Java Quickstart
二、設定JUnit
(1) 專案按右鍵 > Build Path > Configure Build Path
(2) Libraries > Add Library
(3) 選到JUnit > Next
(4) 選擇JUnit 4 > Finish
(5) 新增好JUnit 4
三、建立測試檔案
(1) src/main/java/按右鍵 > New > Package
(2) src/main/java/按右鍵 > New > Package
前述建立的package按右鍵 > New > Class
四、 編寫測試程式
(1) 建立一個method
package com.tsots.junit;
public class JunitTest {
public class TestNum{
public boolean isBigger(int num) {
System.out.println("傳入"+num);
int origin = 555;
if(num > origin){
return true;
//return "Yes";
}else{
return false;
}
}
}
}
(2) 加上@Test表示這是一個測項,記得
import org.junit.Assert;
import org.junit.Test;
@Test
public void test1(){
TestNum testNum = new TestNum();
Assert.assertEquals(true, testNum.isBigger(567));
}
@Test
public void test2(){
TestNum testNum = new TestNum();
Assert.assertEquals(true, testNum.isBigger(123));
}
(3) 欲測試的.java上按滑鼠右鍵 > Run As > JUnit Test
(4) 看結果
這裡告訴你第28行呼叫的method回傳了false,所以在此JUnit Test呈現fail
五、更多應用
@Before :表示會在每一個@test前先執行一次
@After :表示會在每一個@test後再執行一次
@BeforeClass :表示會在執行class前會先執行一次
@AfterClass :表示執行完class後會執行一次
(1) 加上@BeforeClass、@Before、@AfterClass、@After,記得
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
@BeforeClass
public static void beforeClass(){
System.out.println("beforeClass");
}
@Before
public void before(){
System.out.println("before");
}
@AfterClass
public static void afterClass(){
System.out.println("afterClass");
}
@After
public void after(){
System.out.println("after");
}
(2) 欲測試的.java上按滑鼠右鍵 > Run As > JUnit Test
(3) 看結果
通常會在
1. @Before
setUp()←初始化物件
2. @Test
測試方法
3. tesrDown()←釋放測試下物件
(STS&Gradle Project非絕對必要,在此僅以此建立範例)
一、專案建立
(1) File > New > Project
(2) Gradle > Gradle Project
(3) 輸入Project name(自取),Sample project選Java Quickstart
二、設定JUnit
(1) 專案按右鍵 > Build Path > Configure Build Path
(2) Libraries > Add Library
(3) 選到JUnit > Next
(4) 選擇JUnit 4 > Finish
(5) 新增好JUnit 4
三、建立測試檔案
(1) src/main/java/按右鍵 > New > Package
(2) src/main/java/按右鍵 > New > Package
前述建立的package按右鍵 > New > Class
四、 編寫測試程式
(1) 建立一個method
package com.tsots.junit;
public class JunitTest {
public class TestNum{
public boolean isBigger(int num) {
System.out.println("傳入"+num);
int origin = 555;
if(num > origin){
return true;
//return "Yes";
}else{
return false;
}
}
}
}
(2) 加上@Test表示這是一個測項,記得
import org.junit.Assert;
import org.junit.Test;
@Test
public void test1(){
TestNum testNum = new TestNum();
Assert.assertEquals(true, testNum.isBigger(567));
}
@Test
public void test2(){
TestNum testNum = new TestNum();
Assert.assertEquals(true, testNum.isBigger(123));
}
(3) 欲測試的.java上按滑鼠右鍵 > Run As > JUnit Test
(4) 看結果
這裡告訴你第28行呼叫的method回傳了false,所以在此JUnit Test呈現fail
五、更多應用
@Before :表示會在每一個@test前先執行一次
@After :表示會在每一個@test後再執行一次
@BeforeClass :表示會在執行class前會先執行一次
@AfterClass :表示執行完class後會執行一次
(1) 加上@BeforeClass、@Before、@AfterClass、@After,記得
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
@BeforeClass
public static void beforeClass(){
System.out.println("beforeClass");
}
@Before
public void before(){
System.out.println("before");
}
@AfterClass
public static void afterClass(){
System.out.println("afterClass");
}
@After
public void after(){
System.out.println("after");
}
(2) 欲測試的.java上按滑鼠右鍵 > Run As > JUnit Test
(3) 看結果
通常會在
1. @Before
setUp()←初始化物件
2. @Test
測試方法
3. tesrDown()←釋放測試下物件
2014年10月14日 星期二
STS(Spring Tool Suite) 建立 Gradle Project
- 修改 STS.ini , 看看Xmx要不要加大C:\xxx\3.6.1\sts-bundle\sts-3.6.1.RELEASE\STS.ini
- STS.ini加上下列預設值, 避免 gradle2 的 bug
-Dosgi.configuration.area.default=null
-Dosgi.user.area.default=null
-Dosgi.user.area=@user.dir - 啟動 STS
- 建立一個gradle project
File > New > Project
Gradle > Gradle Project
輸入 Project name
Sample project選Java Quickstart
*此時新建好的Gradle Project沒error(紅字)
- 下載新的build.gradle
https://www.evernote.com/shard/s386/sh/343c559e-2422-46a6-9fdb-72ccc3570dc9/844b3db026522687/res/0cb7e2d5-552f-45b7-b3be-ac8f0f5b4398/build.gradle - 找到剛建立Gradle project位置
例如:C:\使用者\xxxx\Documents\workspace-sts-3.6.2.RELEASE\GP - 蓋過原始的 build.gradle
- project上按右鍵 > Gradle > Reflash All
就會開始下載相依 lib
要注意 : 不要用公司OA網路, proxy怪怪的
下載成功後看到如下訊息
*此時新建好的Gradle Project有error(紅字)
project滑鼠按右鍵>Gradle>在Gradle點一下enable DSL support紅字就不見ㄌ- 設定Spring ide 相關開發界面
- Window > preferences > spring > Validation > Project Validator > 展開Bean Validator > Annotation-based Autowiring Rule 打勾
- 專案按右鍵 > Properties > 展開Spring > Beans Support > 找到Config Files > Enable support for <import/> element in configuration files 打勾
- 專案按右鍵 > spring > beans support > 找到Config Detection > Auto detection for annotated Java Spring configuration files 打勾
- 就可以在 spring perspective 看到bean, requestmapping 等列表
- 建立package : 在src/main/java點滑鼠右鍵>New>Package>取名為 tw.net.xxxxxxx.api2.hello
- 在tw.net.xxxxxxx.api2.hello點滑鼠右鍵>New>Class>取名為HelloController
- 內容:
- package tw.net.xxxxxxx.api2.hello;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class HelloController {
@RequestMapping("/hello/{who}")
public @ResponseBody String hello(
@PathVariable String who,
@RequestParam(value = "gender", required = false, defaultValue = "Mr.") String gender,
Model model) {
return " hello " + gender + ' ' + who;
} - }
- 說明:
- method 直接回傳 String , 並說它是@ResponseBody
- @PathVariable 用來收url內嵌變數
- @RequestParam 用來收request變數
- 在tw.net.xxxxxxx.api2.hello點滑鼠右鍵>New>Class>取名為Application
- 內容:
- package tw.net.xxxxxxx.api2.hello;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan
// @EnableAutoConfiguration
@EnableAutoConfiguration(exclude = { DataSourceAutoConfiguration.class })
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
// TODO Auto-generated method stub
}
}
- 說明:
- (src/main/java/tw/net/mymusic/api2/Application.java)
- 指定它可以宣告設定 : @Configuration
- 指定它可以自動掃描 bean : @ComponentScan
- 指定它可以以預設直補齊相關config :@EnableAutoConfiguration
- @EnableAutoConfiguration (exclude = { DataSourceAutoConfiguration. class })
因為沒有datasource設定或使用內建db , 所以先把 datasource自動 config 停掉
project按右鍵 > run as > Spring boot app
-
- 沒給 server port , 預設就是 8080, 直接點下列url, 會觸發Application開啟browser網頁
- http://127.0.0.1:8080/hello/Yung?gender=Miss
- http://127.0.0.1:8080/hello/Bedding
-


- build 一個含embedded tomcat 的 runnable jar
- 專案按右鍵 > Gradle > Task Quick Launcher > 輸入 build > enter後會產生錯誤訊息
- There were failing tests. See the report at: file:///home/freeman/workspace_STS/GP/build/reports/tests/index.html
Could not execute build using Gradle distribution 'https://services.gradle.org/distributions/gradle-2.1-bin.zip'. - 解法:開啟~\workspace-sts-3.6.2.RELEASE\GP2\gradle.build
- 在最下面加上一段
- dependencies {
compile group: 'commons-collections', name: 'commons-collections', version: '3.2'
testCompile group: 'junit', name: 'junit', version: '4.+'
} - 回到STS, 專案按右鍵 > Gradle > Refresh All
- 專案按右鍵 > Gradle > Task Quick Launcher > 輸入 build > 按下enter鍵
- *如果還是出現error, 關掉STS重新開啟, 再重複一次步驟
- 成功後在專案\build\lib\可看到產生api2-xxxxxxx-server-0.1.0.jar
-

- 第二種測試方法:用不同的啟動參數測試
- 打開命令提示字元 > 路徑切換至 ~\專案\build\lib\
- 輸入java -Dserver.port=8888 -jar api2-xxxxxxx-server-0.1.0.jar
- C:\Users\使用者\Documents\workspace-sts-3.6.2.RELEASE\GP3\build\libs>java -
Dserver.port=8888 -jar api2-xxxxxxx-server-0.1.0.jar
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v1.1.6.RELEASE) - 測試url就要用http://127.0.0.1:8888/hello/Justin Lee
- 輸入java -Dserver.port=8880 -jar api2-xxxxxxx-server-0.1.0.jar測試
- 測試url就要用http://127.0.0.1:8880/hello/Methanna?gender=Miss
專案/src/main/resources建立application.propertie,內容
#spring.thymeleaf.cache=false
#server.port=${xxxxxxx.api.port}
#management.port=${xxxxxxx.adm.port}
#management.address=127.0.0.1
# Data Source
spring.datasource.url=jdbc:mysql://127.0.0.1:8306/shop_queue
spring.datasource.username=demoo
spring.datasource.password=123456
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.max-active=50
spring.datasource.max-idle=10
spring.datasource.min-idle=10
spring.datasource.initial-size=10
datasource.secondary.url=jdbc:mysql://127.0.0.1:8306/yii_test
datasource.secondary.username=demoo
datasource.secondary.password=123456
datasource.secondary.driverClassName=com.mysql.jdbc.Driver
datasource.secondary.max-active=50
datasource.secondary.max-idle=10
datasource.secondary.min-idle=10
datasource.secondary.initial-size=10
專案/src/main/java建立封包tw.net.xxxxxxx.api2.hello.cfg再建DataSourceConfig.java
package tw.net.xxxxxxx.api2.hello.cfg;
import javax.sql.DataSource;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.core.JdbcTemplate;
@Configuration
public class DataSourceConfig extends DataSourceAutoConfiguration {
@Bean(name = "ds2")
@ConfigurationProperties(prefix = "datasource.secondary")
public DataSource secondaryDataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "jdbc2")
public JdbcTemplate jdbcTemplate2(DataSource ds2) {
return new JdbcTemplate(ds2);
}
}
結果就像下面這樣

接著在專案/src/main/java/tw.net.xxxxxxx.api2.hello/建立HelloDao.java,內容
package tw.net.xxxxxxx.api2.hello;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
@Repository
public class HelloDao {
private Log logger = LogFactory.getLog(getClass());
@Autowired
private JdbcTemplate jdbcTemplate;
@Autowired
@Qualifier("jdbc2")
private JdbcTemplate jdbc2;
public String getListFromDsDefault() {
String rtn = "";
List<Map<String, Object>> results = (List<Map<String, Object>>) jdbcTemplate
.queryForList("SELECT bat_no FROM order_import_detail LIMIT 5");
for (Map<String, Object> result : results) {
String batNo = (String) result.get("bat_no");
rtn += (batNo + "<br>");
}
return rtn;
}
public String getListFromDsDefault2() {
String rtn = "";
List<Map<String, Object>> results = (List<Map<String, Object>>) jdbc2
.queryForList("SELECT username,email FROM tbl_user LIMIT 5");
for (Map<String, Object> result : results) {
String username = (String) result.get("username");
String email = (String) result.get("email");
rtn += (username + " >> " + email + "<br>");
}
return rtn;
}
}
至於Application.java也稍做修改
package tw.net.xxxxxxx.api2.hello;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan
@EnableAutoConfiguration
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
// TODO Auto-generated method stub
}
}
若成功會開啟網頁如下
若失敗則會讀不出網頁內容
用 Junit 測試 Bean
1. 先於 專案/src/test/java/建立package名為tw.net.xxxxxxx.api2.hello2. 於專案/src/main/java/tw.net.xxxxxxx.api2.hello/HelloDao.java上按右鍵
New > JUnit Test Case > (1)選「New JUnit 4 test」 (2)選「Browse」路徑要專案/src/test/java (3)按「Next」去選擇要測試的項目
(4) 「Finish」後, 專案/src/test/java/tw.net.xxxxxxx.api2.hello/就會產生HelloDaoTest.java了
3. 於專案/src/main/java/tw.net.xxxxxxx.api2.hello/HelloContorller.java上按右鍵
New > JUnit Test Case > (1)選「New JUnit 4 test」 (2)選「Browse」路徑要專案/src/test/java (3)按「Next」去選擇要測試的項目 (4) 「Finish」後, 專案/src/test/java/tw.net.xxxxxxx.api2.hello/就會產生HelloContorllerTest.java了
4.但我們需要去修改HelloContorllerTest.java為
package tw.net.xxxxxxx.api2.hello;
import static org.junit.Assert.*;
import org.apache.http.HttpStatus;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.IntegrationTest;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import com.jayway.restassured.RestAssured;
import static com.jayway.restassured.RestAssured.*;
import static com.jayway.restassured.matcher.RestAssuredMatchers.*;
import static org.hamcrest.Matchers.*;
import tw.net.mymusic.api2.Application;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@WebAppConfiguration
@IntegrationTest("server.port:0")
public class HelloControllerTest {
@Value("${local.server.port}")
int port;
@Before
public void setUp() throws Exception {
RestAssured.port = port;
}
@Test
public void testHello() {
// fail("Not yet implemented");
// hello/Eleanor?gender=Miss
// when().get("/hello/Eleanor").then().assertThat().statusCode(HttpStatus.SC_OK);
given().param("gender", "Miss").param("key2", "value2").when()
.get("/hello/Eleanor").then().assertThat()
.statusCode(HttpStatus.SC_OK)
.body(containsString("hello Miss Eleanor"));
}
}
5. 在HelloContorllerTest.java上按右鍵Run As > 4 JUnit Test ,檢視視窗如下,看有沒有執行成功
6. .body(containsString("hello Miss Eleanor"));←這個字串與http://127.0.0.1:8080/hello/Eleanor?gender=Miss網頁執行的結果一樣,就是Pass;若不一樣,5.則是Fail
#################電腦關掉重啟後#######################
1.
- 打開命令提示字元 > 路徑切換至 ~\專案\build\lib\
- 輸入java -Dserver.port=8888 -jar api2-xxxxxxx-server-0.1.0.jar
- C:\Users\使用者\Documents\workspace-sts-3.6.2.RELEASE\GP3\build\libs>java -
Dserver.port=8888 -jar api2-xxxxxxx-server-0.1.0.jar
2. STS>在HelloContorllerTest.java上按右鍵Run As > 4 JUnit Test ,檢視視窗如下,看有沒有執行成功
3. 開啟網頁http://127.0.0.1:8888/hello/Eleanor?gender=Miss看有無成功
2014年9月24日 星期三
STS (Spring Tool Suite) 建立專案
【Maven Project】
File→New→Maven Project→v Use default workspace location→maven-archetype-quickstart
【Spring Project】
File→New→Spring Project→Simple Spring Utility Project→Run As→Java Application
【Spring MVC(Model-View-Control) Project】
File→New→Spring Project→Spring MVC Project
> 專案滑鼠右鍵 > Run As > Run on Server
若建立好的Spring MVC Project有紅字,可能是資源檔沒下載完全
(1)至.m2/搜尋.lastUpdated←所有的.lastUpdated檔皆刪除→專案砍掉重建→STS關掉重開
(2)確保網路連線順暢,不要用有proxy的網路
(3) 到http://repo.maven.apache.org/maven2/org/apache/maven/plugins/maven-resources-plugin/2.6/下載
maven-resources-plugin-2.6.jar.md5
maven-resources-plugin-2.6.jar.sha1
maven-resources-plugin-2.6.jar
maven-resources-plugin-2.6.pom.sha1
maven-resources-plugin-2.6.pom.md5
maven-resources-plugin-2.6.pom
至.m2/repository/org/apache/maven/plugins/maven-resources-plugin/2.6/←若無2.6/就自己新建
File→New→Maven Project→v Use default workspace location→maven-archetype-quickstart
【Spring Project】
File→New→Spring Project→Simple Spring Utility Project→Run As→Java Application
【Spring MVC(Model-View-Control) Project】
File→New→Spring Project→Spring MVC Project
> 專案滑鼠右鍵 > Run As > Run on Server
![]() |
| 成功後看到這樣的畫面 |
若建立好的Spring MVC Project有紅字,可能是資源檔沒下載完全
(1)至.m2/搜尋.lastUpdated←所有的.lastUpdated檔皆刪除→專案砍掉重建→STS關掉重開
(2)確保網路連線順暢,不要用有proxy的網路
(3) 到http://repo.maven.apache.org/maven2/org/apache/maven/plugins/maven-resources-plugin/2.6/下載
maven-resources-plugin-2.6.jar.md5
maven-resources-plugin-2.6.jar.sha1
maven-resources-plugin-2.6.jar
maven-resources-plugin-2.6.pom.sha1
maven-resources-plugin-2.6.pom.md5
maven-resources-plugin-2.6.pom
至.m2/repository/org/apache/maven/plugins/maven-resources-plugin/2.6/←若無2.6/就自己新建
訂閱:
文章 (Atom)










































