2017年6月23日星期五

[Controller/View]資料直接輸出JSON以及XML格式



1.  設定:
僅需在pom.xml加入Jackson相關的depnency

<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>${jackson.json.version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.dataformat</groupId> <artifactId>jackson-dataformat-xml</artifactId> <version>2.4.0</version> </dependency> <properties> <jackson.json.version>2.4.3</jackson.json.version> </properties>


2. 
接著新增@ResponseBody code到Controller,@RequestMapping中有個參數"produces",用來指定HTTP Content-type,如application/json或是application/xml,新增的code如下:

@Controller @RequestMapping("/dcn") public class DCNController { @Autowired private DCNRepository dcnRepository; ...... @RequestMapping(value="/jsonformat", produces="application/json") public @ResponseBody List restDCNListJson(Model model){ return dcnRepository.findAll(); } @RequestMapping(value="/xmlformat", produces="application/xml") public @ResponseBody List restDCNListXml(Model model){ return dcnRepository.findAll(); } }



3.   啟動Sever,JSON部分擷取畫面如下:



參考 :
http://ithelp.ithome.com.tw/articles/10159507

2017年6月20日星期二

JPA One-To-Many Relationship




  1.    One-To-Many Relationship 
  2. 在  BookCategory class 設定  One-To-Many  : 
@Entity
@Table(name = "book_category")
public class BookCategory {
    private int id;
    private String name;
    private Set<Book> books;

    @OneToMany(mappedBy = "bookCategory", cascade = CascadeType.ALL)
    public Set<Book> getBooks() {
        return books;
    }

3.  建立BookCategoryRepository 繼承   JpaRepository 

import com.hellokoding.jpa.model.BookCategory;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface BookCategoryRepository extends JpaRepository<BookCategory, Integer>{
}


4.  可以使用Repository 已經實作好,常用的CRUD功能
(findOne,findAll,save....)  



        // save a couple of categories
        BookCategory categoryA = new BookCategory("Category A");
        Set bookAs = new HashSet<Book>(){{
            add(new Book("Book A1", categoryA));
            add(new Book("Book A2", categoryA));
            add(new Book("Book A3", categoryA));
        }};
        categoryA.setBooks(bookAs);

        BookCategory categoryB = new BookCategory("Category B");
        Set bookBs = new HashSet<Book>(){{
            add(new Book("Book B1", categoryB));
            add(new Book("Book B2", categoryB));
            add(new Book("Book B3", categoryB));
        }};
        categoryB.setBooks(bookBs);

        bookCategoryRepository.save(new HashSet<BookCategory>() {{
            add(categoryA);
            add(categoryB);
        }});

        // fetch all categories
        for (BookCategory bookCategory : bookCategoryRepository.findAll()) {
            logger.info(bookCategory.toString());
        }
    }


5.  完整範例 :




CrudRepository



原本, 沒有使用 CrudRepository 前, 要在DAO layer中 , 實作CRUD的程式碼.


改用CrudRepository之後 , 基本的CRUD 程式碼可以省略 , CrudRepository  自動幫你處理.


1.    Create Repository interface

package org.arpit.java2blog.repository;

import org.arpit.java2blog.model.Country;
import org.springframework.data.repository.CrudRepository;

public interface CountryRepository extends CrudRepository
}


2.  原本 ,  service class 中, @Autowired Dao , 現在改為 : 

@Autowired
 CountryRepository countryRepository;



3. 然後, 在service class中  ,  可以使用基本的CRUD功能,

不需要寫 code,不須寫SQL或HQL,
因為CountryRepository 繼承CrudRepository
所以可以直接使用 CrudRepository  提供的method :

  countryRepository.save(country);
  countryRepository.findOne(id);
  countryRepository.findAll();
  countryRepository.delete(id);


4.  Service 範例如下:

@Service("countryService")
public class CountryService {

 @Autowired
 CountryRepository countryRepository;

 @Transactional
 public List getAllCountries() {
  List countries=new ArrayList();
  Iterable countriesIterable=countryRepository.findAll();
  Iterator countriesIterator=countriesIterable.iterator();
  while(countriesIterator.hasNext())
  {
   countries.add(countriesIterator.next());
  }
  return countries;
 }

