Basic Internet Programming 2004 Java Server Pages (JSP) Webapp filters Cristian Bogdan [email protected] Björn Eiderbäck [email protected] JSP: Pragmatisk exempelorienterad beskrivning Webapp Filters JSP taglibs Basic Internet Programming JSP and Webapp Filters Vad är JSP? En blandning av Java och XHTML/HTML Man kan skriva stora delar av websidorna med HTML och skriva script i Java och/eller inkludera Java-kod Den som inte kan Java kan enklare delta och konstruera stora delar av sidorna Servlet containers generate servlets out of the JSP pages, which contain request.getWriter().print(…) for every HTML string in the page Since JSP pages are servlets as well, they have all the servlet functionality 1 Basic Internet Programming JSP and Webapp Filters Exempel <%@page language="java" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD><TITLE>Welcome!</TITLE></HEAD> <BODY> You are connecting from <% out.println(request.getRemoteHost()); %> <BR> <TABLE border=1> <%for(java.util.Enumeration e=request.getHeaderNames(); e.hasMoreElements(); ) { %> <% String headerName= (String)e.nextElement(); %> <TR><TD><%=headerName %> <TD><%= request.getHeader(headerName)%> <% } %> </TABLE> </BODY> </HTML> Basic Internet Programming JSP and Webapp Filters Fördelar med JSP jämfört med andra tekniker Jämfört med ASP Java är kraftfullara än Basic och mer portabelt Jämfört med PHP Java mer vidspritt och kraftfullare språk, dvs Java Jämfört med rena servlets JSP översätts till servlet men det kan vara smidigare och enklare att skriva mer HTML-lika beskrivningar för websidor. För mer programmeringsintensiva delar passar servletar bättre Jämfört med Server Side Includes (SSI) SSI spritt men JSP har en rikare flora av verktyg Jämfört med JavaScript Java kraftfullare, enklare att skriva modulärt osv 2 Basic Internet Programming JSP and Webapp Filters Fördefinierade variabler pageContext request response session out Exempel z z javax.servlet.jsp.PageContext javax.servlet.http.HttpServletRequest javax.servlet.http. HttpServletResponse javax.servlet.http.HttpSession javax.servlet.jsp.JspWriter <%= request.getRemoteHost() %> <%= pageContext.getRequest().getRemoteHost() %> Basic Internet Programming JSP and Webapp Filters JSP:s JSP:s element element Siddirektiv <%@ page… import= … contentType=..%> Kommentar <%-- Kommentar --%> Scriplet <% Javakod %> Utmatning <%= ... %> Lite vanlig HTML blandad med Java <I> <%= request.getParameter("title") %></I> Kan också skrivas <% out.print("Lite vanlig HTML blandad med Java <I>"); out.print(request.getParameter("title") ; out.println("</I>"); 3 Basic Internet Programming JSP and Webapp Filters Deklarationer Class-level declarations, outside the service() method <%! Javakod %> Skrivs mellan <%! Javakod %> <%! private int accessCount = 0; %> Accesses to page since server reboot: <%= ++accessCount %> Basic Internet Programming JSP and Webapp Filters Other JSP issues Det går alternativt att använda XML-taggar istället En JSP översätts till servlet och kompileras till en servlet första gången den anropas I denna version av Tomcat hamnar servlet och kompilerad kod i $CATALINA_HOME/work/localhost 4 Basic Internet Programming JSP and Webapp Filters Page context attributes Attributes visible only within the page (one request can include more pages via RequestDispatcher.include() or forward()) PageContext.setAttribute(String name, Object value, int scope) scope can be PageContext.PAGE_SCOPE (default), PageContext.REQUEST_SCOPE (request attrs), PageContext.SESSION_SCOPE (session attrs), PageContext.APPLICATION_SCOPE (accessible to all servlets and JSPs within the same webapp) PageContext.getAttribute(String name, int scope) Basic Internet Programming JSP and Webapp Filters Att Att använda använda bönor bönor (eng (eng Beans) Beans) och och JSP JSP Med Java-bönor kan vi inkludera, läsa och uppdatera vanliga klasser Se http://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/Servlet-TutorialJSP.html#Section8 5 Basic Internet Programming JSP and Webapp Filters Ett exempel <%@ page import = "num.NumberGuessBean" %> <jsp:useBean id="numguess" class="num.NumberGuessBean" scope="session"/> <jsp:setProperty name="numguess" property="*"/> <html> <head><title>Number Guess</title></head> <body bgcolor="white"> <font size=4> Basic Internet Programming JSP and Webapp Filters ... <% if (numguess.getSuccess()) { %> Congratulations! You got it. And after just <%= numguess.getNumGuesses() %> tries.<p> <% numguess.reset(); %> Care to <a href="numguess.jsp">try again</a>? <% } else if (numguess.getNumGuesses() == 0) { %> Welcome to the Number Guess game.<p> 6 Basic Internet Programming JSP and Webapp Filters ... I'm thinking of a number between 1 and 100.<p> <form method=get> What's your guess? <input type=text name=guess> <input type=submit value="Submit"> </form> <% } else { %> Good guess, but nope. %></b>. Try <b><%= numguess.getHint() You have made <%= numguess.getNumGuesses() %> guesses.<p> Basic Internet Programming JSP and Webapp Filters ... I'm thinking of a number between 1 and 100.<p> <form method=get> What's your guess? <input type=text name=guess> <input type=submit value="Submit"> </form> <% } %> </font> </body> </html> 7 Basic Internet Programming JSP and Webapp Filters num.NumberGuessBean.java package num; import java.util.*; public class NumberGuessBean { int answer; boolean success; String hint; int numGuesses; public NumberGuessBean() { reset(); } Basic Internet Programming JSP and Webapp Filters ... public void setGuess(String guess) { numGuesses++; int g; try { g = Integer.parseInt(guess); } catch (NumberFormatException e) { g = -1; } if (g == answer) { success = true; } else if (g == -1) { hint = "a number next time"; } 8 Basic Internet Programming JSP and Webapp Filters ... else if (g < answer) { hint = "higher"; } else if (g > answer) { hint = "lower"; } } public boolean getSuccess() { return success; } public String getHint() { return "" + hint; } Basic Internet Programming JSP and Webapp Filters ... public int getNumGuesses() { return numGuesses; } public void reset() { answer = Math.abs(new Random().nextInt() % 100) + 1; success = false; numGuesses = 0; } } 9 Basic Internet Programming JSP and Webapp Filters Fler exempel Vi tittar lite snabbt på exemplen i Tomcat Basic Internet Programming JSP and Webapp Filters Integrera Integrera Servlets Servlets och och JSP JSP Man kan integrera Servlet och JSP med varandra Den ena kan skicka data till den andra genom att tex utöka och skicka vidare innehållet i requestvariabeln, använda sessionsvariabler mm 10 Basic Internet Programming JSP and Webapp Filters Servlet-JSP: Skicka vidare ”request” I Servlet definiera URL för JSP-sida String url = ”/katalog/sida.jsp”; Skicka vidare kontroll till JSP-sidan RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url); dispatcher.forward(request, response); In this scenario, the servlet decides which JSP to invoke, depending on its internal logic Basic Internet Programming JSP and Webapp Filters Servlet-JSP:communication via attributes Använd någon av Servlet SomeClass value = new SomeClass(...); request.setAttribute(”key”, value); JSP <jsp:useBean id=”key” class=”SomeClass” scope=”request” /> Servlet HttpSession session = request.getSession(true); session.setAttribute(”key”, value); JSP <jsp:useBean id=”key” class=”SomeClass” scope=”session” /> 11 Basic Internet Programming JSP and Webapp Filters Communication via Web application-level attributes Servlet getServletContext().setAttribute(”key”, value); JSP <jsp:useBean id=”key” class=”SomeClass” scope=”application” /> Basic Internet Programming JSP and Webapp Filters Custom JSP tag libraries <%@ taglib uri="http://www.taglibprovider.com/name" prefix=”special" %> <HTML>… <special:makeBold>this text will become bold</special:makeBold> <special:timeOfDay format=”hh:MM:ss” /> </HTML> javax.servlet.jsp.tagext.*, Tag, BodyTag… Tag library descriptor (TLD): info on each tag and params Install the tag library in your web.xml <taglib> <taglib-uri>http://jakarta.apache.org/taglibs/mailer-1.0</taglib-uri> <taglib-location>/WEB-INF/mailer.tld</taglib-location> </taglib> 12 Basic Internet Programming JSP and Webapp Filters Standard Tag Library (JSTL) Problem: hard to program taglibs when the JSP author can use Java scriplets near the custom tags Simple programming within the page (instead of Java) <c:forEach items="${orders}" var="order"> <c:out value="${order.id}"/> </c:forEach> The expression language (EL) ${order.id+order1.id2} EL supported in soon-to-come JSP 2.0, phasing out Java <%scriplets %> Basic Internet Programming JSP and Webapp Filters Filters Using a servlet to dispatch JSPs or other servlets (by forwarding the ”request”) centralizes all accesses to that servlet. All forms will have to be submitted to that servlet as ”action”, which looks ugly in the browser Filters are similar with operating system filters: program1 | program2 | program3 filter1| filter2| filter3 | contentGenerator contentGenerator can be a servlet, JSP or simple HTML 13 Basic Internet Programming JSP and Webapp Filters … Servlets could do content filtering with include() but filters are more standard and more powerful filters just need to be configured in web.xml to take effect, with servlets you would have to change Java code filters can alter the request and the response (using wrappers) and the generated content Controller filters (MVC), authentication filters, Logging filters, etc. Basic Internet Programming JSP and Webapp Filters Filter basics, wrappers A basic filter public class MyFilter implements javax.servlet.Filter{ public void init(javax.servlet.FilterConfig c) {… } public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)throws ServletException, java.io.IOException { … chain.doFilter(req, resp); …} // invoke the filter chain public void destroy(){} } We can pass ”wrapped” request and response to doFilter() class MyRequest extends HttpServletRequestWrapper { MyRequest(HttpServletRequest req) { super(req); } public String getRemoteUser(){return getRequest().getRemoteUser()+”a”;} public String getQueryString() { … } } // we can redefine any other ServletRequest method! Easier to define wrappers as anonymous inner classes ServletRequest req1= new HttpServletRequestWrapper(req){ public String getRemoteUser(){ }… public String getQueryString(){ }… }; 14 Basic Internet Programming JSP and Webapp Filters Länkar Tutorial från SUN http://java.sun.com/products/jsp/ JSP 2.0: http://jcp.org/aboutJava/communityprocess/first/jsr152/ Standard tag library http://java.sun.com/products/jsp/jstl/ http://jakarta.apache.org/taglibs Tutorial av Marty Hall http://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/ http://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/ServletTutorial-JSP.html Diverse resurser http://www.corewebprogramming.com/ 15