This example shows how HTML <form>
works to send user input to backend.
-
login to mysql as a root user
local> mysql -u root -p
-
create a test user and grant privileges:
mysql> CREATE USER 'mytestuser'@'localhost' IDENTIFIED BY 'My6$Password'; mysql> GRANT ALL PRIVILEGES ON * . * TO 'mytestuser'@'localhost'; mysql> quit;
local> mysql -u mytestuser -p
mysql> CREATE DATABASE IF NOT EXISTS moviedbexample;
mysql> USE moviedbexample;
mysql> CREATE TABLE IF NOT EXISTS stars(
id varchar(10) primary key,
name varchar(100) not null,
birthYear integer
);
mysql> INSERT IGNORE INTO stars VALUES('755011', 'Arnold Schwarzeneggar', 1947);
mysql> INSERT IGNORE INTO stars VALUES('755017', 'Eddie Murphy', 1961);
- Clone this repository using
git clone
- Open IntelliJ IDEA -> Open -> (Find the location of the repository) -> Choose "cs122b-project2-form-example" directory -> Click "OK" -> wait until Sync is complete.
- In
WebContent/META-INF/context.xml
, make sure the mysql username ismytestuser
and password isMy6$Password
. - Also make sure you have the
moviedbexample
database. - In Tomcat Deployment Configuration, make sure the application context is: /cs122b-fall21-project2-form-example
- To run the example, follow the instructions on Canvas.
FormServlet.java
is a Java servlet that retrieves the data from HTML <form>
and then talks to the database and generates the result HTML <table>
For project 2, you are recommended to use tomcat to manage your DataSource instead of manually define MySQL connection in each of the servlet.
WebContent/META-INF/context.xml
contains a DataSource, with database information stored in it.
WEB-INF/web.xml
registers the DataSource to name jdbc/moviedbexample, which could be referred to anywhere in the project.
In both FormServlet.java
, a private DataSource reference dataSource is created with @Resource
annotation. It is a reference to the DataSource jdbc/moviedbexample
we registered in web.xml
To use DataSource, you can create a new connection to it by dataSource.getConnection()
, and you can use the connection as previous examples.