package com.jspdev.ch9;

import javax.servlet.*;
import javax.servlet.http.*;
import com.microsoft.jdbc.sqlserver.SQLServerDriver;
import java.sql.*;
import java.util.*;
import java.io.*;
public class AddMessageServlet extends HttpServlet
{

	private Connection con;
	public void doGet(HttpServletRequest request,
                      HttpServletResponse response)
        throws IOException, ServletException
    {
    	
    	String name=request.getParameter("name");
		String mail=request.getParameter("email");
		String title=request.getParameter("title");
		String content=request.getParameter("content");
		if(name==null)
		name="";
		if(title==null)
		title="";
		if(content==null)
		content="";
		if(mail==null)
		mail="";
		try
		{
			PreparedStatement stm=con.prepareStatement("insert into message values(?,?,?,?,?)");
			stm.setString(1,title);
			stm.setString(2,name);
			if(mail.length()==0)
			stm.setString(5,null);
			else stm.setString(5,mail);
			stm.setDate(3,new java.sql.Date(new java.util.Date().getTime()));
			stm.setString(4,content);
		    try 
			{
				stm.executeQuery();
			} 
			catch(Exception e) 
			{
			}			

		RequestDispatcher requestDispatcher = request.getRequestDispatcher("/viewMessages_servlet");
		requestDispatcher.forward(request,response);
		}
		catch(Exception e)
		{
			e.printStackTrace();		
		}
	}

	public void doPost(HttpServletRequest request,
	                      HttpServletResponse response)
	        throws IOException, ServletException
	    {
	    	doGet(request,response);
	    }
    public   AddMessageServlet()
    {
    	String CLASSFORNAME="com.microsoft.jdbc.sqlserver.SQLServerDriver";
	    String SERVANDDB="jdbc:microsoft:sqlserver://127.0.0.1:1433;DatabaseName=jspdev";
	    String USER="bn";
	    String PWD="bn"; 
	    try
	    {
	    	
	    	Class.forName(CLASSFORNAME);
			con = DriverManager.getConnection(SERVANDDB,USER,PWD);
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
	}
	
}

    	