サーブレットでサブクラスの内容をサーバで表示する方法

このQ&Aのポイント
  • サーブレット内でサブクラスを使用し、その内容をサーバで表示する方法を教えてください。
  • 使用しているソースコードには、サーブレット内での標準出力をサーバで表示したいという要望があります。
  • また、サブクラスでサーブレットを宣言できるのかという疑問もあります。
回答を見る
  • ベストアンサー

サーブレット Java 

サブクラス(内部クラス?)の内容をサーバで表示したいです 一度、同じ質問をしましたが解決できず、再質問いたしました。 ご回答よろしくお願いします。 まず、<jsp:include flush="true" page="/servlet/page.Sflow1"/>を使い jspでサーブレットを表示しています。 サーブレットではサブクラスを使用していますが、そのサブクラスの内容をサーバで表示するにはどうすればいいでしょうか。 以下、そのソースです。 ・・・・ public class Sflow1 extends HttpServlet{ private static final long serialVersionUID = 1L; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String sql="select id,c_id,barcode from Flow order by id,c_id,date"; System.out.println("sql="+sql); //中略 HashMap<String,Keiro> hsFlow = new HashMap<String,Keiro>(); String idbk=""; String flowbk=null; while(rs.next()){ String id=rs.getString(1)+":"+rs.getString(2); String flow=rs.getString(3); if(id.equals(idbk)){ if(flowbk!=null){Keiro keiro=hsFlow.get(flowbk);if(keiro == null) keiro = new Keiro(); keiro.addKeiro(flow); hsFlow.put(flowbk,keiro); } } idbk = id; flowbk = flow; } PrintWriter out=response.getWriter(); Object maekeiro[]=hsFlow.keySet().toArray(); Arrays.sort(maekeiro); for(int i=0;i<maekeiro.length;i++){ System.out.println(maekeiro[i]+"からの動き"); hsFlow.get(maekeiro[i]).viewData(); out.println(maekeiro[i]+"からの動き"); } } //中略 class Keiro{ private HashMap<String,Integer> hsNext = new HashMap<String,Integer>(); private int soukei = 0; public void addKeiro(String atokeiro){ Integer i = hsNext.get(atokeiro); if (i==null) i=new Integer(0); hsNext.put(atokeiro,new Integer(i.intValue()+1)); soukei++; } public void viewData(){ Object atokeiro[]=hsNext.keySet().toArray(); Arrays.sort(atokeiro); for(int i=0;i<atokeiro.length;i++){ System.out.println("→"+atokeiro[i]+" "+(hsNext.get(atokeiro[i]).intValue()*100/soukei)+"%"); //このSystem.out.println(・・・)の部分をサーバで表示したいです。 } } } どうすれば標準出力(System.out.println)で表示した内容をサーバで表示することができるのでしょうか? サーブレットを宣言できないのでレスポンスできず・・・(そもそもサブクラスでサーブレットは宣言できるのですか?) 具体的なソース等ご教示お願いいたします。

  • Java
  • 回答数2
  • ありがとう数3

質問者が選んだベストアンサー

  • ベストアンサー
  • infeeld
  • ベストアンサー率37% (3/8)
回答No.1

Keiro クラスの viewData メソッドに PrintWriter の引数を追加してはいかがでしょうか。 class Keiro {   public void viewData(PrintWriter out) {     Object atokeiro[] = hsNext.keySet().toArray();     Arrays.sort(atokeiro);     for (int i = 0; i < atokeiro.length; i++) {       out.println(・・・);     }   } } ■呼び出し元 PrintWriter out = response.getWriter(); //中略 hsFlow.get(maekeiro[i]).viewData(out); HttpServletResponse#getWriter で取得した Writer に print すれば、どのクラスでも出力が可能です。

tsa63688
質問者

お礼

public void viewData(PrintWriter out) { //なるほど!解決できました。 ご回答ありがとうございました。

その他の回答 (1)

  • askaaska
  • ベストアンサー率35% (1455/4149)
回答No.2

回答前に確認しておきたいけど 「サーバで表示する」 ってどういう意味?

関連するQ&A

  • サブクラスの内容をサーバで表示したいです

    まず、<jsp:include flush="true" page="/servlet/page.Sflow1"/>を使い jspでサーブレットを表示しています。 サーブレットではサブクラスを使用していますが、そのサブクラスの内容をサーバで表示するにはどうすればいいでしょうか。 以下、そのソースです。 ・・・・ public class Sflow1 extends HttpServlet{ private static final long serialVersionUID = 1L; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String sql="select id,c_id,barcode from Flow order by id,c_id,date"; System.out.println("sql="+sql); //中略 HashMap<String,Keiro> hsFlow = new HashMap<String,Keiro>(); String idbk=""; String flowbk=null; while(rs.next()){ String id=rs.getString(1)+":"+rs.getString(2); String flow=rs.getString(3); if(id.equals(idbk)){ if(flowbk!=null){Keiro keiro=hsFlow.get(flowbk);if(keiro == null) keiro = new Keiro(); keiro.addKeiro(flow); hsFlow.put(flowbk,keiro); } } idbk = id; flowbk = flow; } PrintWriter out=response.getWriter(); Object maekeiro[]=hsFlow.keySet().toArray(); Arrays.sort(maekeiro); for(int i=0;i<maekeiro.length;i++){ System.out.println(maekeiro[i]+"からの動き"); hsFlow.get(maekeiro[i]).viewData(); out.println(maekeiro[i]+"からの動き"); } } //中略 class Keiro{ private HashMap<String,Integer> hsNext = new HashMap<String,Integer>(); private int soukei = 0; public void addKeiro(String atokeiro){ Integer i = hsNext.get(atokeiro); if (i==null) i=new Integer(0); hsNext.put(atokeiro,new Integer(i.intValue()+1)); soukei++; } public void viewData(){ Object atokeiro[]=hsNext.keySet().toArray(); Arrays.sort(atokeiro); for(int i=0;i<atokeiro.length;i++){ System.out.println("→"+atokeiro[i]+" "+(hsNext.get(atokeiro[i]).intValue()*100/soukei)+"%"); //このSystem.out.println(・・・)の部分をサーバで表示したいです。 } } } どうすれば標準出力(System.out.println)で表示した内容をそのままサーバに送れるのでしょうか? サーブレットを宣言できないのでレスポンスできず・・・ 具体的なソース等ご教示お願いいたします。

    • ベストアンサー
    • Java
  • HTMLの質問なのかJAVAサーブレットの質問なのか微妙なのですがテー

    HTMLの質問なのかJAVAサーブレットの質問なのか微妙なのですがテーブルを一行に二つ表示したいのですが表示はできるんですが表示位置を中央にすることができなくて困ってます どうすれば中央にすることができますか? while(rs2.next()){ String name = rs2.getString("st.staff_name"); String kana = rs2.getString("st.staff_kana"); String birthday = rs2.getString("st.birthday"); String sex = rs2.getString("sm.sex"); String blood = rs2.getString("bm.blood_type"); String hight = rs2.getString("st.hight"); String weight = rs2.getString("st.weight"); String reration = rs2.getString("st.reration"); String mobile = rs2.getString("st.mobile_tel"); String tel = rs2.getString("st.tel"); out.println("<br></br><TABLE border=0 align=\"center\"><table border=1 align=\"left\"><tr><th width=150>氏名</th>"); out.println("<td width=200>"+name+"</td></tr><tr>"); out.println("<th>ヨミガナ</th>"); out.println("<td>"+kana+"</td></tr><tr>"); out.println("<th>生年月日</th>"); out.println("<td>"+birthday.replace("-", "/")+"</td></tr><tr>"); out.println("<th>性別</th>"); out.println("<td>"+sex+"</td></tr><tr>"); out.println("<tr><th>身長</th>"); out.println("<td>"+hight+"</td></tr>"); out.println("<tr><th>体重</th>"); out.println("<td>"+weight+"</td></tr>"); out.println("<tr><th>血液型</th>"); out.println("<td>"+blood+"</td></tr>"); out.println("<tr><th>携帯電話番号</th>"); String mtel=""; if(mobile!=null&&mobile.length()>0){ for (int i = 0; i < mobile.length(); i++) { char ch = mobile.charAt(i); if(i==3){ mtel+="-"; } if(i==7){ mtel+="-"; } mtel+=ch; if(mobile.length()==0){ mtel="-"; } } }else{ mtel="不所持"; } out.println("<td>"+mtel+"</td></tr>"); out.println("<tr><th>自宅電話番号</th>"); String ttel=""; for (int i = 0; i < tel.length(); i++) { char ch = tel.charAt(i); if(i==4){ ttel+="-"; } if(i==6){ ttel+="-"; } ttel+=ch; } out.println("<td>"+ttel+"</td></tr>"); out.println("<tr><th>続柄</th>"); out.println("<td>"+reration+"</td>"); out.println("</tr></table>");

  • jsp、サーブレットの質問です。

    Tomcatを使用してjspとサーブレットを使い掲示板のような投稿サイトもどきを作成していますが解決できない部分があります。 ↓は表示用のjspです♪ <html> <head> <title>Insert title here</title> </head> <body> <% String lsts = (String)request.getAttribute("lst"); %> <table border="4"> <tr> <td>日時</td> <td>タイトル</td> <td>スレッド主</td> <td></td> </tr> <tr> <td><%for(int i = 0; i<lsts.length(); i++){ out.println(lsts); } %> </td> <td><%out.println(); %></td> <td><%out.println("");%></td> <td> </td> </tr> </table> </form> </body> </html> こちらがサーブレットです otected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /*DB接続処理は省略します*/ try{ ps = (PreparedStatement) con.prepareStatement(sql); String sql = "select * from thred"; ResultSet rs = ps.executeQuery(); //テーブル内一覧取得 while(rs.next()){ rs.getString("time"); rs.getString("title"); rs.getString("id"); rs.getString("thredid"); String s = (rs.getString("time")+","+ rs.getString("title")+","+rs.getString("id")); String[] lsts = s.split(","); List<String> thlists = Arrays.asList(lsts); String ss = (thlists.get(0)); request.setAttribute("thlst",ss); RequestDispatcher dispatcher= request.getRequestDispatcher("/list.jsp"); dispatcher.forward(request,response); } }catch(SQLException e){ e.printStackTrace(); } catch(ClassNotFoundException e){ e.printStackTrace(); }finally{ try { con.close(); } } } jspの方にサーブレットでthredDBから抜き取ったtimeとtitleとidを全て表示させたいのですが 現状だと 2014-06-03 06:45:02  aaaa 1 の行だけがたくさん表示されてしまいます 恐らくスコープを取得した時点でこの↑の1行のものしかとれてこれていないのだと思います... どのように処理を行ったらよいのでしょうか? DBの中身は画像添付いたしますっ

  • HashMapについて

    質問させてください 以下に簡単なコードをJBuilderで作成しました。 printでブレークをはってmapインスタンスを評価してみると、mapに20個のキーが登録されるはずが、 16個しかいません。 この時点でstr1[16]が評価しても表示されていないのですが、map.get()で正常に取得はできています。 どのようなことが考えられるか、わかる型がいましたら教えてください。よろしくお願いいたします。 import java.util.*; class Test { public static void main(String[]args){ HashMap map = new HashMap(); String str1[] = new String[20]; String str2[] = new String[20]; for(int i = 0; i < 20; i ++){ str1[i] = new String(Integer.toString(i)); str2[i] = new String(Integer.toString(i * 10)); map.put(str1[i],str2[i]); } System.out.println("デバック用ブレーク"); System.out.println(map.get(str1[11])); } }

    • ベストアンサー
    • Java
  • HashMapがおかしい

    HashMap で以下の様にコーディングしました。 当然 map の中には19個のオブジェクトが存在するはずですが、何故か15個しかありません。どなたか原因を御存知でしょうか? HashMap map = new HashMap(); map.put("key1", new Integer(1)); . (2->8)省略 . map.put("key9", new Integer(9)); map.put("key10", new String("10")); . (11->18)省略 . map.put("key19", new String("19")); 以下エクリプスのデバッガで取得したもの。 ECLIPSE 2.1.3 / JDK 1.4.2.03 map= HashMap (id=21) entrySet= HashMap$EntrySet (id=50) keySet= null loadFactor= 0.75 modCount= 19 size= 19 table= HashMap$Entry[32] (id=26) [0]= null [1]= HashMap$Entry (id=28) [2]= HashMap$Entry (id=31) [3]= null [4]= null [5]= null [6]= null [7]= null [8]= null [9]= HashMap$Entry (id=32) [10]= HashMap$Entry (id=33) [11]= null [12]= null [13]= HashMap$Entry (id=34) [14]= HashMap$Entry (id=35) [15]= HashMap$Entry (id=36) [16]= HashMap$Entry (id=37) [17]= null [18]= null [19]= null [20]= HashMap$Entry (id=38) [21]= null [22]= null [23]= HashMap$Entry (id=39) [24]= HashMap$Entry (id=40) [25]= null [26]= HashMap$Entry (id=41) [27]= HashMap$Entry (id=42) [28]= null [29]= HashMap$Entry (id=43) [30]= HashMap$Entry (id=44) [31]= null threshold= 24 values= null

    • ベストアンサー
    • Java
  • Tomcat環境下でサーブレットを実行するとステータス404になってしまいます。

    いつもお世話になっております。 Tomcat5.0.28 JDK1.4でサーブレットの勉強をしております。 testというパッケージに新たにdbtest.javaを作りました。 web.xmlに <servlet> <servlet-name>dbtest</servlet-name> <servlet-class>test.dbtest</servlet-class> </servlet> <servlet-mapping> <servlet-name>dbtest</servlet-name> <url-pattern>/dbtest</url-pattern> </servlet-mapping> を追加しました。 ソースは以下の通りです。 public class dbtest extends HttpServlet { Connection con = null; Statement stmt = null; List list = new ArrayList(); public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); selecBean selBean = new selecBean(); try { Class.forName("org.postgresql.Driver"); String url = "jdbc:postgresql://192.168.*.***:5432"; con = DriverManager.getConnection(url, "usr", ""); StringBuffer sb = new StringBuffer(); sb.append("SELECT * FROM m_kubunmei_tbl"); stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(sb.toString()); while (rs.next()) { listBean listBean = new listBean(); listBean.setS_cd(rs.getString("syubetu_cd")); listBean.setK_cd(rs.getString("kubun_cd")); listBean.setK_nm(rs.getString("kubun_nm")); list.add(listBean); } out.println("<html><head></head><body>"); out.println(list); out.println("</body></html>"); } catch (Exception e) { e.printStackTrace(); } } } 同手順で他のサーブレットを作成した場合は動きました。 設定の問題かもしくはソースの問題かどなたかご教示お願いします。

  • 配列を大きい順にソートしたいのですが・・・

    次の配列のc.intValue()が回数表示されるのですが、 あまりにデータが多いため、見やすくするために数が大きい順に表示したいと思います。 for文でlengthを求め・・・って言うのは分かるのですが、 c.intValue()で表示にしているので、どう書けばいいか分かりません。 以下ソースです。 ・・・・・ HashMap<String,Integer> hsFlow = new HashMap<String,Integer>(); <中略> Iterator<String> ir = hsFlow.keySet().iterator(); while(ir.hasNext()){ String f = ir.next(); Integer c = hsFlow.get(f); if(c==null) c = new Integer(0); System.out.println("経路"+f+":"+c.intValue()+"回"); 具体的なソースコードを教えていただけると嬉しいです。 ご回答よろしくお願いします。

    • ベストアンサー
    • Java
  • データベースとのやり取り(サーブレット)

    String q1 = "USE riyou"; st.execute(q1); String q2 = "LOCK TABLE r1 WRITE"; st.execute(q2); String q3 = "SELECT * FROM r1 where ban=" + items[0]; ResultSet rs = st.executeQuery(q3); String set[] = {" ","0","1","2","3","4","5","6","7","8","9"}; for( int i = 0;i < 11;i++ ){ if( rs.getString("tou") == set[i] ){ out.println("test"); } out.println("" + set[i] + "0000000"); } touの中身は"1"なんですがIFの条件に合いません。なぜなんでしょうか??set[]の中には"1"が入っているはずなんですが・・・。ちなみにtouもset[2]も文字の"1"なんです。昨日から2日悩んでます;;原因のわかる方いましたらお願いします。

    • ベストアンサー
    • Java
  • javaの文字化けに困っています。

    改善方法はありますか。 public class daytime extends HttpServlet { protected String decodeString(String str){ try{ byte[] byteData = str.getBytes("ISO_8859_1"); str = new String(byteData, "Shift_JIS"); }catch(UnsupportedEncodingException e){ return null; } return str; } public void doGet(HttpServletRequest request ,HttpServletResponse response) response.setContentType("text/html;charset=Shift_JIS"); PrintWriter out = response.getWriter(); String tmp; String name = ""; tmp = request.getParameter("name"); Calendar cal = Calendar.getInstance(); out.println("<html lang=\"ja\" >"); out.println("<head>"); out.println("<title>ContextParam Example</title>"); out.println("<style>"); out.println("</style>"); out.println("<meta http-equiv=\"Content-Type\" Content=\"text/html;charset=Shift_JIS\">"); out.println("</head>"); out.println("<body>"); out.println("<table>"); out.println("<p>"); Connection conn = null; String url = "jdbc:mysql://localhost/list2"; String user = "list2"; String password = "list2"; out.println("</table>"); try { Class.forName("com.mysql.jdbc.Driver").newInstance(); out.println("Mysqlのロードに成功"); conn = DriverManager.getConnection(url, user, password); Statement stmt = conn.createStatement(); String sql = "SELECT * FROM goods"; ResultSet rs = stmt.executeQuery(sql); out.println("<table>"); while(rs.next()){ out.println("<tr>"); out.println("<td>" +rs.getInt("id") + "</td>"); out.println("<td>" +rs.getString("name") + "</td>"); out.println("<td>" +rs.getString("mail") + "</td>"); out.println("<td>" +rs.getInt("price") + "</td>"); out.println("<form method=\"GET\" action=\"./daytime3\">"); out.println("<input type=\"hidden\" name=\"id\" value=\""+ rs.getInt("id") + "\">"); out.println("<td><input type=\"submit\" value=\"更新\"></td>"); out.println("<td><input type=\"submit\" value=\"削除\"></td>"); out.println("</form>"); out.println("</tr>"); } out.println("</table>"); rs.close(); stmt.close(); } catch (ClassNotFoundException e){ out.println("ClassNotFoundException:" + e.getMessage()); }catch (SQLException e){ out.println("SQLException:" + e.getMessage()); } catch (Exception e){ out.println("Exception:" + e.getMessage()); }finally{ try{ if (conn != null){ conn.close(); out.println("DBに切断"); }else{ out.println("データベースの接続ない"); } }catch (SQLException e){ } } out.println("</p>"); out.println("<tr>"); out.println("</tr>"); out.println("<A HREF='/dddd/daytime2'>登録</A>"); out.println("<A HREF='/dddd/daytime5'>アンケート</A>"); out.println("<div style=\"font-size: 40px; text-align: center; font-weight: bold\">"); out.println(cal.get(Calendar.YEAR) + "/" + (cal.get(Calendar.MONTH) + 1) + "/" + cal.get(Calendar.DATE) + " " + cal.get(Calendar.HOUR_OF_DAY) + ":" + cal.get(Calendar.MINUTE)); out.println("</div>"); out.println("</body>"); out.println("</html>"); protected String decodeString(String str){ try{ byte[] byteData = str.getBytes("ISO_8859_1"); str = new String(byteData, "Shift_JIS"); }catch(UnsupportedEncodingException e){ return null; } return str; } } }

  • Javaです。

    以下のSQLのcustomerのc_idの最大値を求め、表示させたいのですが、上手くいかず、エラーが返ります。 Customerはデータベースに格納されています。 以下ソースです。 ・・・・・・・・・ String sql="select max(c_id) as max_c from customer"; Connection con = null; Statement smt = null; try { con = DBManager.getConnection(); smt = con.createStatement(); ResultSet rs = smt.executeQuery(sql); out.println(rs.getInt("max_c")); }catch(SQLException e){ throw new ServletException(e); }finally{ if(smt != null){ try{smt.close();}catch(SQLException ignore){} } if(con != null){ try{con.close();}catch(SQLException ignore){} } } ・・・・・・・ //恐らく、out.println(rs.getInt("max_c")); の表示クエリに問題があると思うのですが、どうすればいいか分からず質問しました。 具体的なソース等、解決策を教えて下さい。 Java素人です。 よろしくお願いします。

    • ベストアンサー
    • Java

専門家に質問してみよう