• Khai báo biến khởi tạo ban đầu trong servlet file có tên LoginProcess.Khi file servlet đó được load lên server thì biến đó đã được khởi tạo.... Một số điều chú ý : Với câu lệnh : HttpS
Trang 1Một số điều cần nhớ với java web
Trang 2<servlet-name>CheckLogin</servlet-name>
<url-pattern>/LoginError</url-pattern>
</servlet-mapping>
server ,thay vì phải chờ đợi cho yêu câu đầu tiên
Trang 3 Configuring Error page.
<error-page>
<exception-type>java.lang.Throwable</exception-type>
<location>/errorPage.jsp</location>
</error-page>
lỗi của ứng dụng là ArithmaticException Nếu lỗi khác với lỗi
ArithmaticException thì nó sẽ gọi đến trang lỗi của toàn ứng dụng
<error-page>
<exception-type>java.lang.ArithmeticException</exception-type> <location>/arithmaticException.jsp</location>
Trang 5đó được load lên server thì biến đó đã được khởi tạo).
Trang 6• Khai báo biến khởi tạo ban đầu trong servlet file có tên LoginProcess.(Khi file servlet đó được load lên server thì biến đó đã được khởi tạo).
Trang 7Note :Trong một web application chỉ có một đối tượng ServletContext ,còn ServletConfig là của riêng từng thằng servlet khác nhau.
2.Servlet
2.1.Một số hàm quan trọng.
getParameter
String[] names=request.getParameterValues("name");
String name=request.getParameter("name");
forward(): used to forward request from one servlet to another servlet.
request.setAttribute("title","home page");
ServletContext servletContext=getServletContext();
RequestDispatcher dispatcher=servletContext.getRequestDispatcher("home"); dispatcher.forward(request, response);
hoặc
request.setAttibute(“imageName”,”funny”);
RequestDispatcher dispatcher=request.getRequestDispatcher("home");
dispatcher.forward(request, response);
sendRedirect :Link tới một trang khác và không có giữ liệu gửi đến trang
đó.(Giống như thẻ a)
response.sendRedirect("login.jsp");
include(): used to include the contents of another servlet, JSP page or a
HTML file to a servlet
RequestDispatcher dispatcher=getServletContext().getRequestDispatcher(path); if(dispatcher==null){
out.print(path+"not found");
Trang 8Note:Nếu session chưa có giá trị thì nó sẽ trả về giá trị null.
Một số hàm liên quan đến session.
• session.invalidate() :làm mất hiệu lực của session
• session.setMaxInactiveInterval(600) :set thời gian hiệu lực tối đa cho session tính bằng second
• session.isNew() :Kiểm tra là session đó được tạo ra lần đầu tiên hay
đã được tạo ra nhiều lần
Một số điều chú ý :
Với câu lệnh : HttpSession session=request.getSession(boolean);
Giá trị truyền vào là kiểu boolean (true or false).Nếu giá trị truyền vào
là false thì sẽ có 2 lựa chọn :
Nếu sesson đó đã tồn tại thì nó sẽ return session đó
Nếu session chưa tồn tại thì nó trả về bằng null
Giá trị truyền vào là true (tức là giá trị mặc định hay không có giá trị boolean truyền vào):
Nếu sesson đó đã tồn tại thì nó sẽ return session đó
Trang 9 Nếu bạn là 1 client mới thì nó sẽ tạo ra một session mới và trả
Class User có thể bao gồm tên,địa chỉ,password,ngày sinh,
Như vậy ta có thể lấy được nhiều thông tin hơn từ 1 object
3.Jsp.
3.1.Một số hàm quan trọng.
3.1.1.pageContext
Trang 10• getAttribute: Chỉ tìm trong nội bộ trang.
• findAttribute :Hàm này sẽ tìm từ phạm vi nhỏ nhất rồi mở rộng dần,từ trong trang ,request, session, và cuối cùng là toàn bộ aplication
Ví dụ :
Session scope is: <
%=pageContext.getAttribute("otherScope",PageContext.SESSION_SCOPE)%>Kq:trả về value atribute có tên otherScope, PageContext.SESSION_SCOPE là phạm vị tìm kiếm
Trang 11Trong một ứng dụng ,các trang đều có giao diện chung,ví dụ:menu chung,section,var,header,footer thì ta có thể sử dụng directive này.
Note:Thường thì trang được tạo footer,section mẫu thì ta chỉ nên để nội dung trong thẻ body,như vậy sẽ tránh được sự trùng lặp trong thẻ <head>
<%@include file="/common/header.jsp" %>
Hoặc :
<jsp:include page="/common/header.jsp"/>
Ta có thể đặt trên đầu trang hoăc trong thẻ body,điều khác nhau của hai cái này là
<%@include file="/common/header.jsp" %> sẽ được biên dịch trước khi chạy server ,khi đó server khởi động châm nhưng nó sẽ nhanh hơn trong quá trình sử dụng,còn <jsp:include page="/common/header.jsp"/> sẽ được load lại sau mỗi lần load trang,bởi vậy cái này lâu hơn
Trong header mẫu ,một trang jsp thừa kế header đó muốn truyền biến thì ta làm như sau:
Trang 12<jsp:include page="header.jsp">
<jsp:param value="Tom" name="userName"/> <jsp:param value="ADMIN" name="isAdmin"/> </jsp:include>
• <%@page %>
Trang 13 errorPage(Trang 492->495)
Trang 14• <%@taglib %>
Ví dụ:
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
Trang 15<%@taglib uri="http://java.sun.com/jstl/xml" prefix="x"%>
<%@taglib uri="http://java.sun.com/jstl/fmt" prefix="f"%>
<%@taglib uri="http://java.sun.com/jstl/sql" prefix="s"%>
Note:Phải thêm thư viện 2 thư viện jstl.jar và standard.jar vào thư mục INF/lib
Thay thế :Exception language :${pageScope.scope1}
hoặc :${pageScope.[“scope1”]}
Trang 16Cách lấy:
${initParam.Password}
Kq:2013
Lấy giá trị gửi từ trang jsp gửi đến thông qua name
(Giống phương thức getParametter của servlet)
<input type="text" name="abc"/><input type="submit" value="Submit"/> </form>
Bên trang Jsp Servlet 27- Jsp pageContext.jsp sẽ lấy giá trị của input có tên abc như sau:
Để lấy một object của một class ta có thể sử dụng useBean
Ví dụ class Student nằm trong package có tên ducky.models với thuộc tính là name
Trang 17kq: Get property name:Thao
Nếu muốn setProperty ta làm như sau:
<jsp:useBean id="student" class="ducky.models.Student" scope="request" /> <jsp:setProperty property="name" name="student" value="Dona"/>
Get property name:<jsp:getProperty property="name" name="student"/>
Kq: Get proerty name:Dona
của Java thì việc get và set property mới chạy được
Bây giờ ta xét trường hợp như sau:
Servlet:
Student student=new Student();
Trang 18request.setAttribute(“student”,student);
Jsp:
<jsp:useBean id="student" class="ducky.models.Student" scope="request" >
<jsp:setProperty property="name" name="student" value="Dona"/>
</jsp:useBean>
<jsp:getProperty property="name" name="student"/>
Nếu ta không có attribute có tên student thì nó vẫn tạo ra một useBean nhưng là useBean rỗng.Thẻ jsp:setProperty hiện tại đang nằm trong cặp thẻ jsp:useBean,nó chỉ thực hiện khi useBean là rỗng
Nếu useBean rỗng thì giá trị in ra là:Dona
Ngược lại,attribute có tên student tồn tại thì kết quả trả về là :Thao
Nếu ra muốn lấy value thông qua name của 1 trang jsp gửi đến trang jsp hiện tại,ta làm như sau:
Trang jsp submit:
<form action="Jsp Servlet 27- Jsp pageContext.jsp" method="get">
<input type="text" name="userName" value=”Minh”/>
<input type="submit" value="Submit"/>
</form>
Trang Jsp Servlet 27- Jsp pageContext.jsp là :
<jsp:useBean id="student" class="ducky.models.Student" scope="page" >
<jsp:setProperty property="name" name="student" param="userName"/> </jsp:useBean>
Get property name:<jsp:getProperty property="name" name="student"/>
Trang 19Lúc này attribute có tên student không tồn tại,nó vẫn tạo ra một useBean rỗng,sau
đó thực hiện hàm setProperty ,hàm setProperty lấy value thông qua tên userName
để gán vào thuộc tính name
Kq:Get property name:Minh
Nếu bỏ thuộc tính param đi thì hàm setProperty nó sẽ map tới trường nào có thuộc tính cùng tên với thuộc tính mà nó đang set rồi lấy giá trị value set cho thuộc tính đó
Ta xét về thuộc tính type của useBean:
Get property name:<jsp:getProperty property="name" name="student"/>
Trong thuộc tính type đó là đường dẫn đến một interface mà class Student
implements Hay nói cách khác,đó là supper class cha của class Student
3.1.4.<c:out>
3.1.4.<c:forEach>
Trang 213.1.5.<c:if>
Trang 243.1.6.<c:choose > <c:when></c:when> <c:otherwise></c:otherwise></c:choose>
Trang 253.1.7.<c:set>
Trang 273.1.8.<c:remove>
Trang 283.1.9.<c:import>
Trang 313.1.10.<c:url> (Trang 489->490) 3.1.11.<c:catch> (Trang 496->499)
Trang 323.2.Custom tag
a.Custom tag don’t have body.
Trong quá trình viết một web page, để ý sẽ thấy có những thành phần được lặp đi lặp lại rất nhiều lần mà trong đó chỉ khác nhau về giá trị của một tham số Mỗi một thành phần như vậy có thể được khai báo thành các thẻ, với các tham số truyền vào là các thuộc tính của thẻ đó Mỗi thẻ như vậy được gọi là một custom tag Việc sử dụng custom tag sẽ rút ngắn được khối lượng code trong trang jsp và cho phép các thành phần này có thể sử dụng lại sau này Bài viết này sẽ hướng dẫn các bạn cách để tạo ra một custom tag đơn giản
Custom tag trong ví dụ của chúng ta sẽ đơn giản là một tag cho phép ta chỉ ra một đoạn text và màu của đoạn text đó, rồi in đoạn text đó ra trên trang web với màu sắc tương ứng
Bình thường, để tạo ra một đoạn text có màu, nội dung của file index.jsp sẽ như sau:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>JSP Custom Tag Demo</title>
Trang 33public class ColorTextParser extends TagSupport { private String content;
private String color;
Trang 34public String getColor() {
Trang 36<description>This is a tag changes color of text</description>
<name>ColorText</name>//name tag to use in jsp
<tag-class>Model.ColorTextParser</tag-class>//path of class
<body-content>empty</body-content>//tag không được có gì trong thân
Có 4 giá trị : tagdependent,empty,JSP,scriptless
<attribute>
<name>content</name>//Phải trùng với tên thuộc tính trong class
<required>true</required>//true:bắt buộc phải gọi đối tượng này khi sd tag
<rtexprvalue>true</rtexprvalue>//true:cho ta biết thuộc tính content có thể
là một giá trị biểu thức Ví Dụ: color=”${colorCurrent}” YES
Trang 37Bây giờ tag mà ta vừa tạo có thể được đưa vào sử dụng trong file jsp, ta thay đổi nội dung của fileindex.jsp như sau
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib uri="http://coder.com/wedget" prefix="wgt" %>
Trang 39b.Custom tag have body.
Ví dụ về định dạng font sử dụng custom tag có body
package Model;
import java.io.IOException;
Trang 40import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.BodyContent;
import javax.servlet.jsp.tagext.BodyTagSupport;
import static javax.servlet.jsp.tagext.Tag.SKIP_BODY;
public class ChangeTextType extends BodyTagSupport{ private String kieu="";
Trang 41} catch (IOException ex) {
throw new JspException("Error:"+ex.getMessage()); }
Trang 42public void setKieu(String kieu) {
Trang 43<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP Page</title>
Trang 44Tổng hợp TagSupport và BodyTagSupport
Trang 45c.Tag menu
Giống như thẻ select trong html cũng chứa các item con đó là các option
Ta xây dựng hai class Menu và MenuItem:
package Model;
import java.io.IOException;
import java.util.ArrayList;
Trang 46import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;
public class Menu extends TagSupport{
private ArrayList items;
pageContext.getOut().println("Menu items are :"+items);
} catch (IOException ex) {
Logger.getLogger(Menu.class.getName()).log(Level.SEVERE, null, ex); }
Trang 47public class MenuItem extends TagSupport{
private String itemValue;
public int doEndTag() throws JspException {
Menu parent=(Menu)getParent();//trả về một tag cha bên ngoài
Trang 48public String getItemValue() {
<tag-class>Model.MenuItem</tag-class> <body-content>empty</body-content>
<attribute>
<name>itemValue</name>
<required>true</required>
Trang 49<%@taglib uri="http://coder.com/wedget" prefix="wgt" %>
<%@taglib tagdir="/WEB-INF/tags/" prefix="myTags" %>
Trang 51Ví dụ một file simple.tag nằm trong thư mục như trên:
<%@tag description="put the tag description here" language="java"
pageEncoding="UTF-8" %>
//set các thuộc tính như cấu hình trong file tld
//Sau đây là các thuộc tính được truyền vào từ file jsp.
<%@attribute name="message" required="false" rtexprvalue="true" %>
<%@attribute name="pathImage" required="true" rtexprvalue="true"%>
Trang 53<%@page contentType="text/html" pageEncoding="UTF-8" isErrorPage="false" errorPage="error page.jsp"%>
<%@taglib uri="http://coder.com/wedget" prefix="wgt" %>
<%@taglib tagdir="/WEB-INF/tags/" prefix="myTags" %>
Trang 54Ask:Container tìm tag file ở đâu?
Reply :
Trang 55Bởi vậy mà ta có thể nén thư mục thư mục META-INF có chứa tag file thành một file jar rồi inport vào thư viện của project.
Trang 563.3.JSP document syntax.
3.3.1 < jsp:plugin
The is used to display an object, especially an applet or a Bean on the client browser.
Syntax: <jsp: plugin type = "bean |applet" code = "ClassFileName" codeBase =
"ClassFileDirectoryName">
The <jsp:plugin> is used to display an object, especially an applet or a Bean on the client browser When the Jsp file is translated and compiled, the <jsp:plugin> is replaced by either an <object> or <embed> element, it is based on the browser version
Some of the attributes of <jsp: plugin> are defined below:
Trang 57type = "bean |applet" :- This type of object will be executed by the plug-in It must be either bean or an applet.
code = "ClassFileName" :- It is the name of the java class file which will be executed by the plug-in The use class extension is a must.
codebase = "ClassFileDirectoryName" :- It is the name of the directory that contains the java class file, that will be executed by the plug-in.
The code of the program is given below:
import java.applet.*;
import java.awt.*;
//<applet code = JavaApplet width = 300 height = 300></applet>
public class JavaApplet extends Applet{
public void paint(Graphics g){
g.drawString("Welcome in Java Applet.",40,20);
}
}
<jsp:plugin type="applet" code="JavaApplet" codebase=
"/tapan/jsp/jspexamples" width = "200" height = "200">