Web Science/Part1: Foundations of the web/Dynamic Web Content/Handling a post request in a Java Servlet/script

Register.java

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.webapp.WebAppContext;

public class Register extends HttpServlet {

	private Connection connect = null;
	private Statement statement = null;
	private ResultSet resultSet = null;

	public Register() {
		try {
			Class.forName("com.mysql.jdbc.Driver");
			// Setup the connection with the DB
			connect = DriverManager
					.getConnection("jdbc:mysql://localhost/mooc?"
							+ "user=mooc&password=studywebscience");

			// Statements allow to issue SQL queries to the database
			statement = connect.createStatement();
			// Result set get the result of the SQL query
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		resp.getWriter().write("hello world");
	}

	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String sql = "insert into mooc.users values(default, '"
				+ req.getParameter("username") + "', '"
				+ req.getParameter("email") + "')";

		resp.setContentType("text/html");
		
		try {
			statement.execute(sql);
			resp.getWriter().write(
					"received username:<b>" + req.getParameter("username")
							+ "</b>, with email: <em>"
							+ req.getParameter("email") + "</em>");
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public static void main(String[] args) throws Exception {
		Server server = new Server(8080);

		WebAppContext context = new WebAppContext();
		context.setDescriptor("WEB-INF/web.xml");
		context.setResourceBase("");
		context.setContextPath("");
		context.setParentLoaderPriority(true);

		server.setHandler(context);

		server.start();
		server.join();
	}
}