なんとな~くしあわせ?の日記

「そしてそれゆえ、知識そのものが力である」 (Nam et ipsa scientia potestas est.) 〜 フランシス・ベーコン

Servlet, JSPの利用

面白そうなWEBサービスがある。これを教材にしてServletJSPを動かしてみよう。
rss.php‚̃NƒGƒŠ¶¬

index.jsp

<%@ page language="java" contentType="text/html; charset=windows-31j"
    pageEncoding="windows-31j"%>
<!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=windows-31j">
<title>しょぼかるダウンローダ</title>
</head>
<body>

<h2>しょぼかるダウンローダ</h2>
<h2>ボタンを押すと番組表を表示するよ</h2>

<form action="<%= request.getContextPath() %>/inputCalendarServlet" METHOD="POST">

	<p>ユーザーID</p>
	<input type="text" name="userID" value="">
	<p>出力最大数(行数)</p>
	<input type="text" name="row" value="">
	<p>出力最大数(日数)</p>
	<input type="text" name="days" value="">

	<input type="submit" value="番組表取得" >

</form>

</body>
</html>

inputCalendarServlet.java

package poorCalendar;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import poorCalendar.httpClient;

/**
 * Servlet implementation class inputCalendarServlet
 */
public class inputCalendarServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	public static ArrayList<String> calArray = new ArrayList<String>();

    /**
     * @see HttpServlet#HttpServlet()
     */
    public inputCalendarServlet() {
        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
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		// TODO Auto-generated method stub

		//入力欄に入力したパラメーターの表示
		perform(req, res);

	}


	//入力したパラメーターの表示
	private void perform(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

		//入力エンコーディングの指定
		req.setCharacterEncoding("Windows-31J");

		//入力パラメーターの取得
		String userID = req.getParameter("userID");
		String row = req.getParameter("row");
		String days = req.getParameter("days");

		res.setContentType("text/plain; charset=Windows-31J");

		//httpClientをそのままいじる

		httpClient.GetHtml("http://cal.syoboi.jp/rss.php?usr="
				+ userID
				+ "&filter=0&count="
				+ row
				+ "&days= "
				+ days
				+ "&titlefmt=%24(StTime)%20%24(Mark)%24(MarkW)%20%24(ShortTitle)%20%24(SubTitleB)%20%5B%24(ChName)%5D");

		res.sendRedirect("./calendar.jsp");
	}
}

httpClient.java

package poorCalendar;

import java.net.*;
import java.io.*;
import java.util.*;

/**
 * Java HTTP クライアントサンプル - HttpURLConnection 版 -
 *
 * @author 68user http://X68000.q-e-d.net/~68user/
 */

/**
 * 上記のサンプルを参考にしました
 *
 * @author nantona-ku shiawase
 */

public class httpClient {


    public static String GetHtml(String urlstr)
        throws MalformedURLException, ProtocolException, IOException {


    	//URLオブジェクトを生成
        URL url = new URL(urlstr);
        String line;

        HttpURLConnection urlconn = (HttpURLConnection)url.openConnection();
        urlconn.setRequestMethod("GET");
        urlconn.setInstanceFollowRedirects(false);
        urlconn.setRequestProperty("Accept-Language", "ja;q=0.7,en;q=0.3");

        urlconn.connect();

        Map headers = urlconn.getHeaderFields();
        Iterator it = headers.keySet().iterator();
        while (it.hasNext()){
            String key= (String)it.next();
            System.out.println("  " + key + ": " + headers.get(key));
        }

        BufferedReader reader =
            new BufferedReader(new InputStreamReader(urlconn.getInputStream(), "UTF-8"));


        while (true){
            line = reader.readLine();
            inputCalendarServlet.calArray.add(line);
            if ( line == null ){
                break;
            }
        }

        reader.close();
        urlconn.disconnect();

        return line;
    }
}

calendar.jsp

<%@ page language="java" contentType="text/html; charset=windows-31j"
    pageEncoding="windows-31j"%>
<%@ page import="poorCalendar.inputCalendarServlet" %>
<!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=windows-31j">
<title>番組表</title>
</head>
<body>

<%

for (int i = 0; i < inputCalendarServlet.calArray.size(); i++) {
    out.println(inputCalendarServlet.calArray.get(i)+"<br />");
}

%>

</body>
</html>


…実行すると入力パラメーター通りに番組表が取得できる。けども出力結果が汚い。
ホントは受け取った内容をDBに格納して、出力する場合Beanに入れて出力するという感じでしょうか。短時間で作ったので許せ、なんて。
private?public? ^q^ あう?気にしない