2017/12/16

Java 自訂例外處理

class MemberIDException extends Exception{
    public MemberIDException(String mID){
        super("ERROR: " + mID)
    }
    public void contactWith(){ // 自訂例外中的自訂方法
        System.out.println("Please try again.");
    }
}

public static void main(String[] args){
    try{
        checkMemberID("123456");
    }
    catch(MemberIDException e){
        tem.out.println(e.getMessage());
        e.contactWith(); // 自訂例外類別中的自訂方法
    }
}

public static void checkMemberID(String mID) throws MemberIDException{
    if(mID.length() != 5){
        throw new MemberIDException(mID); // 自訂例外
    }
}
轉載自http://jhengjyun.blogspot.tw/2010/06/java-extends.html

2017/12/7

Servlet使用外部API

/*
參考資料
http://bit.ly/2umBcG8
 */
/*
用Servlet POST 給API.AI請求與取得回應,正常版不亂碼
*/
package jt;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.util.EntityUtils;

public class AIConversationServlet extends HttpServlet {

    private String tokenId = "";//API.AI那邊的TokenId

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");

        PrintWriter out = response.getWriter();
        String userInput = new String(request.getParameter("userInput").getBytes("UTF-8"));
        String url = "https://api.api.ai/v1/query?v=20150910";
        url = this.stringParser(url);
        String urlParameters = "{\"query\": [\"" + userInput + "\"],\"lang\": \"zh-cn\",\"sessionId\": \"1234567890\"}";
        HttpClient httpClient = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost(url);
        post.setHeader("Content-type", "application/json;charset=utf-8");
        post.setHeader("Authorization", tokenId);
        post.setEntity(new StringEntity(urlParameters, "UTF-8"));
        HttpResponse theResponse = httpClient.execute(post);
        HttpEntity entity = theResponse.getEntity();
        String responseString = EntityUtils.toString(entity, "UTF-8");
        out.write(responseString);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    }

    public String stringParser(String url) throws IOException {
        String url2 = new String();
        for (int j = 0; j < url.length(); j++) {
            if (url.substring(j, j + 1).matches("[\\u4e00-\\u9fa5]+")) {
                try {
                    url2 = url2 + URLEncoder.encode(url.substring(j, j + 1), "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            } else {
                url2 = url2 + url.substring(j, j + 1).toString();
            }
        }

        return url2;
    }
    public static String getBody(HttpServletRequest request) throws IOException {

        String body = null;
        StringBuilder stringBuilder = new StringBuilder();
        BufferedReader bufferedReader = null;

        try {
            InputStream inputStream = request.getInputStream();
            if (inputStream != null) {
                bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                char[] charBuffer = new char[128];
                int bytesRead = -1;
                while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
                    stringBuilder.append(charBuffer, 0, bytesRead);
                }
            } else {
                stringBuilder.append("");
            }
        } catch (IOException ex) {
            throw ex;
        } finally {
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException ex) {
                    throw ex;
                }
            }
        }

        body = stringBuilder.toString();
        return body;
    }
}
需匯入apache的套件

2017/12/4

Servlet輸出不亂碼

程式如下

package newpackage;

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

public class NewServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        String userInput = new String(request.getParameter("userInput").getBytes("UTF-8"));
        out.print(userInput);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.print("哈囉");
    }

}
不管是POST還是GET第一行都要先放response.setContentType("text/html;charset=UTF-8");這行
如果是GET,要先把在網址列取得的參數用getBytes取得並轉成UTF-8,之後才輸出。可以上方的程式碼。

最近又發生亂碼的情況了,看來還有別的會亂碼的情況我沒注意到
就是我從jsp送post請求給servlet,servlet再把這個從jsp送來的參數顯示到另一個jsp
我在servlet用System.out.println()查看這個參數,才發現進到servlet時就亂碼了,所以應該不是jsp的問題

後來我在servlet的doPost的第二行加入request.setCharacterEncoding("UTF-8");
就解決了

原本以為