Uploaded by Diana Pop

Tutorial Servlet

advertisement
DISTRIBUTED SYSTEMS
Assignment 1
Servlet+Hibernate Tutorial
Ioan Salomie
Marcel Antal
Tudor Cioara
Claudia Daniela Pop
2016Guide
Ionut Anghel
Dorin Moldovan
Contents
A. Project Structure ....................................................................................................................................... 3
B. Write the source code: ............................................................................................................................. 8
C. Create the DB and a table ....................................................................................................................... 12
D. Finish the Configuration Files ................................................................................................................. 13
E. Run the Application:................................................................................................................................ 16
F. References............................................................................................................................................... 16
A. Project Structure
1. Create New Maven Project
2. Fill the project name. Change the packaging type from jar to war in order to create a web
project structure.
3. Create a WEB-INF folder inside the webapp folder
4. Add a new FILE to the WEB-INF folder (right-click -> New -> File). Name it web.xml and copy the
following content:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>a1.2</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
5. Add the index.html page in the Deployed Resources/webapp/ folder (right-click -> New -> HTML
File). Add the following code inside:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>LogIn</title>
<head>
<body>
<form action="login" method="post">
User name:<br>
<input type="text" name="username"><br>
User password:<br>
<input type="password" name="password">
<br><br>
<input type="submit" value="LogIn">
</form>
</body>
</html>
6. Create the packages for the Java files inside /src/main/java/ source folder. Add the following
empty classes inside each package:
a. UserDao in dao
b. User in entities
c. LoginServlet in servlet
7. Add two empty files in the /src/main/resources/ folder (right-click -> New -> File). The files will
be used later for hibernate configuration. Name the files:
-
hibernate.cfg.xml
user.hbm.xml
8. Check if the project structure is the same as in the following figure:
B. Write the source code:
The application will use the following classes:
User.java
package entities;
public class User {
private int id;
private String username;
private String password;
private String role;
public String getRole() {
return role;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public boolean isAdmin() {
return role.equals("admin");
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public void setRole(String role) {
this.role = role;
}
}
UserDao.java
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import entities.User;
public class UserDao {
private SessionFactory factory;
public UserDao() {
try {
factory = new Configuration().configure().buildSessionFactory();
} catch (HibernateException e) {
e.printStackTrace();
}
}
public User getUser(String username, String password) {
Session session = factory.openSession();
Transaction tx = null;
List<User> users = null;
try {
tx = session.beginTransaction();
org.hibernate.Query query = session.createQuery("FROM User WHERE username = :username AND
password = :password");
query.setParameter("username", username);
query.setParameter("password", password);
users = query.list();
tx.commit();
} catch (HibernateException e) {
if (tx != null) {
tx.rollback();
}
} finally {
session.close();
}
return users != null && !users.isEmpty() ? users.get(0) : null;
}
}
LoginServlet.java
package servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import dao.UserDao;
import entities.User;
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws IOException {
// add code for GET method
PrintWriter out = response.getWriter();
out.println("hello");
}
@Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
if ((!username.equals("") && !password.equals(""))) {
UserDao userDao = new UserDao();
User user = userDao.getUser(username, password);
if (user != null) {
if (!user.isAdmin()) {
createUserPage(response);
} else {
createAdminPage(response);
}
} else {
response.sendRedirect("index.html");
}
}
}
private void createAdminPage(HttpServletResponse response)
throws IOException {
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>User Page</title>");
out.println("</head>");
out.println("<body>");
out.println("Admin page");
out.println("</body>");
out.println("</html>");
out.close();
}
private void createUserPage(HttpServletResponse response)
throws IOException {
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>User Page</title>");
out.println("</head>");
out.println("<body>");
out.println("user page");
out.println("</body>");
out.println("</html>");
out.close();
}
}
C. Create the DB and a table
1. Open MySQL Workbench
2. Create a schema named userdb
3. Create a table named user with the following specification:
4. Add some data to the table
D. Finish the Configuration Files
The application contains 4 main configuration files: web.xml, pom.xml, hibernate.cfg.xml and
user.hbm.xml;
1. The Web.xml file that contains the definition of the landing page as well as the servlet name
mappings (colored in yellow):
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>a1.2</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>login</servlet-name>
<servlet-class>servlet.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
</web-app>
2. The pom.xml file contains the references to the dependeincies used by the application, in this
case the javax.servlet package, as well as the hibernate and the mysql packages. Add the
following content to the pom.xml file that already exists:
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.9.Final</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.5</version>
</dependency>
</dependencies>
The dependencies can be downloaded from: https://mvnrepository.com/
3. Create the hibernate configuration file hibernate.cfg.xml:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name="hibernate.connection.driver_class">
com.mysql.jdbc.Driver
</property>
<!-- Assume test is the database name -->
<property name="hibernate.connection.url">
jdbc:mysql://localhost:3306/userdb
</property>
<property name="hibernate.connection.username">
root
</property>
<property name="hibernate.connection.password">
root
</property>
<property
name="hibernate.current_session_context_class">thread</property>
<property name="hibernate.enable_lazy_load_no_trans">true</property>
<mapping resource="user.hbm.xml" />
</session-factory>
</hibernate-configuration>
4. Create the mapping file that maps the user to the database:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="entities.User" table="user">
<meta attribute="class-description">
This class contains the user detail.
</meta>
<id name="id" type="int" column="id">
<generator class="native" />
</id>
<property name="username" column="username" type="string" />
<property name="password" column="password" type="string" />
<property name="role" column="role" type="string" />
</class>
</hibernate-mapping>
E. Run the Application:
A web page for login should appear. If the user introduces admin credentials, it will be redirected to the
admin page. If the user introduces user credentials, it will be redirected to user page. Otherwise it will
be redirected again to the login.
F. References
The full application can be downloaded at:
-
https://bitbucket.org/utcn_dsrl/tutorial_servlet_1/overview
Download