I'm trying to do a very simple java web app which allows to informations of a person: fristname, surname, date of birth and store them in a MySql db.
The issue is that when I try to insert a date(e.g.07/03/2019), on db the date is one day before(06/03/2019).
How is it possible to fix that?
Below the code:
The bean
package bean;
import java.io.Serializable;
import java.sql.Date;
public class Persona implements Serializable {
private int idPersona;
private String nome;
private String cognome;
private Date dataNascita;
public Persona() {
super();
}
public Persona(String nome, String cognome, Date dataNascita) {
super();
this.nome = nome;
this.cognome = cognome;
this.dataNascita = dataNascita;
}
public Persona(int idPersona, String nome, String cognome, Date dataNascita)
{
super();
this.idPersona = idPersona;
this.nome = nome;
this.cognome = cognome;
this.dataNascita = dataNascita;
}
public int getIdPersona() {
return idPersona;
}
public void setIdPersona(int idPersona) {
this.idPersona = idPersona;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getCognome() {
return cognome;
}
public void setCognome(String cognome) {
this.cognome = cognome;
}
public Date getDataNascita() {
return dataNascita;
}
public void setDataNascita(Date dataNascita) {
this.dataNascita = dataNascita;
}
}
The servlet
package servlet;
import java.io.IOException;
import java.sql.Date;
import java.sql.SQLException;
import java.text.ParseException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import bean.Persona;
import dao.ProvaDao;
import utility.ManipolazioneDate;
#WebServlet("/Inserimento")
public class Inserimento extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* Default constructor.
*/
public Inserimento() {
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
String nome = request.getParameter("nome");
String cognome = request.getParameter("cognome");
String dataNascita = request.getParameter("dataNascita");
Date dataN = null;
try {
dataN = (Date) ManipolazioneDate.convertiData(dataNascita);
} catch (ParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Persona p = new Persona(nome, cognome, dataN);
System.out.println(p.getNome());
System.out.println(p.getCognome());
System.out.println(p.getDataNascita());
try{
ProvaDao.registraPersona(p);
}catch(SQLException e){
e.printStackTrace();
}
}
}
A class with a static method to parse a String date format into a java.sql.Date format
package utility;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class ManipolazioneDate {
public static Date convertiData(String data) throws ParseException{
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
Date parser = format.parse(data);
java.sql.Date dataSql = new java.sql.Date(parser.getTime());
return dataSql;
}
}
Dao
package dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import bean.Persona;
import utility.Connessione;
public class ProvaDao {
public static void registraPersona(Persona persona) throws SQLException{
Connection conn = Connessione.getConnection();
PreparedStatement ps = null;
String ins = "insert into prova2.persona(nome, cognome, dataNascita)
values(?,?,?)";
try{
ps = conn.prepareStatement(ins);
ps.setString(1, persona.getNome());
ps.setString(2, persona.getCognome());
ps.setDate(3, persona.getDataNascita());
ps.executeUpdate();
System.out.println("Persona inserita");
}catch(SQLException e){
System.out.println(e.getMessage());
System.out.println("Errore nell'inserimento");
}finally{
if(ps != null){
ps.close();
}
if(conn != null){
conn.close();
}
}
}
}
JSP with form
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<div align="center">
<form action="/Prova/Inserimento" method="get">
<p>Nome</p>
<input type="text" value="" name="nome">
<br>
<p>Cognome</p>
<input type="text" value"" name="cognome">
<br>
<p>Data di nascita</p>
<input type="text" value="" name="dataNascita">
<br>
<input type="submit" value="Invia">
</form>
</div>
</body>
</html>
Thank you.
Maybe code is not wrong. (Because code does not manipulate datetime.)
At java code, do SELECT CURRENT_TIMESTAMP; get and check the timestamp. If the timestamp is wrong, it is due to MySQL server.
Related
I am trying to get the values from a form in order to create an object with those values. How would I do this? Also currently when I hit submit I get the http 404 error. I know I'm doing this wrong, I just don't know how to fix it!
I have created the form with the following code:
<html lang="en">
<head>
<title>Example</title>
</head>
<body>
<h1>Welcome to Loggy!</h1>
<form id="logForm" action="LogsServlet" method="GET">
<h3>What have you been up to today?</h3>
<br>
<label id="logTitleLabel" for="logTitle">Title :</label>
<br>
<input type="text" id="logTitle" name="logTitle">
<br>
<label id="logDescriptionLabel" for="LogDescription">Description</label>
<br>
<input type="text" id="logDescription" name="logDescription">
<label id="logContentLabel" for="logContent">Content :</label>
<br>
<input type="text" id="logContent" name="logContent">
<button type="submit" id="submitLog">Submit Log</button>
</form>
</body>
</html>
Here are the abstract Log Class and TextLog Class:
import java.sql.Timestamp;
import java.util.Date;
import java.util.UUID;
public abstract class Log {
private UUID id;
private String title;
private String description;
private String content;
private Timestamp createTimestamp;
//Constructor
Log(String title,String description, String content){
this.setTitle(title);
this.description=description;
this.content=content;
};
public void create() {
//call UUID method
id();
//create new timeStamp
Date date= new Date();
Timestamp createTimestamp = new Timestamp(date.getTime());
this.createTimestamp=createTimestamp;
}
public UUID id() {
UUID uuid = UUID.randomUUID();
id = uuid;
return id;
}
//GETTERS AND SETTERS
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Timestamp getCreateTimestamp() {
return createTimestamp;
}
public void setCreateTimestamp(Timestamp createTimestamp) {
this.createTimestamp = createTimestamp;
}
}
public class TextLog extends Log {
public TextLog(String title,String description, String content) {
super(title,description, content);
}
}
I am trying to get the values from the form and then create a Log object of type TextLog with the variables submitted in the form. Here is my 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;
/**
* Servlet implementation class LogsServlet
*/
//#WebServlet(description = "Loggy Logs", urlPatterns = { "/LogsServlet" })
public class LogsServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public LogsServlet() {
super();
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//set content type
response.setContentType("text/html");
//get print writer
PrintWriter writer = response.getWriter();
//generate content
request.getParameter("logTitle");
request.getParameter("logDescription");
request.getParameter("logContent");
}
}
This is the first time I have worked with this, and I am quite lost of how to set it! I will also have to display the object in a list after and add it to a database if that makes a difference.
Any advice would be appreciated!
This is a common issue on Tomcat 10 because the change from Java EE to Jakarta EE, so you can change your project, using Jakarta EE 9
<dependency>
<groupId>jakarta.platform</groupId>
<artifactId>jakarta.jakartaee-api</artifactId>
<version>9.0.0</version>
<scope>provided</scope>
</dependency>
and importing this packages
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
If you don´t want do that, you can downgrade to Tomcat 9. Don´t forget uncomment
//#WebServlet(description = "Loggy Logs", urlPatterns = { "/LogsServlet" })
For related documentation follow this link
Tomcat 10.0.4 doesn't load servlets (#WebServlet classes) with 404 error
so i made simple site where i can add products to list (text area) using Spring framework 4.0.1, i can see page content but in text area on the bottom there is this exception preventing me from getting products on list.
Model class
package model;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
*
* #author mkSS
*/
public class Products {
public int product_id;
public String productname;
public String productstock;
public String productdescription;
public int getProduct_id() {
return product_id;
}
public void setProduct_id(int product_id) {
this.product_id = product_id;
}
public String getProductname() {
return productname;
}
public void setProductname(String productname) {
this.productname = productname;
}
public String getProductstock() {
return productstock;
}
public void setProductstock(String productstock) {
this.productstock = productstock;
}
public String getProductdescription() {
return productdescription;
}
public void setProductdescription(String productdescription) {
this.productdescription = productdescription;
}
public static String productList() throws ClassNotFoundException, SQLException {
StringBuilder product_list = new StringBuilder();
Class.forName("com.mysql.jdbc.Driver");
try (java.sql.Connection conn= DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "miksa988");){
Statement st= conn.createStatement();
st.executeQuery("select productname, productstock,productdescription from products");
ResultSet rs= st.getResultSet();
while (rs.next()){
product_list.append(rs.getString("productname"));
product_list.append(rs.getString(", "));
product_list.append(rs.getString("productstock"));
product_list.append(rs.getString(", "));
product_list.append(rs.getString("productdescription"));
product_list.append(rs.getString("\n"));
}
} catch(SQLException ex){
product_list.append(ex.getMessage());
}
return product_list.toString();
}
public void addProduct() throws ClassNotFoundException {
Class.forName("com.mysql.jdbc.Driver");
try (java.sql.Connection conn= DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "miksa988");){
if (productname !=null && !(productname.isEmpty()) && productstock !=null && !(productstock.isEmpty()) && productdescription !=null && !(productdescription.isEmpty())){
Statement st = conn.createStatement();
st.execute("insert into products (productname,productstock, productdescription) values ('"+ productname + "','"+productstock+"','"+productdescription+"')");
}
}catch(SQLException ex){
System.out.println("Error while trying to connect with databse"+ex);
}
}
}
And now this is my controller class
package controller;
import java.sql.SQLException;
import model.Products;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
#Controller
public class ProductController {
#RequestMapping(value = "/product", method= RequestMethod.GET)
public String createForm(ModelMap model) throws ClassNotFoundException, SQLException{
model.addAttribute("product", new Products());
model.addAttribute("products", Products.productList() );
return "product";
}
#RequestMapping(value = "/product", method= RequestMethod.POST)
public String addProduct(#ModelAttribute("product") Products product , ModelMap model) throws ClassNotFoundException ,SQLException {
product.addProduct();
createForm(model);
return "product";
}
}
and this is my JSP page
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>E-commerce</title>
</head>
<body>
<h1>Our Products</h1>
<form:form action="product.htm" method="post" commandName="product">
<form:label path="productname">Enter product name:</form:label></br>
<form:input id="pname" type="text" path="productname" placeholder="product name"></form:input><br>
<form:label path="productstock">Enter amount of items in stock:</form:label></br>
<form:input id="pstock" type="text" path="productstock" placeholder="product stock"></form:input><br>
<form:label path="productdescription">Enter product description:</form:label></br>
<form:input id="pdescription" type="text" path="productdescription" placeholder="product description"></form:input><br>
<input type="submit" value="Dodaj proizvod"/>
</form:form>
<label for="product_list" id="products_list_label">List of products: </label> </br>
<textarea id="products_list" rows="20" cols="100" readonly>${products}</textarea>
</body>
</html>
this is my SQL Query
`product_id` INT NOT NULL AUTO_INCREMENT,
`productname` VARCHAR(45) NOT NULL,
`productstock` INT NOT NULL,
`productdescription` VARCHAR(45) NOT NULL,
PRIMARY KEY (`product_id`));
Error occurred when i load page, i can see content (those labels and text area) but in text-area i can see this java lang class cast exception is there, so when i try to get products on list i can't. What could it be?
If I put the code from UsuarioDAO into UsuarioServlet, the JSP works well. But I'm trying to use MVC, OO, and I can't understand what's wrong with my code, since I call the created object from the UsuarioDAO in UsuarioServlet, in theory should works well to, but it doesn't. I appreciate if someone can show me what I did wrong.
Usuario.java
package modelo;
public class Usuario {
private String nome;
private String login;
private String senha;
private int tipo;
private String cpf;
public void setNome(String nome) {
this.nome = nome;
}
public void setLogin(String login) {
this.login = login;
}
public void setSenha(String senha) {
this.senha = senha;
}
public void setTipo(int tipo) {
this.tipo = tipo;
}
public void setCpf(String cpf) {
this.cpf = cpf;
}
public String getNome() {
return nome;
}
public String getLogin() {
return login;
}
public String getSenha() {
return senha;
}
public int getTipo() {
return tipo;
}
public String getCpf() {
return cpf;
}
}
UsuarioDAO.java
package controle;
import modelo.Usuario;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
public class UsuarioDAO {
private Connection con;
public void init(ServletConfig config) throws ServletException {
final String url = "jdbc:oracle:thin:#oracle.inf.poa.ifrs.edu.br:1521:XE";
final String us = "kar";
try {
Class.forName("oracle.jdbc.OracleDriver");
} catch (ClassNotFoundException ex) {
Logger.getLogger(ex1.class.getName()).log(Level.SEVERE, null, ex);
}
try {
con = DriverManager.getConnection(url, us, us);
} catch (SQLException ex) {
throw new ServletException(ex);
}
}
public List<Usuario> list() throws SQLException {
List<Usuario> lista = new ArrayList<>();
try (
Connection connection = con;
PreparedStatement statement = connection.prepareStatement("SELECT * FROM JDBC_USUARIO");
ResultSet rs = statement.executeQuery();) {
while (rs.next()) {
Usuario usuario = new Usuario();
usuario.setNome(rs.getString(1));
usuario.setLogin(rs.getString(2));
usuario.setSenha(rs.getString(3));
usuario.setTipo(rs.getInt(4));
usuario.setCpf(rs.getString(5));
lista.add(usuario);
}
}
return lista;
}
}
UsuarioServlet.java
package controle;
import modelo.Usuario;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet(name = "UsuarioServlet", urlPatterns = {"/UsuarioServlet"})
public class UsuarioServlet extends HttpServlet {
UsuarioDAO usrDAO = new UsuarioDAO();
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
List<Usuario> retorno = usrDAO.list();
request.setAttribute("listaJSP", retorno);
request.getRequestDispatcher("/WEB-INF/listarUsuarios.jsp").forward(request, response);
} catch (SQLException e) {
throw new ServletException("Erro ao obter os dados", e);
}
}
}
listarUsuarios.jsp
<%# taglib prefix="c" uri="http://java.sun.com/jstl/core_rt" %>
<%# taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Servlet Exibe Resultado</title>
</head>
<body>
<TABLE BORDER=“1”>
<th>ID</th>
<th>Nome</th>
<th>Login</th>
<th>Senha</th>
<th>Tipo</th>
<th>CPF</th>
<c:forEach items="${listaJSP}" var="show" >
<c:set var="i" value="${i+1}" />
<tr>
<td><c:out value="${i}" /></td>
<td><c:out value="${show.nome}" /></td>
<td><c:out value="${show.login}" /></td>
<td><c:out value="${show.senha}" /></td>
<td><c:out value="${show.tipo}" /></td>
<td><c:out value="${show.cpf}" /></td>
</tr>
</c:forEach>
</table>
</body>
</html>
You are getting this error because the init() method on your UsuarioDAO is never called and this line
List<Usuario> retorno = usrDAO.list();
returns null.
Try to usrDAO.init() before calling the list.
The reason probably because UsuarioDAO is not a httpServlet so the init() method is not running on creation
I'm a beginner and i'm trying to make a simple app to display a table from mysql using JavaScript and jquery, json object. This is not giving me any error and but i'm lost as to how to proceed. Please provide your feedback!
This is my books.java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
public class Books {
private int id;
private String title;
private String author;
private float price;
private int qty;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public int getQty() {
return qty;
}
public void setQty(int qty) {
this.qty = qty;
}
public Books(int id, String title, String author, float price, int qty) {
super();
this.id = id;
this.title = title;
this.author = author;
this.price = price;
this.qty = qty;
}
public Books() {
}
public ArrayList <Books> getBooks(ArrayList<Books> bookList){
Connection conn =null;
ResultSet rset = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/ebookshop", "root", "root");
PreparedStatement pst = (PreparedStatement) conn
.prepareStatement("SELECT * from books");
rset = pst.executeQuery();
while (rset.next()){
Books books = new Books();
books.setId(rset.getInt("id"));
books.setAuthor(rset.getString("author"));
books.setTitle(rset.getString("title"));
books.setPrice(rset.getFloat("price"));
books.setQty(rset.getInt("qty"));
bookList.add(books);
}
} catch (SQLException e) {
System.out.println("Could not connect to DB" + e);
} catch (ClassNotFoundException classexpt){
System.out.println("Couldn't find the class" + classexpt);
}
return bookList;
}
}
Servlet File:
import java.io.IOException;
import java.util.ArrayList;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class BooksServlet
*/
#WebServlet("/BooksServlet")
public class BooksServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public BooksServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("application/json");
Books books = new Books();
ArrayList <Books> bookList = new ArrayList <Books>();
bookList = books.getBooks(bookList);
request.setAttribute("bookList", bookList);
JSONObject obj=new JSONObject();
JSONArray arr = new JSONArray();
for(int i = 0 ; i< bookList.size() ; i++)
{
Books b = bookList.get(i);
obj.put("id", b.getId());
obj.put("title", b.getTitle());
obj.put("author", b.getAuthor());
obj.put("price", b.getPrice());
obj.put("qty", b.getQty());
arr.add(obj.toString());
obj = new JSONObject();
}
String address = "DisplayBook.jsp";
RequestDispatcher dispatcher =
request.getRequestDispatcher(address);
dispatcher.forward(request, response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
Jsp File:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<script type="text/javascript" src="js/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
function showBook(){
$.ajax({
type:"GET",
url:"BooksServlet.java",
dataType: "json",
data: JSON.stringify({ bookList: bookdata }),
success:function(data){
$("#content").html(data);
}
});
}
showBook();
});
</script>
<h3 align="center">Manage Book Details</h3>
<table border="1" align="center">
<tr>
<td> <input type="button" id="display" value="Display All Data" /> </td>
</tr>
</table>
<div id="content" align="center"></div>
<table>
<tr>
<td>id</td>
</tr>
</table>
</body>
</html>
JSp file is where i'm lost. I think i'm sending the data right with the list but not receiving it. Or am i sending the data wrong in the servlet?
Any help would be appreciated!
Try to access [server]/[context]/BooksServlet, example localhost:8080/myappp/BookServlet, since your /BookServlet is the mapping URL in your servlet.
See this #WebServlet annotation with Tomcat 7 and http://www.codejava.net/java-ee/servlet/webservlet-annotation-examples
By the way, I am still don't get, your Ajax URL go to /BookServlet and return json, but at that servlet does not return json data.
BooksServlet.java should not be in your jquery url but a servlet that returns a JSON. I don't get what you are trying to do with your jquery code. Now it seems to be ready to receive HTML, not a JSON.
I would recommend you to use a plug in like firebug or similar go to network and analize the request/response you are creating.
I would use DataTables to handle JSON in the front end side
I would use a JSON parser for the backend part example "Struts 2 result type JSON.
To be shortly: here is simple web app. On the main page there is a button, after clickig on it it has to be another page with table that contains data from database.
Im using servlets/jsp MySQL
Here is code
Main page
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<head>
<title>University</title>
</head>
<body>
<h2 style="text-align: center">Welcome to university!</h2>
<p style="text-align: center"><img src="Images/university.jpg"></p>
<form>
<p style="text-align: center">
<button formmethod="GET" formaction="SelectStudents.do">See all students</button>
</p>
</form>
</body>
</html>
Page with table
<%# page import="java.util.List" %>
<%# page import="model.StudentDAO" %>
<%# page import="model.Student" %>
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Students</title>
</head>
<body>
<table border="1" >
<caption>Students</caption>
<tr>
<th>ID</th>
<th>Name</th>
<th>Surname</th>
<th>Age</th>
<th>Country</th>
<th>City</th>
<th>Street</th>
<th>House</th>
<th>Flat</th>
<th>Group</th>
</tr>
<%
List<Student> students = new StudentDAO().selectAll();
for (Student s : students) {
%>
<tr>
<td><%=s.getId()%>></td>
<td><%=s.getName()%>></td>
<td><%=s.getSurname()%>></td>
<td><%=s.getAge()%>></td>
<td><%=s.getAddress().getCountry()%>></td>
<td><%=s.getAddress().getCity()%>></td>
<td><%=s.getAddress().getStreet()%>></td>
<td><%=s.getAddress().getHouseNumber()%>></td>
<td><%=s.getAddress().getFlatNumber()%>></td>
<td><%=s.getGroup().getName()%>></td>
</tr>
<%
}
%>
</table>
</body>
</html>
Class Student
public class Student {
private int id;
private String name;
private String surname;
private int age;
private Address address;
private Group group;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String name) {
this.surname = surname;
}
public void setAge(int age) {
this.age = age;
}
public int getAge() {
return age;
}
public void setAddress(Address address) {
this.address = address;
}
public Address getAddress() {
return address;
}
public void setGroup(Group group) {
this.group = group;
}
public Group getGroup() {
return group;
}
}
JDBCConnecto
package model;
import java.sql.*;
public class ConnectionManager {
private static final String JDBC_LOADER = "com.mysql.jdbc.Driver";
private static final String URL = "jdbc:mysql://localhost:3306/";
private static final String LOGIN = "root";
private static final String PASSWORD = "15021990";
private Connection connection;
public ConnectionManager() throws ClassNotFoundException, SQLException{
Class.forName(JDBC_LOADER);
connection = DriverManager.getConnection(URL, LOGIN, PASSWORD);
}
public Connection getConnection() throws SQLException{
return connection;
}
}
DAO
package model;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
public class StudentDAO {
private static final String SELECT_ALL =
"SELECT student.id, student.name, student.surname, student.age, \n" +
"\t address.country, address.city, address.street, address.house, address.flat, \n" +
"\t class.name\n" +
"\t FROM University.student join University.address \n" +
"\t on university.student.address = university.address.id join university.class\n" +
"\t on university.student.class = university.class.id";
public List<Student> selectAll() {
List<Student> result = new ArrayList<Student>();
Connection c = null;
try {
c = new ConnectionManager().getConnection();
Statement s = c.createStatement();
ResultSet students = s.executeQuery(SELECT_ALL);
while (students.next()) {
int id = students.getInt(1);
String name = students.getString(2);
String surname = students.getString(3);
int age = students.getInt(4);
String country = students.getString(5);
String city = students.getString(6);
String street = students.getString(7);
int house = students.getInt(8);
int flat = students.getInt(9);
String groupName = students.getString(10);
Address address = new Address();
address.setCountry(country);
address.setCity(city);
address.setStreet(street);
address.setHouseNumber(house);
address.setFlatNumber(flat);
Group group = new Group();
group.setName(groupName);
Student student = new Student();
student.setId(id);
student.setName(name);
student.setSurname(surname);
student.setAge(age);
student.setAddress(address);
student.setGroup(group);
result.add(student);
}
} catch (SQLException e) {
System.out.print(e.getErrorCode());
} catch (ClassNotFoundException e) {
} finally {
try {
if (c != null)
c.close();
} catch (SQLException e) {
System.out.print(e.getErrorCode());
}
}
return result;
}
}
Servlet
package controller;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class StudentsSelect extends HttpServlet {
#Override
public void doGet(HttpServletRequest request, HttpServletResponse response) {
RequestDispatcher view = request.getRequestDispatcher("table.jsp");
try {
view.forward(request, response);
} catch (ServletException e) {
} catch (IOException e) {
}
}
}
The problem is that after pressing the button there is no information about students in table in table.jsp.
You obviously forgot to add your MySQL connector (select platform independent and click download zip package, if your didn't download it). Add MySQL connector jar file to lib directory in your project. That should solve your problem.