Load Data into JSP Page from MySQL without Form - java

I am trying to load data into JSP page from MySQL database using Eclipse and Tomcat 8 server. My .jsp file looks as follows:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# page import="java.util.ArrayList"%>
<!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=UTF-8">
<title>Insert title here</title>
</head>
<body>
<jsp:forward page="/ProductDisplay" />
<table border="2">
<tr>
<td>Id</td>
<td>First Name</td>
<td>Last Name</td>
<td>Email</td>
<td>Phone Number</td>
</tr>
<c:forEach var="patients" items="${patients}">
<tr>
<td>${patients.getPatientId()}</td>
<td>${patients.getPatientfName()}</td>
<td>${patients.getPatientlName()}</td>
<td>${patients.getPatientEmail()}</td>
<td>${patients.getPatientPhone()}</td>
</tr>
</c:forEach>
</table>
</body>
</html>
The .java servlet file:
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
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 ProductDisplay
*/
#WebServlet("/ProductDisplay")
public class ProductDisplay extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public ProductDisplay() {
super();
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
PatientsDao p = new PatientsDao();
ArrayList<Patient> patients = p.getPatients();
request.setAttribute("patients", patients);
request.getRequestDispatcher("/Patient.jsp").forward(request, response);
}
}
And the database connector class looks as follows:
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 PatientsDao {
DBConnection mt = new DBConnection();
Connection myConn = mt.myConn;
private class DBConnection {
public Connection myConn;
public DBConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
myConn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/PatientsDB", "root", "");
} catch (Exception exc) {
exc.printStackTrace();
}
}
}
public ArrayList<Patient> getPatients() {
ArrayList<Patient> patients = new ArrayList<>();
try {
PreparedStatement pst =
myConn.prepareStatement("select * from Patients");
ResultSet r = pst.executeQuery();
while(r.next()) {
Patient p = new Patient();
p.setId(r.getInt("id"));
p.setfName(r.getString("fName"));
p.setlName(r.getString("lName"));
p.setEmail(r.getString("Email"));
p.setPhone(r.getString("Phone"));
patients.add(p);
}
}
catch (SQLException exc) {
System.out.println("An error occured. Error: " + exc.getMessage());
}
return patients;
}
}
Correct me if I'm wrong but I believe that upon running the Tomcat server the .java servlet class is invoked and information from the database is loaded into JSP page without any action needed. However, this does not happen in my case. Once I start Tomcat server and navigate to the Patient.jsp page the only thing that is displayed is the table header (which does not come from database). No data from MySQL database is displayed.
I know that this is not a MySQL problem as I can load all the data successfully if I add a form and use a button. Once the button is clicked and doGet method is invoked everything is loaded successfully.
My question is, how would I load the data automatically, without clicking a button or a link? I was doing research and apparently all info is supposed to load automatically. This, however, does not happen in my case. Am I missing something? Thank you in advance!

