What u need is an organize code :)
In establishing a connection with you database
i think this is a more better way.
The code below shows how to connect or establish a connection.
as you can see, it is organized in a way that if you miss something, you will easily notice it.
Here are the steps:
1. Create a new class.
2. Study the code below and try to analyse it.
public Connection getConnection() {
final String USER_NAME ="You Username";
final String PASSWORD = "Your Password";
final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
final String JDBC_URL = "jdbc:mysql://localhost:3306/Your schema ";
Connection conn = null;
try{
Class.forName(JDBC_DRIVER);
conn = DriverManager.getConnection(JDBC_URL, USER_NAME, PASSWORD);
}catch(ClassNotFoundException e){
e.printStackTrace();
}catch(SQLException e){
e.printStackTrace();
}
return conn;
}
}
After that you can now create your servlet.
Here's how :
1. Create a new class, and put it in a package named: "app.servlet"
You should put all ur servlet classes in an app.servlet package so that it will be easy for you to look for things.
Our professor said that it is not neat to print from a servlet class. So dont do that. A servlet class should only be a servlet class, and not do anything that is not its purpose.
Create another class. The class that you should create is a class that will write into your database.
How should you write your servlet:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {