· 7 years ago · Jan 06, 2019, 07:40 AM
1溫下=MVC圖 / 其他圖
2
3Advantages of JSP
4separates request processing and business logic from the presentation
5‧allows the separation of tasks between Java programmers and WEB page authors
6‧makes it easier to change presentation without affecting business layer and vice versa
7
8Servlet is a web component that is deployed on the server to create dynamic web page.
9
10
11
12
13Advantages of Servlet
14‧Secure
15‧Access to entire family of Java APIs
16‧Reliable, better performance and scalability
17‧Platform and server independent
18
19
20‧Servlet Problems:
21‧good Java knowledge is needed to develop and maintain the application
22‧changing look and feel or a new client type require changes to the Servlet code
23‧cannot use web page development tools
24
25Servlets contain (ç‡ç‡OK)
26‧request processing,
27‧business logic
28‧response generation
29
30What is JSP action?
31JSP action are predefined tags and perform action based on information
32JSP provides a list of standard tags for specific task to interact with java bean obeject
33
34What are the scopes available in <jsp:useBean>?
35(d) State and briefly explain the FOUR scopes in Java Bean.
36
37page scope
38It specifies that the object will be available for the entire JSP page but not outside the page.
39
40request scope
41 It specifies that the object will be associated with a particular request and exist as long as the request exists.
42
43‧session scope
44It specifies that the object will be available throughout the session with a particular client.
45
46?application scope
47‧It specifies that the object will be available throughout the entire Web application but not outside the application.
48
49
50
51(iii) Briefly describe the purpose of the HttpSession class?
52Need a mechanism to maintain client state across a series of
53requests from a same user (or originating from the same browser)
54over some period of time
55
56Main Enterprise Java Bean(3) EJB
57Session Bean
58A session bean
59implement the functionality of your application.
60represent a single client inside the Application Server.
61
62Stateful Session bean -Maintain conversational state when used by client.
63
64Stateless session bean-Do not maintain any conversational state
65-can offer better scalability
66
67Message Driven Bean -to implement messaging in your business logic.
68Entity Bean- to map an entry in a database table to a class. (Object Relational Mapping)
69
70
71
72benefits of using Java Enterprise Beans?
73EJB container provides System level services to enterprise java beans.
74EJB developer just focus on business logic and on solving business problems.
75The client developer can focus on the presentation of the client.
76The Bean developer can concentrate on solving business problems.
77
78
79Used in JSP as a containers for dynamic content
80‧A bean encapsulates data about one entity
81‧A reusable component
82‧to separate Business logic from the Presentation logic
83‧A Java class with some special format
84
85MVC-
86Why MVC Separate presentation from data
87‧ Make it easier to change presentation
88‧ Make it easier to change data
89‧ Make presentation objects more reusable !!!
90‧ Allow people to specialize in data or in presentation
91
92
93response.sendRedirect("/insertServlet");
94
95HttpSession theSession = request.getSession(true);
96// (i) Get the HttpSession object from request object.
97Basket bkt = (Basket) theSession.getAttribute("bkt");
98// (ii) (1) Get the attribute with name “bkt†from the session object.
99Item itm = new Item(id, desc, price);
100bkt.add(itm);
101theSession.setAttribute("bkt", bkt);
102
103ServletContext sc = getServletConfig().getServletContext();
104
105// (vi) Forward the result to the product.jsp page.
106sc.getRequestDispatcher("/product.jsp").forward(request, response);
107
108// (xi) Remove the attribute and destroy the session.
109theSession.removeAttribute("bkt");
110theSession.invalidate();
111
112
113Mel (Business process layer)
114- Models the data and behavior behind the business process.
115- Encapsulate of data and behavior which are independent of presentation.
116
117View (Presentation layer)
118- Display information according to client types
119- Display result of business logic (Model)
120- Not concerned with how the information was obtained, or from where
121
122Controller (Control layer)
123- Serves as the logical connection between the user's interaction and the business services on the back;
124it will control how the request should be handled and what information should be returned
125
126FOUR scope objects in Java Servlet and Java Server Page.
127FOUR scope objects for Servlet/JSP
128
1291. Web context (ServletConext)
130- Accessible from Web components within a Web context
1312. Session - Accessible from Web components handling a request that belongs to the session
1323. Request - Accessible from Web components handling the request.
133 The following scope object for JSP only
1344. Page- Accessible from JSP page that creates the object.
135
136
137====================================================================================
138ch3
139
140package ict.servlet; //!!!!!!!!!!!!!!
141import java.io.IOException;
142import java.io.PrintWriter;
143import javax.servlet.ServletException;
144import javax.servlet.annotation.WebServlet;
145import javax.servlet.http.*; //!!!!!!!!!!!
146@WebServlet(name = "Checkbox", urlPatterns = {"/checkbox"})//!!!!!!!!!!!!!!
147
148public class Checkbox extends HttpServlet { //!!!!!!!!!!!!!!!!!
149
150 public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException, IOException {
151 // doGet(....) // doPost(...)
152 res.setContentType("text/html");//!!!!!!!!!!!!
153
154 PrintWriter out = res.getWriter();//!!!!!!!!!
155
156
157 String[] ideName = req.getParameterValues("ide");//!! checkbox
158
159 out.println("<html>");
160 out.println("<head><title>radio button</title></head>");
161 out.println("<body>");
162 out.println("Your choices are :");
163
164
165 if (ideName != null) { //!!!!
166 for (int i = 0; i < ideName.length; i++) {
167 out.println("<br/><b>" + ideName[i]+"</b>");
168 }
169 }
170 out.println("</body></html>");
171 //out.close();
172 }
173}
174
175============================================================================
176The Servlet Life Cycle Handled by the Container
177
178‧ Instantiation:default constructor()
179– This happens once in the servlet's lifetime
180
181‧ Initialization-the init() method
182– To create an instanc of a Servlet class Done once
183– Overriding the init() method is your opportunity to perform one time initialization of data structures,
184database connections, class variables, and etc.
185
186‧ Service - the service() method
187– Calls the appropriate doXXX() method.
188– Each request is handled concurrently by threads
189
190‧ Destruction -the destroy() method
191– To destroy the Serlvet and tidy up the resources Done once
192
193
194
195Forward Vs Redirect
196
197Forward
198– a forward is performed internally by the servlet
199– the browser is completely unaware that it has taken place, so its original URL remains intact
200– any browser reload of the resulting page will simple repeat the original request, with the original URL
201
202Redirect
203– a redirect is a two step process, where the web application instructs the browser to fetch a second URL, which differs from the original
204– a browser reload of the second URL will not repeat the original request, but will rather fetch the second URL
205– redirect is marginally slower than a forward, since it requires two browser requests, not one
206– objects placed in the original request scope are not available to the second request
207
208‧ for SELECT operations,use a forward
209‧ for INSERT, UPDATE, or DELETE operations,use an redirect
210
211
212
213
214Servlets contain (controller)
215‧ request processing
216‧ business logic
217‧ response generation
218‧ all lumped together!
219=================================================================================================================================================
220Ch5.
221Scripting Elements
222‧Provide dynamic contents to a HTML page
223
224 ‧Scriptlets
225 <% java code %>
226
227‧?Expression
228 <%= expression %>
229 <%= 4+6 %> outputs 10 in the HTML
230 <%= varA + varB %>
231
232‧Declarations
233 <%! Define variables %>
234
235accessCount.jsp
236 ‧<h1>JSP Declaration</h1>
237<%! ‧// accessCount initialize only one time
238 private int accessCount = 0;
239%>
240<h2>Access to page since last compiling:
241‧<%= ++accessCount %>
242</h2>
243
244
245
246JSP Directive Elements
247 <%@ page import="pack1,pack2" %>
248<%@ page import="java.util.*" %>
249?<%@ page errorPage="relativeURL" %> //!!!!!
250?<%@ page isErrorPage="true" %?>
251<%@ include file="URL.jsp" %>
252
253<%@ taglib uri="/WEB-INF/tlds/Add-taglib.tld" prefix="ict" %>
254===============================================================================
255ch6
256<jsp:include page="relative url" />
257
258<jsp:include page="info.jsp">
259 <jsp:param value="Jesse" name="name"/>
260 <jsp:param value="TY" name="campus"/>
261</jsp:include>
262
263?Syntax 1:
264<jsp:forward page=“pagePath†/>
265?Syntax 2:
266?<jsp:forward page=“pagePath†>
267 <one or more <jsp:param> actions
268</jsp:forward>
269
270<jsp:useBean id=“pet†class=“ict.bean.Pet†scope=“page†/>
271<jsp:setProperty name=“pet†property=“name†value=“Fluffy†/>
272?<jsp:getProperty name=“pet†property=“name†/>
273
274<%
275 String name = request.getParameter("name");
276 int grade = Integer.parseInt(request.getParameter("grade"));
277 String[] course = request.getParameterValues("course");
278%>
279
280 <jsp:useBean id="s" class="ict.bean.Student" scope="request" />
281
282<jsp:setProperty name="s" property="name" value="<%=name%>"/>
283<jsp:setProperty name="s" property="grade" value="<%=grade%>"/>
284<jsp:setProperty name="s" property="course" value="<%=course%>"/>
285
286<jsp:setProperty name="s" property="name" param="name"/>
287<jsp:setProperty name="s" property="grade" param="grade" />
288<jsp:setProperty name="s" property="course" param="course" />
289
290<jsp:setProperty name=“s" property="*" />
291
292<jsp:setProperty name="MixBean" property="item" value=‘<%= request.getParameter("item") %>’/>
293
294Student.java
295
296public class Student implements Serializable { //import java.io.Serializable
297
298private String name; //attribute
299private int grade;
300private String[] course;
301
302 public Student () {} //Constructor!!!
303 public String[] getCourse() { return course;}//getter setter
304 public void setCourse(String[] course) {this.course = course;}
305 public int getGrade() {return grade;}
306 public void setGrade(int grade) {this.grade = grade;}
307 public String getName() {return name;}
308 public void setName(String name) {this.name = name;}
309}
310
311Syntax 1:
312 <jsp:forward page=“pagePath†/>
313?Syntax 2:
314<jsp:forward page=“pagePath†>
315 <one or more
316<jsp:param>
317 actions
318</jsp:forward>
319
320
321What are the scopes available in <jsp:useBean>
322page scope
323‧It specifies that the object will be available for the entire JSP page but not outside the page.
324request scope
325‧ It specifies that the object will be associated with a particular request and exist as long as the request exists.
326session scope
327‧ It specifies that the object will be available throughout the session with a particular client.
328application scope
329‧ It specifies that the object will be available throughout the entire Web application but not outside the application.
330
331Separation of
332‧data and business logic (Model)
333‧data presentation (View)
334‧data interaction (Controller)
335
336‧The user interacts with the Controller to ask for things to be done.
337?‧Controller forward the request to the Model
338‧?the result of the request is displayed by the View
339==========================================================================================================================
340SCOPES
341Scope |Accessibility |Lifetime
342Page |Current, pages |Within a page
343Request |Current, included, or forwarded pages |Until the response is returned to the user.
344Session |All requests from same browser within session |timeout Until session timeout or session ID invalidated (such as user quits browser)
345Application |All request to same Web application |Life of container or explicitly killed (such as container administration action)
346
347
348
349SCOPE IN WEB APPLICATION
350 ï¿ The pagescope refers to all information that only pertains to a specific instance of a given page.
351 The server keeps the page-specific information as long as the page exists.
352 ï¿ The session scope contains information pertaining to a session instance.
353 ï¿ The applicationscope contains information that is available to all sessions in the application, as long as the application is running.
354
355
356
357<% // initialize the attribute in different scope
358 if (pageContext.getAttribute("pageCount")==null) {
359 pageContext.setAttribute("pageCount", new Integer(0));
360 }
361 if (request.getAttribute("requestCount")==null) {
362 request.setAttribute("requestCount", new Integer(0));
363 }
364 if (session.getAttribute("sessionCount")==null) {
365 session.setAttribute("sessionCount",new Integer(0));
366 }
367 if (application.getAttribute("appCount")==null) {
368 application.setAttribute("appCount",new Integer(0));
369 }
370 %>
371
372
373<%
374// update the count in the respective scope
375Integer count = (Integer)pageContext.getAttribute("pageCount");
376pageContext.setAttribute("pageCount", new Integer(count.intValue()+1));
377Integer count2 = (Integer)session.getAttribute("sessionCount");
378session.setAttribute("sessionCount",new Integer(count2.intValue()+1));
379Integer count3 = (Integer)application.getAttribute("appCount");
380application.setAttribute("appCount",new Integer(count3.intValue()+1));
381Integer count4 = (Integer)request.getAttribute("requestCount");
382request.setAttribute("requestCount", new Integer(count4.intValue()+1));
383%>
384
385
386
387Page Count = <%= pageContext.getAttribute("pageCount")%><br/>
388Request Count = <%= request.getAttribute("requestCount")%> <br/>
389Session count = <%= session.getAttribute("sessionCount")%> <br/>
390Application count = <%= application.getAttribute("appCount")%> <br/>
391Time = <%= new java.sql.Time(System.currentTimeMillis()) %>
392==================================================================================================================
393TAG
394‧? Just like other descriptor file is put in WEB-INF\tlds
395Why Custom Tags?
396-Encapsulate business logic
397-Reusable & Maintainable
398-Separate presentation from business
399
400
401ict.tag.ExampleTag.java
40213
403package ict.tag;
404 import javax.servlet.jsp.*;
405import java.io.*;
406 import javax.servlet.jsp.tagext.SimpleTagSupport;
407 public class ExampleTag extends SimpleTagSupport {
408 @Override public void doTag() {
409 try {
410 PageContext pageContext = (PageContext) getJspContext();
411 JspWriter out = pageContext.getOut();
412 out.print("Custom tag example " + "(Example Tag)");
413 } catch (IOException e) {}
414 }
415}
416
417
418ict-taglib.tld
419
420<?xml version="1.0" encoding="UTF-8"?>
421<taglib version="2.1" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd">
422 <tlib-version>1.0</tlib-version>
423 <short-name>add-taglib</short-name>
424 <uri>/WEB-INF/tlds/Add-taglib</uri>
425 <tag>
426 <name>icon</name>
427 <tag-class>ict.tag.IconTag</tag-class>
428 <body-content>scriptless</body-content>
429 <attribute>
430 <name>message</name>
431 <required>true</required>
432 <type>java.lang.String</type>
433 <rtexprvalue>true</rtexprvalue>
434 </attribute>
435 <attribute>
436 <name>color</name>
437 <required>false</required>
438 <type>java.lang.String</type>
439 <rtexprvalue>true</rtexprvalue>
440 </attribute>
441 </tag>
442</taglib>
443
444ict.tag.IconTag.java
445
446package ict.tag;
447 import java.io.IOException;
448 import java.util.Date;
449 import java.util.Random;
450 import javax.servlet.jsp.*;
451 import javax.servlet.jsp.tagext.*;
452 public class IconTag extends SimpleTagSupport {
453 private String message;
454 private String color;
455 private String bgColor;
456 private String icon ;
457 private Random generator = new Random((new Date()).getTime());
458 private String getRandomColor() {
459 String[] num = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "A", "B", "C", "D", "E", "F"};
460 String rcolor = "";
461 for (int i = 0; i < 6; i++) {
462 rcolor += num[generator.nextInt(16)];
463 }
464 return rcolor;
465 }
466
467
468public IconTag() {
469 icon="ski";
470 bgColor = "FFFFFF";
471 message = "default";
472 this.color = getRandomColor();
473 }
474 public void setColor(String color) {
475 this.color = color;
476 }
477 public void setMessage(String message) {
478 this.message = message;
479 }
480 @Override
481 public void doTag() {
482 try {
483 PageContext pageContext = (PageContext) getJspContext();
484 JspWriter out = pageContext.getOut();
485 String url = "https://chart.googleapis.com/chart? chst=d_bubble_icon_text_small&chld="+icon+"|bb|" + message + "|" + bgColor + "|" + color;
486 out.print("<img src=\"" + url + "\" /><br/>");
487 } catch (IOException e) {
488 e.printStackTrace();
489 }
490 }
491}
492
493
494
495
496
497
498JSP use tab lib
499<%@taglib uri="/WEB-INF/tlds/ict-taglib.tld" prefix="ict" %>
500
501<ict:icon message="<%=message%>" /> !!//如果è¦ç”¨ <%= %> è¦SET => In .tld file, need to set <rtexprvalue>true</rtexprvalue>
502<ict:icon message="<%=message%>" color="00FFFF" />
503=================================================================================================================================================================
504Cookies
505What is the purpose of cookies in web development?
506//A popular tool for session tracking
507-Customizing a site for different users
508-identifying a user during an e-commerce session
509
510State TWO major problems of cookies.
511-The problem is privacy ,not security.
512Servers can remember your previous actions.
513card numbers directly in cookie
514
515setMaxAge(int seconds) //set 0 = DEL COOKIES SET è² æ•¸ 唔會SAVE
516<%
517 // create a cookies
518 Cookie cookie = new Cookie(“username",“Shum");
519 // set duration (one hour) for a cookies
520 cookie.setMaxAge(3600);
521 // c.setMaxAge(60*60*24*7); // One week
522 // sending cookie to the browser
523 response.addCookie(cookie);
524%>
525del cookie
526<%
527 Cookie cookie = new Cookie(“username",“");
528
529 cookie.setMaxAge(0);
530
531
532 response.addCookie(cookie);
533%>
534
535
536Show all Cookies
537<table border="1" align="center">
538 <tr><th>Cookie Name</th><th>Cookie Value</th></tr>
539 <%
540
541 // get all cookies from the request
542 Cookie[] cookies = request.getCookies();
543 if (cookies != null) {
544 Cookie cookie;
545 for (int i = 0; i < cookies.length; i++) {
546 cookie = cookies[i];
547 out.println("<tr>\n" + " <td>" + cookie.getName() + "\n" + "</td>"
548 + " <td>" + cookie.getValue() + "</td>");
549 }
550 }
551 %>
552</table>
553
554//find cookie //Cookie[] cookies = request.getCookies() //(cookie[i].getName //cookie[i].getValue();
555<%
556
557 // get all cookies from the request
558 Cookie[] cookies = request.getCookies();
559 if (cookies != null) {
560 Cookie cookie;
561 String result;
562 for (int i = 0; i < cookies.length; i++) {
563 cookie = cookies[i];
564 out.println("<tr>\n" + " <td>" + cookie.getName() + "\n" + "</td>"
565 + " <td>" + cookie.getValue() + "</td>");
566 if(cookie.getName.equals("search"){
567 result = cookie.getValue();
568 break;
569 }
570 }
571 }
572 %>
573======================================================================================================================
574Session
575HttpSession session=request.getSession(true);
576
577ShoppingCart cart = (ShoppingCart)session.getAttribute(“theCartâ€);
578
579Session.setAttribute(“theCartâ€,cart);
580
581 Remove the specified attribute
582session.removeAttribute("theCart");
583
584
585session.invalidate();
586
587
588
589session.getCreationTime()
590session.getAccessedTime()
591session.getMaxInactiveInterval();//?
592
593========================================================================================
594 public Connection getConnection() throws SQLException, IOException, ClassNotFoundException{
595
596 System.setProperty("jdbc.drivers","com.mysql.jdbc.Driver");
597 //Class.forName("com.mysql.jdbc.Driver");
598
599 return DriverManager.getConnection(url,username,password);
600 }
601 public arraylist createCustTable(){
602 ArrayList<bean> list = new ArrayList<bean>();
603
604 Statement stmnt=null;
605 Connection cnnt =null;
606 try{
607
608 cnnt = getConnection();
609 stmnt= cnnt.createStatement();
610 String sql="select * from customer";
611 ResultSet rs = stmnt.execute(sql);
612 while(rs.next()){
613 bean b = b.setAttr(rs.getString("field name"));
614 .....
615 list.add(b);
616 }
617 return list;
618
619
620
621 }catch(SQLException ex){
622 while(ex !=null){
623 ex.printStackTrace();
624 ex=ex.getNextException();
625 }
626 }catch(IOException ex){
627 ex.printStackTrace();
628 }catch(ClassNotFoundException ex){
629 ex.printStackTrace();
630 }
631 }
632
633
634
635 public boolean editRecord(CustomerBean cb){
636 Connection conn = null;
637 PreparedStatement pStmnt = null;
638 boolean isOK =false;
639
640 try{
641 conn = getConnection();
642 String preQueryStatement = "UPDATE customer SET name= ? ,tel= ?,age=? WHERE custId= ?";
643 pStmnt = conn.prepareStatement(preQueryStatement);
644
645 pStmnt.setString(1, cb.getName());
646 pStmnt.setString(2, cb.getTel());
647 pStmnt.setInt(3, cb.getAge());
648 pStmnt.setString(4, cb.getCusId());
649
650 int rowCount = pStmnt.executeUpdate();
651 if(rowCount>=1){
652 isOK=true;
653 }
654 }catch(SQLException ex){
655
656 ex.printStackTrace();
657
658 } catch (IOException ex) {
659 Logger.getLogger(CustomerDB.class.getName()).log(Level.SEVERE, null, ex);
660 } catch (ClassNotFoundException ex) {
661 Logger.getLogger(CustomerDB.class.getName()).log(Level.SEVERE, null, ex);
662 }
663 return isOK;
664 }