No, you mistake.
Servlet load first time when you call it(for examle go to Patient.jsp).
But when you go to Patient.jsp work only servlet Patient.jsp(jsp page convert to servlet class automatically), and you servlet /ProductDisplay dont work at all.
Your request attribute is empty when you call Patient.jsp beacause ProductDisplay don`t work.
You have three ways:
1) You should start with /ProductDisplay page
2) Or add index.jsp page and start with this page.
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<jsp:forward page="/ProductDisplay" />
</body>
</html>
3) And bad variant - add scriptlet to page Patient.jsp with code and start whith this page
PatientsDao p = new PatientsDao();
ArrayList<Patient> patients = p.getPatients();
request.setAttribute("patients", patients);
And remember never call servlets directly. Only through any servlet.
This is bad practice

Related

<c:out> tag is not showing up in JSP nor does it work

Somehow, the <c:out> tag is not working at all. It doesn't show any alerts and it's just blank. It's like I never added the tag into the file. Here's my code:
Connector.java:
package connect;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import javax.servlet.ServletContext;
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 javax.servlet.http.HttpSession;
import products.Product;
/**
* Servlet implementation class Connector
*/
#WebServlet("/Connector")
public class Connector extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public Connector() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
#SuppressWarnings({ "unchecked", "null", "unused" })
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String url = "jdbc:sqlserver://\\\\.\\pipe\\MSSQL$SQLEXPRESS\\sql\\query:8888;databaseName=ShoppingDB";
Connection con = DriverManager.getConnection(url,"sa","33887899");
Statement stmt = con.createStatement();
ArrayList<Product> pro=new ArrayList<Product>();
ResultSet rs=stmt.executeQuery("select * from Products");
Product p = new Product();
while(rs.next()) {
p.setId(rs.getInt("product_id"));
p.setName(rs.getString("product_name"));
p.setDes(rs.getString("product_des"));
p.setPrice(rs.getInt("product_price"));
p.setSrc(rs.getString("product_img_source"));
p.setType(rs.getString("product_type"));
p.setBrand(rs.getString("product_brand"));
p.setAmount(1000);
pro.add(p);
}
Product re;
String name=request.getParameter("search");
for(int i =0;i<pro.size();i++) {
if(pro.get(i).getName()==name) {
re=pro.get(i);
break;
}
}
p=pro.get(0);
ServletContext context=getServletContext();
context.setAttribute("p", p);
}catch(Exception e) {
out.println(e);
}
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
Home.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<link rel="stylesheet" href="Style.css">
</head>
<body style="background-color:#f5f5f5;">
<h1 style="text-align:center">PRJ321X_202x</h1>
<div id="nav">
<button class="navbtn">Home</button>
<button class="navbtn">Products</button>
<button class="navbtn">About Us</button>
<button class="navbtn" style="float:right;" onclick="location.href='Login.jsp'">Log in</button>
<form style="float:right;" method="Post" action="Connector">
<input name="search" id="search" type="text" placeholder="Search..">
<input type="submit" style="display:none">
</form>
</div>
<script src="Script.js"></script>
<div style="float:left;width:75%;margin-right:5px;" id="products">
<div>
<c:out value="${p.id}"/>
</div>
</div>
<div style="float:left;width:24%">
<div style="background-color:white;width:100%">
<h3>Shopping cart</h3>
<div style="height:2.5cm;background-color:#8f8d8d;width:100%">Your cart is currently empty</div>
</div>
<div style="background-color:white;width:100%">
<h4>Popular products or banner</h4>
<p>Iphone 11 Pro Max</p>
<img src="11PM.jpg" style="width:50%">
<p>Iphone 12 Pro Max</p>
<img src="12PM.jpg" style="width:50%">
<p>Samsung Galaxy S20</p>
<img src="S20.jpg" style="width:50%">
</div>
</div>
</body>
</html>
In your servlet you are doing
context.setAttribute("p", p);
But in your JSP you are doing:
<c:out value="${s.id}"/>
Obviously, your names must match and the tag should be:
<c:out value="${p.id}"/>
One other thing I notice is that you are not dispatching to the JSP. You need to do a requestDispatcher.forward() to your JSP
Here is the minimum example to make everything work:
Servlet:
package connect;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
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 products.Product;
#WebServlet("/Connector")
public class Connector extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Product p = new Product();
p.setId(1234);
ServletContext context = getServletContext();
context.setAttribute("p", p);
RequestDispatcher requestDispatcher = request.getRequestDispatcher("/Home.jsp"); // <--- your path here
requestDispatcher.forward(request, response);
}
}
If your Home.jsp file is on some other path, change above accordingly.
Home.jsp:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<c:out value="${p.id}" />
With that being said, a few comments on your controller code.
First of all, don't use #SuppressWarnings unless you know what you are doing. Based on your code, you are at a beginner level, so this annotation can hide a lot of issues that you should pay attention to.
You use an output stream PrintWriter out = response.getWriter(); in your code, but only to write a exception message into it when your code fails. If your code works, not only that you don't use your JSP, but you also don't use this out object to write a response to send to the client. So in regards with generating a response, your servlet did nothing, that's why nothing was displayed.
If you are doing a search for a product, you can write a WHERE clause and retrieve only what you are searching for instead of getting all the products in the database and then looping through them. Make sure you use prepared statement parameters when building your query. DO NOT CONCATENATE STRING TO BUILD YOUR SQL QUERY. That can cause SQL injection vulnerabilities.
You are looping through a list of product results but you are declaring your product object outside of the while loop. The result of this is that your array will only be filled with this reference object, that will point to objects that have the last retrieved value from the database. You need to move the product creation inside the while loop, like this:
while (rs.next()) {
Product p = new Product();
p.setId(rs.getInt("product_id"));
// all the other props
pro.add(p);
}
You are using the Product re; reference to search for your product, but then you never use it because you do a p=pro.get(0); to get the first product from your list and you use p to place in context for the JSP. I'me assuming you mean to use re instead.
Don't compare strings with ==. This code:
if (pro.get(i).getName() == name) {
should probably be something like:
if (pro.get(i).getName().equalsIgnoreCase(name)) {
Even more, you need to make sure you protect yourself from NullPointerExceptions in case getName() can also return null. If you used a WHERE SQL clause, you wouldn't need to loop again and search for products.
Finally, you should read some books or documentation on the concepts and code you are using. You might be able to put something together eventually, without fully understanding what's going on, but it might not necessarily be what you expect.

how i do when ihave this issue JSP Problem: HTTP 500 Internal Server Error Status when handling action?

I have searched the forums a lot for a solution to my problem but so far nothing. So I need your help!
Currently I am taking the Java EE course: "Develop websites with Java EE" on openclassrooms and arrived on JDBC I am blocked.
The principle consists of reading data in the database from the Java code and displaying them at the level of the JSP. But the display poses a problem at the JSP level. Thank you for your help! Here is my code for the JSP.
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>titre</title>
</head>
<body>
<h1>Bienvenue dans mon site</h1>
<ul>
<c:forEach var="utilisateur" items="${ utilisateurs }" >
<li><c:out value="${ utilisateurs.prenom }" /><c:out value="${ utilisateurs.nom }" /></li>
</c:forEach>
</ul>
</body>
</html>
import java.io.IOException;
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 sn.mballo.bdd.Personnes;
#WebServlet("/bonjour")
public class Test extends HttpServlet {
private static final long serialVersionUID = 1L;
public Test() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Personnes tablePersonnes = new Personnes();
request.setAttribute("utilisateurs", tablePersonnes.recupererUtilisateurs());
this.getServletContext().getRequestDispatcher("/WEB-INF/bonjour.jsp").forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}

Deleting table row using jsp and servlet [duplicate]

This question already has an answer here:
How do I pass current item to Java method by clicking a hyperlink or button in JSP page?
(1 answer)
Closed 7 years ago.
Hello everyone hope you having a good day,because i'm not xD , i'm new to the web programming and i've started with JSP and Servelts to do web operation my problem is when i click on "delete" it triggers the servlet but nothing happen the row doesn't get deleted and the value ( pw.print(name) ) doesn't show up. these are my codes.
DeleteServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class deleteuser extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter pw=response.getWriter();
try {
Connection con=Connecter.obtenirconnexion();
Statement st=con.createStatement();
String name=request.getParameter("id");
String Query="delete from users where name ='"+ name+"'";
st.executeUpdate(Query);
pw.print(name);
} catch (SQLException ex) {
Logger.getLogger(deleteuser.class.getName()).log(Level.SEVERE, null, ex);
}
request.getRequestDispatcher("users.jsp").forward(request, response);
}
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
Users.jsp
<%#page import="java.sql.ResultSet"%>
<%#page import="java.sql.PreparedStatement"%>
<%#page import="login.Connecter"%>
<%#page import="java.sql.Connection"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Users</title>
<style> table,td,th
{
border:1px black solid;
} </style>
</head>
<body>
<h1>Hello World</h1>
<%
Connection con = Connecter.obtenirconnexion();
String req = "select * from users";
PreparedStatement pst = con.prepareStatement(req);
ResultSet cur = pst.executeQuery();
out.println("<table ><tr><th>Name</th> <th>Password </th><th>Rank </th><th>Delete </th>");
while (cur.next()) {
out.println("<tr><td>" + cur.getString(1) + "</td><td>" + cur.getString(2) + "</td><td>" + cur.getString(3) + "</td><td> <a href=deleteuser id='"+cur.getString(1)+"'> delete </a></td></tr>");
}
out.println("</table>");
out.close();
%>
</body>
Well, the link to the DeleteServlet is broken. In order to pass a request parameter, it should be:
<a href=deleteuser?id='"+cur.getString(1)+"'> delete </a>
(note the ?)
But what you do is bad.
you have direct database accesses in a JSP. Best practices recommend to do data accesses in a servlet that would populate request attributes and forward to a JSP to display everything (or even to have layers that could be unit tested : Servlet <-> service <-> persistence)
you do a response.getWriter().print(...) inside the servlet before forwarding to the JSP. What you print will be outside of the body part (and even before the head!): here again you should put it in a request attribute and use it in JSP
you use a GET request to change database values. GET requests should only be used for read only operations. A delete should use a POST request - this last part is mainly for purists and if it has been the only problem I would not even have mentioned it...

Using JSP to store images in Mysql and upload the images online

I am still wondering what it is that i am doing wrong,my problem is i dont know if it is my entire sample code which has na error or my connection to the database which has an issues, as of where i stand i am not sure what is making me get this error. (displayed below).I have tried to look here at stack overflow but all i get is loading images using JSP but not adding them to the database. If we have one i couldnt trace please help me with the link. I have included all the libraries needed and my code has no error apart from this output. I came here because i am stranded and need a short review of what you proffesionals think is wrong with my code as done below. I will really appreciate anyhelp given as i am working on a deadline.
my Database name is
AppDB
I was wondering should i use the name of the table? to INSERT INTO? which is
'contacts'
Error Message
HTTP Status 404 - /UploadImageOnWeb/uploadServlet type Status report
message /UploadImageOnWeb/uploadServlet description The requested
resource is not available. Apache Tomcat/8.0.23
Thank you
Java Servlet Code
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
/**
* Servlet implementation class FileUploadDBServlet
*/
#MultipartConfig(maxFileSize = 16177215)
#WebServlet("/FileUploadDBServlet")
public class FileUploadDBServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
// database connection settings
/*private String dbURL = "jdbc:mysql://localhost/AppDB";
private String dbUser = "root";
private String dbPass = "mypassword";*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String firstName = request.getParameter("firstName");
String lastName = request.getParameter("lastName");
InputStream inputStream = null;
Part filePart = request.getPart("photo");
if (filePart != null) {
System.out.println(filePart.getName());
System.out.println(filePart.getSize());
System.out.println(filePart.getContentType());
inputStream = filePart.getInputStream();
}
Connection conn = null;
String message = null;
try {
// connects to the database
/*DriverManager.registerDriver("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(dbURL, dbUser, dbPass);*/
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost/AppDB","root","mypassword");
// constructs SQL statement
String sql = "INSERT INTO contacts (first_name, last_name, photo) values (?, ?, ?)";
PreparedStatement statement = conn.prepareStatement(sql);
statement.setString(1, firstName);
statement.setString(2, lastName);
if (inputStream != null) {
// fetches input stream of the upload file for the blob column
statement.setBlob(3, inputStream);
}
int row = statement.executeUpdate();
if (row > 0) {
message = "File uploaded and saved into database";
}
} catch (SQLException ex) {
message = "ERROR: " + ex.getMessage();
ex.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (conn != null) {
// closes the database connection
try {
conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
// sets the message in request scope
request.setAttribute("Message", message);
// forwards to the message page
getServletContext().getRequestDispatcher("/Message.jsp").forward(request, response);
}
}
}
My .Jsp class
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>File Upload to Database Demo</title>
</head>
<body>
<center>
<h1>File Upload to Database Demo</h1>
<form method="post" action="uploadServlet" enctype="multipart/form-data">
<table border="0">
<tr>
<td>Enter First Name: </td>
<td><input type="text" name="firstName" size="20"/></td>
</tr>
<tr>
<td>Enter Last Name: </td>
<td><input type="text" name="lastName" size="20"/></td>
</tr>
<tr>
<td>Portrait Photo: </td>
<td><input type="file" name="photo" size="20"/></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Save">
</td>
</tr>
</table>
</form>
</center>
</body>
</html>
Display Jsp
<%# 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>Message</title>
</head>
<body>
<center>
<h3><%=request.getAttribute("Message")%></h3>
</center>
</body>
</html>
The 404 error indicates that the form is not even getting to the servlet.
You defined the action attribute in the form as uploadServlet which doesn't seem to be a valid URL for your application.
The servlet's URL is defined in the #WebServlet annotation as FileUploadDBServlet.
So you can fix it by changing the action in the form or changing the URL for the servlet.

Can't call doPost() method of servlet in jsp page [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
At beggining. There is a application structure.
I have 3 MySQL tables ( Obiekt, Termin, Rezerwacja). In project i have jsp page (here is code) :
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# page import="java.sql.*"%>
<%# page import="java.io.*"%>
<%# page import="java.util.*"%>
<%# page import="test.Obiekt"%>
<%# page import="test.ListaObiektow"%>
<%# page import="test.Termin"%>
<%# page import="test.ListaTerminow"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>menu główne</title>
<meta name="viewport" content="initial-scale=1, maximum-scale=1">
<meta name="android-mobile-web-app-capable" content="yes">
<meta name="android-mobile-web-app-status-bar-style" content="black">
<link href="css/ratchet.css" rel="stylesheet">
<link href="css/ratchet-theme-android.css" rel="stylesheet">
<script src="js/ratchet.js"></script>
<script type="text/javascript">
function Refresh(idObiekt){
location.href="pilkaNozna.jsp?idObiekt=" + idObiekt;
}
</script>
</head>
<body>
</br>
</br>
</br>
<header class="bar bar-nav">
<a class="icon icon-left-nav pull-left" href="wyszukaj.jsp"></a>
<h1 class="title">Wybierz obiekt</h1>
</header>
<div id="content">
<div class="tabelawybor">
<b>Wybierz obiekt:</b>
<%
ArrayList<Obiekt> list = new ListaObiektow().getObiekty();
%>
<form>
<select name="obiekt" onChange="Refresh(this.value)">
<option value="0" selected>Wybierz Obiekt</option>
<%
String selectedObiekt = request.getParameter("idObiekt");
int counter=0;
for (Obiekt obiekt : list) {
if(selectedObiekt == null && counter==0)
{
selectedObiekt = Integer.toString(obiekt.idObiekt);
}
%>
<option value="<%=obiekt.idObiekt%>"
<%= ((Integer.toString(obiekt.idObiekt)).equals(selectedObiekt))?"selected":""%>><%=obiekt.nazwa%>
<%=obiekt.adres%></option>
<%
}
%>
</select>
</form>
</div>
<div class="tabelawybor">
<td><b>Wpisz liczbę uczestników:</b><input type="text"
name="uczest" /></td>
<% String liczbaUczestnikow = request.getParameter("liczbaUczestnikow"); %>
</div>
<div class="tabelawybor">
<form action="Rezerwacja?action=doPost" method="post">
<table class="center">
<tr>
<td>Nazwa obiektu:</td>
<td>Data:</td>
<td>Godzina</br> rozpoczęcia:
</td>
<td>Godzina</br> zakończenia:
</td>
<td></td>
</tr>
<%
ListaTerminow listaterminow = new ListaTerminow();
listaterminow.setId(selectedObiekt);
ArrayList<Termin> lista =listaterminow.getTerminy();
String idTermin = request.getParameter("idTermin");
for (Termin termin : lista) {
%>
<tr>
<td><%=termin.nazwaObiektu%> <%=termin.adresObiektu%></td>
<td><%=termin.dzien%></td>
<td><%=termin.odKtorej%></td>
<td><%=termin.doKtorej%></td>
<td>
<button class="btn btn-primary">Zarezerwuj</button>
</td>
</tr>
<%
}
%>
</table>
</form>
</div>
</div>
</body>
</html>
In this jsp page i have select form which have List of Obiekt (this list is created in ListaObiektow.java), but it works. I also have table form which contains List of Termin (created in ListaTerminow.java). It works too. But, in this table form there is button to make Rezerwacja.
I made Rezerwuj servlet. Here is code:
package test;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
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 test.ConnectionClass;
import test.Rezerwacja;
import test.Termin;/**
* Servlet implementation class Rezerwuj
*/
#WebServlet("/Rezerwacja")
public class Rezerwuj extends HttpServlet {
private static final long serialVersionUID = 1L;
Connection conn;
private int idTermin;
private int liczbaUczestnikow;
public Rezerwuj() {
super();
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
conn = ConnectionClass.Polacz();
ArrayList<Rezerwacja> rezerwacje = new ArrayList<Rezerwacja>();
PreparedStatement st = null;
ResultSet rs = null;
String sql = "INSERT INTO rezerwacje (liczbaUczestnikow,idTermin) values ('" + liczbaUczestnikow + "','" + idTermin + "')"
+ "UPDATE termin SET termin.czyZajety=true WHERE termin.idTermin = '"+ idTermin +"'";
try
{
st = conn.prepareStatement(sql);
if(liczbaUczestnikow > 0 && liczbaUczestnikow < 20)
{
rs = st.executeQuery();
}
while(rs.next())
{
Rezerwacja rezerwacja = new Rezerwacja();
rezerwacja.setLiczbaUczestnikow(rs.getInt(1));
rezerwacja.setIdTermin(rs.getInt(2));
rezerwacje.add(rezerwacja);
}
}
catch(SQLException e)
{
System.out.println(e);
}
}
public void setIdTermin(String id)
{
idTermin = Integer.parseInt(id);
}
public void setliczbaUczestnikow(String liczba)
{
liczbaUczestnikow = Integer.parseInt(liczba);
}
}
When i click on the button, it returns error like this:
type Exception report
message
description The server encountered an internal error that prevented it from fulfilling this request.
exception
java.lang.NullPointerException
test.Rezerwuj.doPost(Rezerwuj.java:63)
javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
What i want:
I select one of option in select form, then type value (0-20) into text input, then click on button and create a record in MySQL table Rezerwacja. Any suggestions ?
<form action="Rezerwacja?action=doPost" method="post">
In this line the action is where you are sending the request, so it should be action="Rezerwacja" and method should be method="POST"
I think you have problem with liczbaUczestnikow after initialization is always 0. As result rs always null, therefore exception thrown.

Categories