■目次
■Servlet & JSP
ServletからJSPにパラメータを渡す
request.setAttribute("string", "文字列を渡す");
Servletから受け取ったパラメータを利用する
<%= request.getAttribute("string") %>
■Servlet
文字コードやコンテンツタイプを指定する
response.setContentType("text/html; charset=UTF-8");
response.setContentType("image/png");
response.setContentType("image/jpeg");
response.setContentType("image/gif");
クッキーを取得する
// レスポンスから配列で取得
Cookie[] cs = request.getCookies();
// 値を取得
Cookie c = cookies[0];
String v = cookie.getValue();
クッキーを取得する関数
/**
* クッキー取得
* @param name クッキーの名前
* @param req リクエスト
* @return クッキーの名前のクッキー ない場合は null
*/
private static Cookie getCookie(String name, HttpServletRequest req) {
Cookie[] cookies = req.getCookies();
for (Cookie cookie : cookies) {
if (cookie.getName().equals(name)) {
return cookie;
}
}
return null;
}
クッキーを設定する
// 名前と値を指定して作成
Cookie c = new Cookie("Name", "Value");
response.addCookie(c);
Http only cookieの指定
c.setHttpOnly(true); // 解除はfalse
Http only cookieとは、
Java Script での操作を禁止する設定で、クロスサイトスクリプティング攻撃等への対策に有効な設定です。
■JSP
ページの文字コードを設定する
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ page language="java" contentType="text/html; charset=Shift_JIS" pageEncoding="Shift_JIS" %>
<%@ page language="java" contentType="text/html; charset=EUC_JP" pageEncoding="EUC_JP" %>
- ページディレクティブはJSPファイルの先頭に記述します。
- JSPファイルの文字コードも同じ文字コードにしておいたほうが無難です。
htmlに変数やオブジェクトを出力する
<%= hogehoge %>
クラスやパッケージをインポートする
<%@ page import="java.util.*" %>
<%@ page import="my.package.MyBean" %>
コンテキストパスを出力する
- <%=request.getContextPath()%>
- <form action='<%=request.getContextPath()%>/hogeservlet' method="post">
- → <form action='/ContextPath/hogeservlet' method="post">
不要な空白や開業の出力を抑止する
<%@ page trimDirectiveWhitespaces="true" %>
■html
ページの文字コードをブラウザに伝える
<meta http-equiv="Content-Type" content="text/html; charset="UTF-8">
<meta http-equiv="Content-Type" content="text/html; charset="Shift_JIS">
<meta http-equiv="Content-Type" content="text/html; charset="EUC_JP">
最終更新:2013年11月11日 23:29