Java Tutorial/Servlet/URL Rewrite
Servlet Query String
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
public class MyServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/plain");
PrintWriter out = res.getWriter();
out.println("Query String:");
out.println(req.getQueryString());
out.println();
out.println("Request Parameters:");
Enumeration e = req.getParameterNames();
while (e.hasMoreElements()) {
String name = (String) e.nextElement();
String values[] = req.getParameterValues(name);
if (values != null) {
for (int i = 0; i < values.length; i++) {
out.println(name + " (" + i + "): " + values[i]);
}
}
}
}
}
Servlet URL Rewrite
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
public class MyServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, java.io.IOException {
response.setContentType("text/html");
java.io.PrintWriter out = response.getWriter();
String contextPath = request.getContextPath();
String encodedUrl = response.encodeURL(contextPath + "/default.jsp");
out.println("<html>");
out.println("<head>");
out.println("<title>URL Rewriter</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>This page will use URL rewriting if necessary</h2>");
out.println("Go to the default.jsp page
== URL rewriting ==
<!-- start source code -->
<source lang="java">
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class CounterRewrite extends HttpServlet {
static final String COUNTER_KEY = "Counter.count";
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
IOException {
HttpSession session = req.getSession(true);
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
int count = 1;
Integer i = (Integer) session.getAttribute(COUNTER_KEY);
if (i != null) {
count = i.intValue() + 1;
}
session.setAttribute(COUNTER_KEY, new Integer(count));
out.println("<html>");
out.println("<head>");
out.println("<title>Session Counter</title>");
out.println("</head>");
out.println("<body>");
out.println("Your session ID is <b>" + session.getId());
out.println("</b> and you have hit this page <b>" + count
+ "</b> time(s) during this browser session");
String url = req.getRequestURI();
out.println("<form method=GET action=\"" + resp.encodeURL(url) + "\">");
out.println("<input type=submit " + "value=\"Hit page again\">");
out.println("</form>");
out.println("</body>");
out.println("</html>");
out.flush();
}
}