สำหรับสรุปนี้รวมมาจากหนังสือ Head First Servlet and JSP เป็นหลัก
มาทำ link รวมไว้ให้เผื่อใครจะสอบ ตอนที่สอบเป็นรหัส 310-083 นะค่ะ รู้สึกว่าจะเป็น J2EE 1.5 ค่ะ
ขอให้โชคดีกันนะค่ะ
%JAVA_HOME%\bin\keytool -genkey -alias tomcat -keyalg RSAจากนั้นใส่ password เป็น changeit (ซึ่งเป็น password default ที่ใช้กับ tomcat)
</security-constraint>
...
<user-data-constraint>
<transport-guarantee>CONFIDENTIAL</transport-guarantee>
</user-data-constraint>
</security-constraint>
<?xml version="1.0" encoding="UTF-8"?> <taglib version="2.0" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd "> <tlib-version>1.2</tlib-version> <short-name>NMTOKEN</short-name> <uri>DiceFunction</uri> <!-- สำหรับ Custom Tag --> <tag> <description>random advice</description> <name>advice</name> <tag-class>package.AdvisorTagHandler</tag-class> <body-content> empty | scriptlet | tagdependent </body-content> <attribute> <name>user</name> <required> true | false </required> <rtexprvalue> true | false </rtexprvalue> <type>int | java.lang.String | etc. </type> </attribute> [<attribute> ... </attribute>] <dynamic-attributes> true | false </dynamic-attributes> </tag> <!-- สำหรับ tag file --> <tag-file> <name>Header</name> <path>/META-INF/tags/Header.tag</path> </tag-file> <!-- สำหรับ function --> <function> <name>rollIt</name> <function-class>com.amadmonster.scwcd.el.function.DiceRoller</function-class> <function-signature>int rollDice()</function-signature> </function> <!-- สำหรับ function ที่รับตัวแปร --> <function> <name>rollWith</name> <function-class>com.amadmonster.scwcd.el.function.DiceRoller</function-class> <function-signature>int rollDice(int)</function-signature> </function> </taglib>
Tag | Attribute | Usage |
---|---|---|
c:out | value | String ของค่าที่ต้องการจะแสดงผล |
escapeXml | ไม่ render XML หรือ HTML แ่ต่จะแสดงผลเหมือนกับ String ปกติ default: true | |
default | ค่า default เมื่อ value เป็น null ซึ่งสามารถใช้ได้เช่นเดียวกับ <c:out value="some string">default value</c:out> | |
c:forEach | var | ชื่อของตัวแปรที่ไว้รับ element ในแต่ละ loop |
items | ชื่อของตัวแปรตัวแปร array, Collection, Map หรือ comma-delimited String ซึ่งเก็บแต่ละ element สำหรับการวนลูป | |
varStatue | ชื่อของตัวแปร javax.servlet.jsp.jstl.core.LoopTagStatus ซึ่งสามารถนำมาหาค่าต่างๆ เช่น count ต่อไป เช่น<c:forEach var="movie" items="${movieList}" varStatus="movieLoopCount"> <tr><td>Count: ${movieLoopCount.count} </td></tr> </c:forEach> | |
c:forTokens | var | ชื่อของตัวแปรที่ไว้รับ element ในแต่ละ loop |
items | ชื่อของตัวแปรตัวแปร array, Collection, Map หรือ comma-delimited String ซึ่งเก็บแต่ละ element สำหรับการวนลูป | |
varStatue | ชื่อของตัวแปร javax.servlet.jsp.jstl.core.LoopTagStatus ซึ่งสามารถใช้ได้เช่นเดียวกับ varStatus ของ c:forEach | |
delims | String ที่เป็นตัวคั่นในการแบ่งแต่ละ token เช่น <c:forTokens items="${dataString}" delims="," var="item"> Next item - ${item} </c:forTokens> | |
begin | ตัวแรกที่จะเริ่มใช้ใน loop | |
end | ตัวสุดท้ายที่จะใช้ใน loop | |
step | ตัวถัดที่จะใช้ใน loop | |
c:if | test | ค่าที่เป็น boolean เพื่อใช้ทดสอบว่าจะทำคำสั่งใน c:if หรือไม่ |
c:choose | ตัวนี้ไม่มี attribute จะใช้ ร่วมกับ c:when และ c:otherwise<c:choose> <c:when test="${userPref == 'performance'}"> ...do something... </c:when> <c:when test="${userPref == 'safety'}"> ...do something... </c:when> <c:otherwise> ...do something... </c:otherwise> </c:choose> | |
c:when | test | เหมือนกับ attribute test ของ c:if คือใช้ทดสอบเงื่อนไขในการทำงาน |
c:otherwise | ตัวนี้ไม่มี attribute ใช้ร่วมกับ c:when ดังนี้ | |
c:set | var | ตัวแปรที่ต้องการ set ค่า ในกรณีที่ไม่มีตัวแปรชื่อนี้ ตัวแปรนี้ก็จะถูกสร้างขึ้นมา |
scope | scope ของตัวแปร
| |
value | ค่าที่ต้องการจะ set หรือสามารถใส่ค่านี้เป็น body ของ tag ก็ได้ เช่น | |
c:set | target | bean หรือ Map ที่ต้องการจะ set ค่า |
property | ชื่อ property ที่ต้องการจะ set ค่า | |
value | ค่าที่ต้องการจะ set หรือสามารถใส่ค่านี้เป็น body ของ tag ก็ได้ เช่น <c:set target="${person}" property="name">new name</c:set> | |
c:remove | var | ตัวแปรที่ต้องการลบออก |
scope | scope ของตัวแปรที่ต้องการจะลบ
| |
c:import | url | c:import จะใช้ได้เหมือน jsp:include แต่ว่าสามารถอ้างถึงไฟล์ได้ทั้งใน application และนอก web application โดยระบุ URL ของไฟล์ที่ต้องการจะใส่เข้ามา |
c:param | name | c:param ใช้ในการส่งตัวแปรข้ามไปยัง included page เหมือนกับ jsp:param โดยระบุชื่อของตัวแปรที่ต้องการจะส่งไป |
value | ค่าของตัวแปรที่จะส่งไป ใช้ร่วมกับ c:import หรือ c:url ซึ่งค่าของตัวแปรก็จะ encodeUrl แล้ว และสามารถส่งได้อย่างถูกต้อง ตัวอย่างเช่น<c:import url="Header.jsp"> <c:param name="subTitle" value="any sub-title for this page" /> <c:import> | |
c:url | value | path และ file ที่ต้องการจะ link ไป โดย c:url จะจัดการเรื่อง session ให้อัตโนมัติ เช่นในกรณีที่ client ไม่รับ cookies มันจะใส่ session id ต่อท้าย url ให้อัตโนมัติ แต่มันจะไม่ได้ทำ encodeUrl ให้ดังนั้นถ้าใน URL มีค่าตัวแปรที่เป็นอักขระพิเศษสำหรับ HTML เช่น space ก็จะทำให้ error ได้ |
c:redirect | url | url ที่จะ redirect ไป ซึ่งจะมีการ rewrite URL เพื่อจัดการ session ให้อัตโนมัติ |
c:catch | var | สำหรับใส่ code ที่เสี่ยงจะ throw exception ถ้ามี exception เกิดขึ้น มันจะข้าม block ของ c:catch ไปทำคำสั่งต่อจากนั้นเลย และ property var เป็นชื่อของตัวแปร exception ซึ่งจะใช้หลังจาก c:catch ได้ เช่น<c:catch var="ex"> <% int x = 1/0 %> </c:catch> If error occurs with ${ex} |
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;
...
try {
Robot robot = new Robot();
// ส่ง key A ไป
robot.keyPress(KeyEvent.VK_A);
} catch (AWTException e) {
e.printStackTrace();
}
...
package com.amadmonster.util.mail;
import java.util.Date;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import org.apache.log4j.Logger;
public class MailUtility {
/** Get logger. */
private static Logger logger = Logger.getLogger(MailUtility.class);
Properties props;
public MailUtility(String smtpServer) {
props = System.getProperties();
props.put("mail.smtp.host", smtpServer);
}
public void sendMail(String to, String from, String subject, String body) throws MailUtilityException {
Session session = Session.getDefaultInstance(props);
session.setDebug(false);
Message msg = new MimeMessage(session);
try {
msg.setFrom(new InternetAddress(from));
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, true));
msg.setSubject(subject);
// check mime type from Web: Content Type
msg.setContent(body, "text/plain");
msg.setText(body);
msg.setSentDate(new Date());
// -- Send the message --
Transport.send(msg);
logger.info("Message sent OK.");
} catch (AddressException e) {
throw new MailUtilityException("Incorrrect address format", e);
} catch (MessagingException e) {
throw new MailUtilityException("Error occurs when sending mail", e);
}
}
}
package com.amadmonster.util.mail;
public class MailUtilityException extends Exception {
public MailUtilityException(String message, Throwable cause) {
super(message, cause);
}
public MailUtilityException(String message) {
super(message);
}
public MailUtilityException(Throwable cause) {
super(cause);
}
}
package com.amadmonster.util.command;
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.log4j.Logger;
public class CommandUtility {
static Logger logger = Logger.getLogger(CommandUtility.class);
private int status; // return command status, 0 - normal exit
/**
* Run Window command on specific working directory.
* @param command Array of command string and option.
* @param workDir String of working directory.
* @throws CommandUtilityException
*/
public void runCommand(String[] command, String workDir) throws CommandUtilityException {
String[] cmd = { "C:\\WINDOWS\\system32\\cmd.exe", "/y", "/c" };
ListcmdList = new ArrayList ();
cmdList.addAll(Arrays.asList(cmd));
cmdList.addAll(Arrays.asList(command));
Process p;
try {
p = Runtime.getRuntime().exec(cmdList.toArray(new String[0]), null,
new File(workDir));
logCommandInputStream(p);
logCommandErrorStream(p);
setStatus(p.exitValue());
if (getStatus() != 0) {
throw new CommandUtilityException("Fail to run command.");
}
} catch (IOException e) {
// TODO Auto-generated catch block
throw new CommandUtilityException("Fail to run command.", e);
}
}
private void logCommandInputStream(Process p) throws IOException {
InputStream is = p.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
logger.info(line);
}
}
private void logCommandErrorStream(Process p) throws IOException, CommandUtilityException {
InputStream is = p.getErrorStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
logger.error(line);
}
}
/**
* Run Window command on specific working directory.
* @param command Command string.
* @param workDir String of working directory.
* @throws CommandUtilityException
*/
public void runCommand(String command, String workDir) throws CommandUtilityException {
String[] cmd = { command };
runCommand(cmd, workDir);
}
/**
*
* @return int Status of running command, 0 - normal
*/
public int getStatus() {
return status;
}
/**
*
* @param status Exit command status
*/
private void setStatus(int status) {
this.status = status;
}
}
package com.amadmonster.util.command;
public class CommandUtilityException extends Exception {
public CommandUtilityException(String message, Throwable cause) {
super(message, cause);
}
public CommandUtilityException(String message) {
super(message);
}
public CommandUtilityException(Throwable cause) {
super(cause);
}
}
<jsp:scriptlet>
list.add("Fred");
</jsp:scriptlet>
Directive | Attribute | Usage |
---|---|---|
page | contentType | กำหนดการเข้ารหัสตัวอักษรหรือ MIME type ของ response ในกรณีที่ไม่ได้กำหนดค่าจะใช้ค่าจาก pageEncoding attribute default = "text/html;charSet=ISO-8859-1" |
import | import class อื่นเข้ามาใช้งาน XML-compliant: <jsp:directive.page import="path/file" /> | |
isThreadSafe | ถ้าเป็น "true" แปลว่า Servlet ที่ได้ หลังจาก translate JSP แล้วจะ implement SingleThreadModel เพื่อให้ Servlet เป็น thread safe (ซึ่งการทำงานจริงๆ ของ SingleThreadModel ขึ้นอยู่กับ Web Container แต่ละเจ้า จะ implement เป็นแบบไหน ซึ่งโดยลึกๆ แล้ว ไม่ค่อยได้ประโยชน์เท่าไร) | |
errorPage | url ของ exception page | |
isErrorPage | บอกให้รู้ว่า JSP page ปัจจุบันเป็น errorPage หรือไม่ ถ้าเป็น "true" ก็จะมี implicit object exception ถ้าเป็น "false" ก็จะไม่สามารถใช้ object exception ใน page นี้ได้default = "false" | |
isELIgnored | บอกว่าจะไม่สามารถใช้ Expression Language ใน JSP นี้ได้ | |
language | define scripting language ที่ใช้ใน scriptlet และ declaration default = Java | |
extends | กำหนด class ที่ JSP นี้จะ extend ซึ่งโดยปกติ จะึขึ้นอยู่กับ web containner ดังนั้นถ้าเราต้องการจะ extend ตัวอื่นจะต้องกำหนดไว้ แต่ควรจะแน่ใจจริงๆ ว่ามันทำงานได้นะจ๊ะ | |
session | กำหนดว่าเอกสารนี้จะใช้ implicit object session หรือไม่ สามารถกำหนดเป็น session="false" ถ้าไม่ต้องการใช้ sessiondefault = "true" | |
buffer | ควบคุมการใช้ buffer สำหรับ jsp ว่าต้องการ buffer หรือไม่ ค่าเริ่มต้นจะอยู่ที่ 3 KB | |
autoFlush | เมื่อ buffer เต็มจะ cleart buffer ให้อัตโนมัติ default = "true" | |
info | สามารถกำหนดเป็นค่า string ใดๆ ซึ่งจะเก็บไว้ใน servlet ที่ได้ translate จาก JSP และสามารถดึงขึ้นมาโดย Servlet.getServletInfo() | |
pageEncoding | บอกว่า page JSP encode ด้วยรหัสอะไร ในกรณีที่ไม่กำหนดค่าจะใช้ค่าจาก contentType attribute default = " ISO-8859-1 "
| |
include | file | ชื่อไฟล์ที่ต้องการนำมา include (ไฟล์ servlet ที่ได้จะเสมือนเอา included file มาแปะไว้กับ servlet เลย) |
taglib | tagdir | directory ที่เก็บ tag file ไว้ (จะใช้ในกรณีที่ไม่ได้ declare tag file ไว้ใน tld) |
prefix | ชื่อที่ใ้ช้ในการเรียก tag lib นี้ ซึ่งเป็นค่าอะไรก็ได้ ยกเว้น jsp, jspx, java, javax, servlet, sun, sunw | |
uri | ชื่อที่ต้องใช้ให้ตรงกับไฟล์ Tag Library Descriptor (TLD) | |
tag *ใช้สำหรับ tag file เท่านั้น | import | import class อื่นเข้ามาใช้งาน |
isELIgnored | บอกว่าจะไม่สามารถใช้ Expression Language ใน JSP นี้ได้ | |
language | define scripting language ที่ใช้ใน scriptlet และ declaration default = Java | |
body-content | มีค่าได้ดังนี้
| |
dynamic-attributes | ชื่อของ dynamic attribute ซึ่งจะรับเป็น HashMap เป็นชื่อและค่าของ attribute | |
attribute | name | ชื่อของ attribute ที่รับเข้ามา |
required | เป็นค่า boolean เพื่อบอกว่าเป็น attribute ที่ต้องมีเสมอหรือไม่ | |
rtexprvalue | ค่า boolean ที่บอกว่าจะ สามารถรับเป็น scriptlet ได้หรือไม่ | |
variable *ใช้สำหรับ tag file เท่านั้น | name-given | ชื่อของตัวแปร |
variable-class | class ของตัวแปร เช่น java.lang.String |
<jsp:expression>
it.next()
</jsp:expression>
<jsp:declaration>
int y = 3;
</jsp:declaration>
<jsp:text>
This is text.
<jsp:text>
API | Implicit Object | Used by Servlet |
---|---|---|
JspWriter | out | response.getWriter()* * it will get PrintWriter, not JspWriter |
HttpServletRequest | request | request* * depend on how to declare parameter name in service method |
HttpServletResponse | response | response* * depend on how to declare parameter name in service method |
HttpSession | session | request.getSession() |
ServletContext | application | getServletContext() |
ServletConfig | config | getServletConfig() |
Throwable | exception | |
PageContext | pageContext | N/A |
Object | page | N/A page scope is not available in Servlet |
Implicit Object | Used by Scriplet |
---|---|
${pageScope.name} | N/A page scope is not available in Servlet |
${requestScope.name} | request.getAttribute("name") |
${sessionScope.name} | session.getAttribute("name") |
${applicationScope.name} | application.getAttribute("name") |
${param.name} | request.getParameter("name") |
${paramValues.name[index]} | request.getParameterValues("name")[index] |
${header.name} | request.getHeader("name") |
${headerValues.name[index]} | Enumeration headers |
${cookie.name} | Cookie[] cookies = request.getCookies(); |
${initParam.name} | application.getInitParameter("name") |
${pageContext.name} | pageContext.getName() เช่น pageContext.exception ซึ่งเป็นตัวแปรเดียวกับ exception ใน JSP Implicit Object ซึ่งจะสามารถ access ตัวแปรนี้ได้จะต้องกำหนดให้* <%@ page isErrorPage="true" %> *แต่ไปลองดูแล้วกับ Tomcat 6, Servlet 2.5 ปรากฎว่าถึงไม่ใส่ ก็สามารถ access ตัวแปรได้นะ ไม่แน่ใจเหมือนกัน |
<?xml version="1.0" encoding="UTF-8"?>
<taglib version="2.0" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd ">
<tlib-version>1.2</tlib-version>
<short-name>NMTOKEN</short-name>
<uri>DiceFunction</uri>
<function>
<name>rollIt</name>
<function-class>com.amadmonster.scwcd.el.function.DiceRoller</function-class>
<function-signature>int rollDice()</function-signature>
</function>
<!-- สำหรับ function ที่รับตัวแปร -->
<function>
<name>rollWith</name>
<function-class>com.amadmonster.scwcd.el.function.DiceRoller</function-class>
<function-signature>int rollDice(int)</function-signature>
</function>
</taglib>
Action | Attribute | Usage |
---|---|---|
jsp:useBean | id | เป็น identifier ของ object โดยรับเป็น string name ของ JavaBean นั้นๆ ซึ่งจะแปลเป็น servlet โดยใช้ getAttribute หรือ setAttribute method ดังนั้นจึงเป็น case sensitive |
scope | เป็น scope ที่ใช้ในการอ้างอิงถึง JavaBean นั้น มีค่าได้ดังนี้
default: page | |
class | class ของ bean ที่จะถูกสร้างขึ้นในกรณีที่ attribute นั้นๆ ไม่มีอยู่ใน scope ที่ ซึ่งไ่ม่สามารถกำหนดเป็น interface หรือ abstract class ได้ property นี้เป็น optional คือไม่จำเป็นต้องมีก็ได้ ซึ่งใช้ในกรณีที่เราต้องการดึงค่า attribute ขึ้นมาใช้ แต่ในกรณีที่ไม่มี attribute อยู่จะทำการสร้าง bean เพื่อจะ add attribute ก็จะ error InstantiationException | |
type | Type ของ bean ในกรณีที่จะถูกสร้างขึ้น เมื่อไม่มีอยู่ใน scope ซึ่งอาจจะเป็นค่าเดียวกับ class property หรือว่าเป็น parent object ของ class property หรือว่าเป็น interface ก็ได้ในกรณีที่ไม่ได้กำหนด จะถือว่าเป็นค่า default คือ เหมือนกับ class | |
beanName | ชื่อของ Bean | |
jsp:setProperty สามารถใส่ไว้ใน body ของ jsp:useBean ได้ กรณีที่ต้องการให้ set property เมื่อมีการสร้าง bean ใหม่ (ในกรณีที่มีอยู่แล้วจะไม่ set) | name | ชื่อของ Bean (เป็นค่า property id ใน action jsp:useBean นั้นเอง) ที่เรา้้จะ set ค่า |
property | ชื่อ property ที่เราต้องการจะ set ค่า ถ้าให้ค่าเป็น "*" คือ ให้ map ชื่อ property กับ parameter ของ request object ที่ชื่อตรงกัน | |
value | ค่าที่จะ set ใหักับ property นั้นๆ (ถ้ามีการ set ค่าใช้กับ param attribute ก็จะต้องไม่มีการ set ค่ากับ value อีก | |
param | ชื่อ parameter ที่จะให้ค่ากับ property นั้นๆ ในกรณีนี้จะไม่ใส่ property value หรือในกรณีที่ไม่ใส่ัทั้ง value และ param แสดงว่า param เป็นค่าเดียวกับ property (หรือให้ใช้ param ที่มีค่าเดียวกับ property สำหรับ set ค่า) | |
jsp:getProperty | name | ชือของ object Bean (ค่า property id ใน action jsp:useBean นั้นเอง) ที่เราต้องการจะรับค่า |
property | property ที่เราต้องการจะรับค่า | |
jsp:forward | page | relative url ที่ต้องการ forward ไป ซึ่งจะเป็น JSP, servlet หรือ dynamic file อื่นๆ ก็ได้ ที่อยู่ใน application เดียวกัน |
jsp:include | page | relative url ที่จะ include (jsp:include ให้ผลเหมือนกับ directive include แต่ว่าจะทำเมื่อ runtime สำหรับในกรณีที่ included file ยังมีการเปลี่ยนแปลงอยู่) |
jsp:param | name | ชื่อตัวแปรที่ต้องการ forward ไปพร้อมกับ jsp:forward หรือ jsp:include เช่น<jsp:include page="Header.jsp"> |
value | ค่าของตัวแปรตามชื่อที่ต้องการส่ง | |
jsp:attribute | name | ชื่อของ attribute ซึ่งตัวนี้มี body ด้วยเป็นค่าของ attribute เช่น<jsp:attribute name="user">${userName}</jsp:attribute>jsp:attribute สามารถใส่ใน custom tag body ได้ ถึงแม้ว่าจะกำหนด <body-content>empty</body-content> |
jsp:doBody *ใช้สำหรับ tag file เท่านั้น | สำหรับ tag file เพื่อดึงค่า body ของ tag |
Listener | Description | method |
---|---|---|
javax.servlet. ServletContextListener | support event ที่เกี่ยวกับการ initialize และ destroy context หรือเมื่อเรา deploy application เราขึ้นไปบน web container หรือตอนที่ เรา undeploy หรือตอนที่ server start หรือ clash ก็จะมีการเรียก class นี้ไปใช้ | contextInitialized(ServletContextEvent) contextDestroyed(ServletContextEvent) |
javax.servlet. ServletContextAttributeListener | ทำงานเมื่อการมี add, remove, replace attribute เข้าไปที่ context | attributeAdded(ServletContextAttributeEvent) attributeRemoved(ServletContextAttributeEvent) attributeReplaced(ServletContextAttributeEvent) |
javax.servlet. ServletRequestListener | เมื่อมี request เกิดขึ้น หรือก่อนที่ request จะจบ | requestInitialized(ServletRequestEvent) requestDestroyed(ServletRequestEvent) |
javax.servlet. ServletRequestAttributeListener | เมื่อมีการเปลี่ยนแปลงของ attribute ใน request | attributeAdded(ServletRequestAttributeEvent) attributeRemoved(ServletRequestAttributeEvent) attributetReplaced(ServletRequestAttributeEvent) |
javax.servlet.http. HttpSessionListener | เกี่ยวกับ สร้าง/ทำลาย session | sessionCreated(HttpSessionEvent) sessionDestroyed(HttpSessionEvent) |
javax.servlet.http. HttpSessionAttributeListner | เกี่ยวกับ add, remove, replace ของ session attribute | attributeAdded(HttpSessionBindingEvent) attributeRemoved(HttpSessionBindingEvent) attributeReplaced(HttpSessionBindingEvent) |
javax.servlet.http. HttpSessionActivationListener | จะเกี่ยวพันถึงการ migrate session ข้าม jvm (สำหรับบางกรณี เช่นการทำ load-balancing) | sessionDidActivate(HttpSessionEvent) sessionWillPassivate(HttpSessionEvent) |
javax.servlet.http. HttpSessionBindingListener | คล้ายกับ HttpSessionAttributeListener แต่ต่างกันที่เป็น listener ที่จะ implement โดย attribute class คือมันจะ notify ที่ attribute ที่ implement มัน เมื่อ attribute นั้นๆ ถูกผูกเข้ากับ session หรือโยนออกจาก session | valueBound(HttpSessionBindingEvent) valueUnbound(HttpSessionBindingEvent) |
package com.amadmonster.scwcd.cookies; import java.io.IOException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class CookieAdd */ public class CookieAdd extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); // add any name to test cookie Cookie cookie = new Cookie("username", "amadmonster"); cookie.setMaxAge(30 * 60); response.addCookie(cookie); RequestDispatcher view = request .getRequestDispatcher("cookies/cookieresult.jsp"); view.forward(request, response); } }
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!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=UTF-8"> <title>Insert title here</title> </head> <body> <a href="testcookie.do">click</a> </body> </html>
package com.amadmonster.scwcd.cookies; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class CookieTester */ public class CookieTester extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse * response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); Cookie[] cookies = request.getCookies(); if (cookies != null) { for (int i = 0; i < cookies.length; i++) { Cookie cookie = cookies[i]; if (cookie.getName().equals("username")) { String userName = cookie.getValue(); out.println("Hello " + userName); break; } } } }
Forward | Include |
---|---|
javax.servlet.forward.request_uri | javax.servlet.include.request_uri |
javax.servlet.forward.context_path | javax.servlet.include.context_path |
javax.servlet.forward.servlet_path | javax.servlet.include.servlet_path |
javax.servlet.forward.path_info | javax.servlet.include.path_info |
javax.servlet.forward.query_string | javax.servlet.include.query_string |
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <context-param> <param-name>param</param-name> <param-value>parameter value</param-value> </context-param> [ <context-param> ...parameter name-value pair as above... </context-param> ] <listener> <listener-class>package.class</listener-class> </listener> <session-config> <session-timeout>10</session-timeout> </session-config> <servlet> <servlet-name>Internal Name</servlet-name> <servlet-class>package.ServletClass</servlet-class> | <jsp-file>path/file.jsp</jsp-file> <load-on-startup>1<load-on-startup/> <init-param> <param-name>param</param-name> <param-value>parameter value</param-value> </init-param> [ <init-param> ...parameter name-value pair... <init-param> ]... <security-role-ref> <role-name>Manager</role-name> <role-link>Admin</role-line> </security-role-ref> </servlet> <servlet-mapping> <servlet-name>Internal Name</servlet-name> <url-pattern>/Public.do</url-pattern> </servlet-mapping> <jsp-config> <jsp-property-group> <url-pattern>*.jsp</url-pattern> <el-ignored>[ true | false ]</el-ignored> <scripting-invalid>[ true | false ]</scripting-invalid> </jsp-property-group> <taglib> <taglib-uri>randomThing</taglib-uri> <taglib-location>/WEB-INF/myFunctions.tld</taglib-location> </taglib> </jsp-config> <!-- filter config --> <filter> <filter-name>LogRequest</filter-name> <filter-class>package.Filter</filter-class> <init-param> <param-name>param</param-name> <param-value>parameter value</param-value> </init-param> [ <init-param> ...parameter name-value pair... <init-param> ]... </filter> <filter-mapping> <filter-name>LogRequest</filter-name> <url-pattern>/path/*</url-pattern> | <servlet-name>AnyRequest</servlet-name> <dispatcher> REQUEST | INCLUDE | FORWARD | ERROR </dispatcher> [ <dispatcher> REQUEST | INCLUDE | FORWARD | ERROR </dispatcher> ]... </filter-mapping> <!-- declare welcome file --> <welcome-file-list> <welcome-file>index.html</welcome-file> [ <welcome-file>index.html</welcome-file> ]... </welcome-file-list> <!-- declare to catch all error, but you can change to catch only some exceptions --> <error-page> <exception-type>java.lang.Throwable</exception-type> <location>/ErrorPage.jsp</location> </error-page> <!-- This is another way to catch error by status code --> <error-page> <error-code>404</error-code> <location>/ErrorNotFound.jsp</location> </error-page> <!-- external resource related --> <resource-env-ref> <resource-env-ref-name>jms/StockQueue</resource-env-ref-name>
<resource-env-ref-type>javax.jms.Queue</resource-env-ref-type> </resource-env-ref>
<resource-ref> <res-ref-name>ECC</res-ref-name> <res-type>javax.sql.DataSource</res-type> <res-auth> APPLICATION | CONTAINER </res-auth> <res-sharing-scope> Shareable | Unshareable </res-sharing-scope> </resource-ref> <!-- EJB related --> <ejb-local-ref> <ejb-ref-name>JNDI lookup name (such as ejb/Customer)</ejb-ref-name> <ejb-ref-type> Entity | Session </ejb-ref-type> <local-home>package.Class</local-home> <local>package.Class</local> </ejb-local-ref> <ejb-ref> <ejb-ref-name>JNDI lookup name (such as ejb/Customer)</ejb-ref-name> <ejb-ref-type> Entity | Session </ejb-ref-type> <home>package.Class</home> <remote>package.Class</remote> </ejb-ref> <env-entity> <env-entry-name>JNDI lookup name (such as rates/discountRate)</env-entry-name> <env-entry-type>java.lang.Integer</env-entry-type> <env-entry-value>10<env-entry-value> </env-entity> <!-- mine-type mapping --> <mime-mapping> <extension>mgp</extension> <mime-type>video/mpeg</mime-type> </mime-mapping> <!-- constraint resource --> <security-constraint> <web-resource-collection> <web-resource-name>some name</web-resource-name> <description>explain about tht resource</description> <url-pattern>/Public.do</url-pattern> [ <url-pattern>/Path/resource</url-pattern> ]... <http-method>GET | POST | PUT | TRACE | DELETE | HEAD | OPTION</http-method> [ <http-method>GET | POST | PUT | TRACE | DELETE | HEAD | OPTION</http-method> ]... </web-resource-collection> <auth-constraint> <role-name>Admin</role-name> [ <role-name>Others</role-name> ]... </auth-constraint> <user-data-constraint> <transport-guarantee> NONE | INTEGRAL | CONFIDENTIAL </transport-guarantee> </user-data-constraint> </security-constraint> <!-- authorization path to define role --> <security-role><role-name>Admin</role-name></security-role> [ <security-role><role-name>Admin</role-name></security-role> ]... <login-config> <auth-method>BASIC | DIGEST | CLIENT-CERT | FORM</auth-method> <form-login-config> <form-login-page>/loginPage.html</form-login-page> <form-error-page>/loginPage.html</form-error-page> </form-login-config> </login-config> </web-app>