 @Transactional
 public Country getCountry(int id) {
  return countryRepository.findOne(id);
 }

 @Transactional
 public void addCountry(Country country) {
  countryRepository.save(country);
 }

 @Transactional
 public void updateCountry(Country country) {
  countryRepository.save(country);

 }

 @Transactional
 public void deleteCountry(int id) {
  countryRepository.delete(id);
 }

}



5. 完整範例請參考:


 http://www.java2blog.com/2016/09/spring-mvc-spring-data-hibernate-mysql-example.html




6. CrudRepository 提供的CRUD功能有以下: 

2017年5月18日星期四

How to kill tomcat process on windows




實用資訊:

1) Go to (Open) Command Prompt (Press Window + R then type cmd Run this).
2) Run following commands
For all listening ports

netstat -aon | find /i "listening"

Apply port filter

netstat -aon |find /i "listening" |find "8080"

Finally with the PID we can run the following command to kill the process

Copy PID from result set

taskkill /F /PID

Ex: taskkill /F /PID 189

Done !!!

2017年3月12日星期日

2017年2月23日星期四

Android手機app開發入門



2017年2月20日星期一

tomcat 404筆記

A.  一般404的解法:

1. 404.htm
將404.htm放到以下的目錄:
[tomcat install path]/webapps/ROOT/
例如:/usr/local/tomcat8/webapps/ROOT/



2. 修改web.xml 
2.1 加上以下四行:

2.2  web.xml所在目錄:
[tomcat install path]/conf/
例如:/usr/local/tomcat8/conf/





B. 其他404,如果有使用spring 或是struct,還必須參考相關文件進行設定 , 有時候還需要寫code

spring-security設定範例如下:




2017年2月15日星期三

Web Notification API sample



Web Notification API



1. 範例如下:
https://jsbin.com/ziwod/2/edit?html,js,output







2. 還需要搭配
ajax , server side(例如: .NET , J2EE ,  Node.js , PHP .....)

3.  手動click button的部分,可以改為自動 : 每隔一段時間, 自動到server side取得資料,有資料才在右上角顯示通知或訊息



2017年1月20日星期五

Google oAuth - part 2 - simple test




簡單的測試程式碼 :

<a href="https://accounts.google.com/o/oauth2/v2/auth?response_type=token&scope=email%20profile&state=%2Fprofile&
redirect_uri=http%3A%2F%2Flocalhost%3A8080%2Fraas%2Ftesting%2FgoogleOAuth2_redirectUri.jsp&
client_id=YOUR_Client_ID">Google login test </a>


YOUR_Client_ID , 記得要修改 , 
如何取得client_id ,請參考前一篇文章  Google oAuth - part 1 

redirect_uri 後面會用到


測試結果如下:
點擊以下“Google login test”,出現以下畫面(如果已經登入過google,否則會先出現登入畫面)

上圖  ,按下允許或按下取消 , 會到 redirect_uri 這個網址的網頁


在 redirect_uri 這個網頁,可以get token ( access_token )


按下取消 : 
  1. location:
    http://localhost:8080/raas/testing/googleOAuth2_redirectUri.jsp#error=access_denied&state=google

Validating the token

https://www.googleapis.com/oauth2/v3/tokeninfo?access_token=YOUR_TOKEN
得到結果如下:
{
 "azp": "XXX.apps.googleusercontent.com",
 "aud": "XXXapps.googleusercontent.com",
 "sub": "XXX",
 "scope": "https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile",
 "exp": "1484967676",
 "expires_in": "3542",
 "email": "XXX@gmail.com",
 "email_verified": "true",
 "access_type": "online"
}







google oAuth - part 1 - 取得Client ID











[Oauth]使用 OAuth 2.0 存取 Google APIs(for Login)


要使用Google API第一步要先 取得Client ID ,步驟如下:





  • 申建立專案





  •  啟用API




  • 啟用 Google+ API








  • 建立 憑證:



  • 類型 , 來源,"使用者資料" :



  •  已授權的重新導向 URI   (填寫需要的網址):
    • 例如:   
    • http://localhost:8080/raas/googleLoging.jsp
    • http://localhost:8080/raas/testing/googleOAuth2_redirectUri.jsp






  • 產品名稱:隨便填,以後可以修改



  • Client ID ,由google系統產生, source code會用到