Servlets

Υλοποίηση

Πλεονεκτήματα

Υποστήριξη

Παράδειγμα

import java.io.*;
import java.lang.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
 
 
public class comments extends HttpServlet {
 
    Connection con=null;
    //This is executed only once during servlet loading
    public void init(ServletConfig config) throws ServletException{
        super.init(config);
        try {
            Class.forName("org.postgresql.Driver");
            con=DriverManager.getConnection("jdbc:postgresql:comments",
                                                    "george","george");
        }
        catch (ClassNotFoundException e) {
            System.out.println("No such class:"+e.getMessage());
        }
        catch (SQLException s) {
            System.out.println("Connection error"+s.getMessage());
        }
    }
    //The function that handles POST requests
    public void doPost (HttpServletRequest req, HttpServletResponse res)
    throws ServletException,IOException{
        //Get input parameters
        String name=req.getParameter("name");
        String email=req.getParameter("email");
        String comments=req.getParameter("comments");
        PrintWriter out=res.getWriter();
        res.setContentType("text/html");
        //Insert the record into the database
        try {
            Statement stmt=con.createStatement();
            stmt.execute("INSERT INTO comments values('"+name+"','"+email+
                                                    "','"+comments+"')");
            out.println("All done ok");
        }
        catch (SQLException s) {
            out.println("Connection error"+s.getMessage());
        }
 
        finally {
            out.println("</BODY></HTML>");
        }
 
    }
    //GET and POST requests are handled in the same way
    public void doGet (HttpServletRequest req, HttpServletResponse res)
    throws ServletException,IOException{
        doPost (req,res);
    }
    //Only called when the servlet is unloaded
    public void destroy() {
        try {
            con.close();
        }
        catch (SQLException s) {
            System.out.println("Connection error"+s.getMessage());
        }
 
    }