1 |
torben |
609 |
|
2 |
|
|
|
3 |
|
|
import java.io.IOException; |
4 |
|
|
import javax.servlet.ServletException; |
5 |
|
|
import javax.servlet.http.HttpServletRequest; |
6 |
|
|
import javax.servlet.http.HttpServletResponse; |
7 |
|
|
|
8 |
|
|
|
9 |
|
|
|
10 |
|
|
public class TestServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet { |
11 |
|
|
|
12 |
|
|
static final long serialVersionUID = 1; |
13 |
|
|
|
14 |
|
|
public TestServlet() { |
15 |
|
|
super(); |
16 |
|
|
} |
17 |
|
|
|
18 |
|
|
|
19 |
|
|
|
20 |
|
|
|
21 |
|
|
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { |
22 |
|
|
|
23 |
|
|
int count = parseArguments(request); |
24 |
|
|
String resp = buildResponse(count); |
25 |
|
|
|
26 |
|
|
response.setContentType("text/html"); |
27 |
|
|
response.getWriter().print( resp ); |
28 |
|
|
} |
29 |
|
|
|
30 |
|
|
|
31 |
|
|
|
32 |
|
|
protected int parseArguments(HttpServletRequest request) { |
33 |
|
|
int count = 10; |
34 |
|
|
String countStr = request.getParameter("count"); |
35 |
|
|
if (countStr != null) |
36 |
|
|
{ |
37 |
|
|
try |
38 |
|
|
{ |
39 |
|
|
int radix = 10; |
40 |
|
|
if (countStr.length() >2 && countStr.substring(0, 2).equalsIgnoreCase("0x") ) |
41 |
|
|
{ |
42 |
|
|
radix = 16; |
43 |
|
|
countStr = countStr.substring(2); |
44 |
|
|
} |
45 |
|
|
|
46 |
|
|
count = Integer.parseInt(countStr,radix); |
47 |
|
|
count = Math.min(count, 1000); //overflow protection |
48 |
|
|
count = Math.max(count, 5); //min 5 rows |
49 |
|
|
} catch (NumberFormatException e) |
50 |
|
|
{ |
51 |
|
|
//System.out.println(e); |
52 |
|
|
} |
53 |
|
|
} |
54 |
|
|
return count; |
55 |
|
|
} |
56 |
|
|
|
57 |
|
|
protected String buildResponse(int count) |
58 |
|
|
{ |
59 |
|
|
StringBuilder sb = new StringBuilder(); |
60 |
|
|
sb.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">"); |
61 |
|
|
sb.append("<html><head><title>Servlet hello world</title></head><body>\n"); |
62 |
|
|
//sb.append("<form action='' method='get'><input type='text' name='count'value='").append(count).append("'></form><br>"); |
63 |
|
|
for (int i=1; i<=count; i++) { |
64 |
|
|
sb.append("Hello World! #").append( i ).append(" <br>\n"); |
65 |
|
|
} |
66 |
|
|
sb.append("</body></html>"); |
67 |
|
|
|
68 |
|
|
return sb.toString(); |
69 |
|
|
} |
70 |
|
|
} |