web applications the basics (part 2)
TRANSCRIPT
1
Web Applications – The Basics (Part 2)
Use case
• Say we want to write a simple “Hello” + current time page using Servlets
2
public class S1 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
response.getWriter().write("<html><head><title>Welcome page</title></head>
<body>Hello! The time is now " + new Date() + "</body></html>");
}
}
Java Servlet Pages
• Wouldn’t it be nice if we could concentrate on writing the HTML code and add Java code where it’s needed?
• Servlets: HTML code is printed using Java code
• JSP: Java code is embedded in HTML code
3
Java
HTML
HTML
JAVA
Based on slide by Yaron Kanza - 236369
4
Webapps/abc/j1.jsp <html>
<body>
Hello! The time is now <%= new java.util.Date() %>
</body>
</html>
5
http://localhost:8080/abc/j1.jsp
6
JSP – Behind the scenes
• An External DSL for generating HTML
• Server:
– Generates a Servlet Java code off of it
– Compiles
– Runs
• Has extensions (Tag-libraries)
7
Java Blocks <% %> <html>
<body>
<%
System.out.println( "Evaluating date now" ); //printed to console
java.util.Date date = new java.util.Date();
%>
Hello! The time is now
<%
out.println( date ); //same as response.getWriter().println(date)
out.println( "<br>Your machine's address is " );
out.println( request.getRemoteHost());
%>
</body>
</html>
8
http://localhost:8080/abc/j2.jsp
9
Webapps/abc/j2.jsp <html>
<body>
<ul>
<%
int i = 0;
while(i < 10) {
%>
<li> i = <%= i %> </li>
<%
++i;
}
%>
</ul>
</body>
</html>
Basic JSP Elements
10
HTML code: <html-tag>content</html-tag>
JSP Comments: <%-- comment --%>
Expressions: <%= expression %>
Scriptlets (statements): <% code %>
Declarations: <%! code %>
Directives: <%@ directive attribute="value" %>
Actions: <jsp:forward.../>, <jsp:include.../>
Expression-Language Expressions: ${expression}
Based on slide by Yaron Kanza - 236369
JSP = Servlet
11
<h1>A Random Number</h1>
<%= Math.random() %>
public void _jspService(HttpServletRequest request,
HttpServletResponse response)
throws java.io.IOException, ServletException {
...
response.setContentType("text/html");
...
out.write("<h1>A Random Number</h1>\r\n");
out.print( Math.random() );
out.write("\r\n");
...
} The generated servlet calls out.write() for Strings, and
out.print() for objects
Default content-type
Based on slide by Yaron Kanza - 236369
Scriplets translation
12
<%= foo() %>
<% bar(); %>
public void _jspService(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
...
response.setContentType("text/html");
...
out.print(foo());
bar();
...
}
Based on slide by Yaron Kanza - 236369
Compound translation
13
<% if (Math.random() < 0.5) { %>
You <b>won</b> the game!
<% } else { %>
You <b>lost</b> the game!
<% } %>
if (Math.random() < 0.5) {
out.write("You <b>won</b> the game!");
} else {
out.write("You <b>lost</b> the game!");
}
14
f8.html
15
Ajax
• Asynchronous JavaScript and XML
• User Interacts with the page
• Javascript code communicates with the server
– (In the background)
• When a response arrives – Page is updated
• Note: Data does not have to be XML-ed
16 webapps/abc/f8.html <html><body> <p>Team Name: <input id="input" type="text"/></p> <p>Suggestion: <span id="suggestion"></span></p> <script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"> </script> <script type="text/javascript"> $(document).ready(function() { var element = $("#input"); element.keyup(function() { var params = {}; params.url = "d3.html"; params.data = 'input=' + $("#input").val(); params.dataType = 'json'; params.type = 'get'; params.success = function(items) { var bullets = "<ul>"; for(var i = 0; i < items.length; ++i) bullets += "<li>" + items[i] + "</li>"; bullets += "</ul>"; $("#suggestion").html(bullets); }; $.ajax(params); }); }); </script></body></html>
17
Source code: S3.java package s1;
public class S3 extends HttpServlet {
private static final long serialVersionUID = -8846608158862513134L;
private static List<String> teams = Arrays.asList("Australia", "Japan",
... );
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
resp.setContentType("application/json");
resp.setCharacterEncoding("UTF-8");
String in = req.getParameter("input");
String result = process(in);
resp.getWriter().println(result);
}
private String process(String in) {
List<Match> matches = computeMatches(in);
Collections.sort(matches);
return computeOutput(matches);
}
18
Source code: S3.java (cont.) package s1;
public class S3 extends HttpServlet {
...
private String computeOutput(List<Match> matches) {
if(matches.size() == 0)
return "[]";
String result = "[" + matches.get(0).quote();
for(int i = 1; i < matches.size(); ++i) {
if(matches.get(i-1).compareTo(matches.get(i)) != 0)
break;
result += ", " + matches.get(i).quote();
}
result += "]";
return result;
}
}
19
Source code: Match.java public class Match implements Comparable<Match> {
public String team;
public int charCount = 0;
public Match(String team, String keyword) {
this.team = team;
if(keyword == null)
return;
Set<Character> s1 = Match.setOf(team);
Set<Character> s2 = Match.setOf(keyword);
s1.retainAll(s2);
this.charCount = s1.size();
}
public String quote() { return "\"" + team + "\""; }
@Override
public int compareTo(Match that) { return that.charCount - charCount; }
private static Set<Character> setOf(String s) {
s = s.toLowerCase();
HashSet<Character> result = new HashSet<Character>();
for(int i = 0; i < s.length(); ++i)
result.add(s.charAt(i));
return result;
}
}