1 21 22 package nu.xom.samples; 23 24 import java.io.IOException ; 25 import java.io.OutputStream ; 26 import java.math.BigInteger ; 27 28 import javax.servlet.http.HttpServlet ; 29 import javax.servlet.http.HttpServletRequest ; 30 import javax.servlet.http.HttpServletResponse ; 31 32 import nu.xom.Attribute; 33 import nu.xom.Document; 34 import nu.xom.Element; 35 import nu.xom.ProcessingInstruction; 36 import nu.xom.Serializer; 37 38 39 48 public class FibonacciServlet extends HttpServlet { 49 50 51 public void doGet( 52 HttpServletRequest request, HttpServletResponse response) 53 throws IOException { 54 55 int numberOfGenerations; 57 String generations = request.getParameter("generations"); 58 try { 59 numberOfGenerations = Integer.parseInt(generations); 60 } 61 catch (Exception ex) { numberOfGenerations = 10; 64 } 65 66 response.setContentType("text/xml; charset=UTF-8"); 67 OutputStream out = response.getOutputStream(); 68 69 Element root = new Element("Fibonacci_Numbers"); 70 Document doc = new Document(root); 71 ProcessingInstruction stylesheet = new 72 ProcessingInstruction("xml-stylesheet", 73 "type='text/css' HREF='/xml/styles/fibonacci.css'"); 74 doc.insertChild(stylesheet, 0); 75 76 BigInteger low = BigInteger.ONE; 77 BigInteger high = BigInteger.ONE; 78 for (int i = 1; i <= numberOfGenerations; i++) { 79 Element fibonacci = new Element("fibonacci"); 80 Attribute index 81 = new Attribute("index", String.valueOf(i)); 82 fibonacci.addAttribute(index); 83 fibonacci.appendChild(low.toString()); 84 root.appendChild(fibonacci); 85 86 BigInteger temp = high; 87 high = high.add(low); 88 low = temp; 89 } 90 Serializer serializer = new Serializer(out, "UTF-8"); 91 serializer.write(doc); 92 serializer.flush(); 93 out.close(); 94 95 } 96 97 98 public void doPost( 99 HttpServletRequest request, HttpServletResponse response) 100 throws IOException { 101 102 doGet(request, response); 103 104 } 105 106 } | Popular Tags |