I am creating a project with JSP & Servlet (and entity beans) and I am trying to create a form where a user registers as a customer and is then redirected to a reservation page.
I want to keep the Id for the Customer that just registered and fill it into a disabled text field and then create a reservation on the next page. But whenever I try to load the customer class through jsp the whole application crashes with a NullPointerException.
It seems like the program crashes when it reaches the jsp-tags to fetch my customer, since it does print out the c.cPnr to the console as well as the test in the JSP-file.
<%# page import = "g24.isp.ejb.Customer" %>
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Welcome to Ski Village!</title>
<link rel="stylesheet" href="new/css/normalize.css">
<link rel="stylesheet" href="new/css/stylesheet.css">
<link href='https://fonts.googleapis.com/css?family=Fjalla+One|Poppins:400,500,600' rel='stylesheet' type='text/css'>
<script src="javascript/script.js" type="text/javascript"></script>
</head>
<body>
<% System.out.println("test"); %>
<% Customer c = (Customer) session.getAttribute("customer"); %>
<div id="container">
<!-- HEADER + MENU -->
<header>
<div class="logo"><!-- Ski Village Logo --></div>
<div class="menu">
<ul>
<li> Home </li>
<li class="left-menu"> About </li>
<li class="right-menu"> Book </li>
<li> <a href="index.html" > Test</a></li>
</ul>
</div>
</header>
<!-- PAGE CONTENT -->
<div id="wrapper">
<div class="center-form">
<form action="/HotelClient/HotelServlet" name="resForm" method="post">
<input type="text" name="cPnr" value="<%= c.getcPnr() %>" >
<input type="number" name="week" min="1" max="52" placeholder="Select week" >
<select name="cno">
<option value="1">Adventure Cabin
</option>
<option value="2">Cozy Cabin
</option>
<option value="3">Snowy Cabin
</option>
<option value="4">Hacker Cabin
</option>
</select>
<input type="submit" name="checkres" value="Check availability">
<input type="submit" name="submitresform" value="Create reservation" type="hidden">
<input name="operation" value="bajskorv" type="hidden">
</form>
</div>
<!-- FOOTER + SOCIAL ICONS -->
<footer>
<img src="img/facebook-logo.png" class="social-icon" alt="facebook logo">
<img src="img/instagram-logo.png" class="social-icon" alt="instagram logo">
<img src="img/twitter-logo.png" class="social-icon" alt="twitter logo">
<p>© 2016 | Ski Village</p>
</footer>
</div>
</div>
</body>
</html>
Servlet code:
package g24.isp.servlets;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.EJB;
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;
import javax.servlet.http.HttpSession;
import g24.isp.ejb.Cabin;
import g24.isp.ejb.Customer;
import g24.isp.ejb.Hotel;
import g24.isp.ejb.Reservation;
import g24.isp.facade.Facade;
import g24.isp.facade.FacadeLocal;
import g24.isp.ejb.MethodClass;
/**
* Servlet implementation class HotelServlet
*/
#WebServlet("/HotelServlet")
public class HotelServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
#EJB
private FacadeLocal facade;
/**
* #see HttpServlet#HttpServlet()
*/
public HotelServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
PrintWriter out = response.getWriter();
out.println("MainServlet-doGet");
out.close();
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
String url = "did not get an url";
// Get hidden field
String operation = request.getParameter("operation");
MethodClass mc = new MethodClass();
if (operation.equals("createcustomer")) {
String cPnr = request.getParameter("txtcPnr");
String cAddress = request.getParameter("txtcAddress");
String cPhone = request.getParameter("txtcPhone");
String cName = request.getParameter("txtcName");
if (facade.findByCpnr(cPnr) == null) {
Customer customer = new Customer();
customer.setcPnr(cPnr);
customer.setcAddress(cAddress);
customer.setcPhone(cPhone);
customer.setcName(cName);
facade.createCustomer(customer);
url = "/new/reservation.jsp";
} else {
url = "new/newcust.jsp";
}
}
else if (operation.equals("createreservation")) {
String cpnr = request.getParameter("txtcPnr");
int week = mc.ParseStringToInt(request.getParameter("week"));
int cno = mc.ParseStringToInt(request.getParameter("cno"));
Customer cs = facade.findByCpnr(cpnr);
Cabin cb = facade.findByCabinNo(cno);
if (cb != null && cs != null) {
Reservation res = new Reservation();
res.setCabin(cb);
res.setCustomer(cs);
res.setrDate(week);
facade.createReservation(res);
url = "/Index.jsp";
} else {
System.out.println("Did not enter if statement");
url = "/Index.jsp";
}
}
else if (operation.equals("newcustomer")) {
url = "/new/newcust.jsp";
}
else if (operation.equals("setcustomer")) {
System.out.println("Servlet - Create reservation");
String cpnr = request.getParameter("txtcPnr");
System.out.println(cpnr);
url = "/new/reservation.jsp";
Customer customer = facade.findByCpnr(cpnr);
if (customer != null) {
System.out.println(customer.getcName());
session.setAttribute("customer", customer);
url = "/reservation.jsp";
}
else {
System.out.println("Customer value is null");
}
}
System.out.println(url);
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
dispatcher.forward(request, response);
}
}
May be it's not setting the session attribute and when c.getcPnr() gets executed, it throws NullPointerException. Can you check whether the attribute is set in the session? You can try printing out 'c' in the jsp.
I solved the problem - i was trying to find the customer by accessing the facade.findBycPnr() method.
The solution was to session.setAttribute(customer, cust) when creating the customer.
Related
This question already has answers here:
Does form data still transfer if the input tag has no name?
(3 answers)
Closed 1 year ago.
request.getParameter("fname") and request.getParameter("lname") are returning a null value. I checked for typos but I can't find any. Help please.
This is the HTML code with posting to Java Servlet FirstServlet
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>One</title>
</head>
<body>
<form action="FirstServlet" method="post">
Enter FirstName: <input type="text" value="fname">
Enter LastName: <input type="text" value="lname">
<input type="submit" value="Next">
</form>
</body>
</html>
Java Servlet code here
package com;
import java.io.IOException;
import dto.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* Servlet implementation class FirstServlet
*/
public class FirstServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public FirstServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
*/
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
User user = new User();
HttpSession session= request.getSession();
user.setFname(request.getParameter("fname"));
user.setLname(request.getParameter("lname"));
session.setAttribute("user", user);
response.sendRedirect("two.html");
}
}
It should be name, not value.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>One</title>
</head>
<body>
<form action="FirstServlet" method="post">
Enter FirstName: <input type="text" name="fname">
Enter LastName: <input type="text" name="lname">
<input type="submit" value="Next">
</form>
</body>
</html>
I have created a login form in my index.jsp file:
<%# page contentType="text/html; ISO-8859-1" language="java" %>
<html>
<head>
<title>Material Master Data Manager</title>
<meta charset="ISO-8859-1">
<link rel="stylesheet" href="css/login_style.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<body>
<div id="basicData">
<div id="createMaterialHeader">
<h2><i><b>Material Master Data Manager</b></i></h2>
<div id="newPasswordBar">
<p>New Password</p>
</div>
</div>
<form class="tabcontent" action="MaterialCreator" method="post">
<label for="client">Client</label><br>
<select type="text" name="client" id="client">
<option>Commerzbank AG S.A. Branch in Lodz</option>
<option>Daikin Airconditioning Poland Sp. z o.o.</option>
<option>Infosys Consulting</option>
</select><br>
<label for="userID">User ID</label><br>
<input type="text" id="userID" name="userID"><br>
<label for="userPassword">Password</label><br>
<input type="password" id="userPassword" name="userPassword"><br>
<label for="isAdmin">Admin</label><br>
<input type="text" id="isAdmin" name="isAdmin"><br>
<input type="submit" class="fa fa-check">
</form>
</div>
</div>
<footer>
<p><a>© Created by Lorem Ipsum. 2017</a></p>
</footer>
</body>
<script src='javaScript/loginJs.js'></script>
</html>
That is MaterialCreator servlet:
package com.mmdmanager;
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 java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
#WebServlet("/MaterialCreator")
public class MaterialCreator extends HttpServlet {
Connection dbConnection;
PreparedStatement getCredentialsFromDb;
ResultSet userCredentialsReceived;
String userCredentials = "SELECT USER_ID, FIRST_NAME, LAST_NAME, SEX, COMPANY_NAME, IS_ADMIN, ACC_PASSWORD FROM USERS " +
"WHERE COMPANY_NAME =? AND USER_ID =? AND ACC_PASSWORD =? AND IS_ADMIN =?";
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//response.getWriter().append("Served at: ").append(request.getContextPath());
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter printWriter = response.getWriter();
doGet(request,response);
String company_name = request.getParameter("client");
String user_id = request.getParameter("userID");
String acc_password = request.getParameter("userPassword");
String is_admin = request.getParameter("isAdmin");
if (company_name.equals("Infosys Consulting") && user_id.equals("ADMIN1") && acc_password.equals("Q#3wertyuiop") && is_admin.equals("Y")) {
response.sendRedirect("MaterialCreator.jsp");
}
else {
response.sendRedirect("");
}
}
}
As You can see in the code above, the main idea is to redirect on condition that a user provides correct credentials (IF statement stores it). Unfortunately, no matter what credentials I provide, every time when I click the input button (class "fa fa-check") I am redirected to MaterialCreator servlet, not to MaterialCreator.jsp file, however the code contains method -> response.sendRedirect("MaterialCreator.jsp");, but it is invisible for the project.
MaterialCreator.jsp file has a very simple html code:
<%# page contentType="text/html; ISO-8859-1" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>Hello User!</h1>
</body>
</html>
I'm very new to FullCalendar and I seriously don't know how to adapt it according to my project requirements. Chose it because my Lecturer wants me to. I am aware that fullcalendar is drag and drop function. What i'm trying to do is have an add button for each cell in my fullcalendar page then when I click add it will go to another jsp page (Add Events). Then I have date inputs (java.sql.Date) so this dates must match to full calendar date.I'm So sure that it's some logic here in index.jsp that needs to be done like if and else statement. If mysql date match to fullcalendar date,you display in that cell. Now what it's doing is print out date in every cell from database.And I just need to display the Title. Refer to the pictures attached :)
RetrieveServlet: Retrieve from AddEventsServlet (for adding events)
ackage servlet;
import java.io.IOException;
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 javax.servlet.http.HttpSession;
import database.DBAO;
import model.AddEvents;
/**
* Servlet implementation class RetrieveServlet
*/
#WebServlet("/RetrieveServlet")
public class RetrieveServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public RetrieveServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//response.getWriter().append("Served at: ").append(request.getContextPath());
doPost(request,response); //dispatcher sents deget request, since ur code is in dopost, u will need to all it.
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try
{
DBAO myDatabase = new DBAO();
ArrayList <AddEvents> myEventList = myDatabase.getAddEvents();
System.out.println(myEventList.size());
request.setAttribute("EventList",myEventList);
request.getRequestDispatcher("index.jsp").forward(request, response);
}catch(Exception ex)
{
System.out.println("Error Accessing Database:" +ex.getMessage());
}
}
}
AddEventsServlet:
package servlet;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.ListIterator;
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;
import javax.servlet.http.HttpSession;
import database.DBAO;
import model.AddEvents;
/**
* Servlet implementation class AddEventsServlet
*/
#WebServlet("/AddEventsServlet")
public class AddEventsServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public AddEventsServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* #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);
AddEvents myEvent = new AddEvents();
//create an object based on the Java class customers
//DateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
//Assignment of data
myEvent.setTitle(request.getParameter("Title"));
myEvent.setEventDesc(request.getParameter("EventDesc"));
myEvent.setStartTime(request.getParameter("StartTime"));
myEvent.setEndTime(request.getParameter("EndTime"));
myEvent.setBudget(Double.valueOf(request.getParameter("Budget")));
myEvent.setStartDate(java.sql.Date.valueOf(request.getParameter("StartDate")));
myEvent.setEndDate(java.sql.Date.valueOf(request.getParameter("EndDate")));
myEvent.setEnvironment(request.getParameter("Environment"));
System.out.println(request.getParameter("Title"));
System.out.println(request.getParameter("EventDesc"));
System.out.println(request.getParameter("StartTime"));
System.out.println(request.getParameter("EndTime"));
System.out.println(request.getParameter("Budget"));
System.out.println(request.getParameter("StartDate"));
System.out.println(request.getParameter("EndDate"));
System.out.println(request.getParameter("Environment"));
System.out.println("Title="+myEvent.getTitle());
System.out.println("EventDesc="+myEvent.getEventDesc());
System.out.println("StartTime="+myEvent.getStartTime());
System.out.println("EndTime="+myEvent.getEndTime());
System.out.println("Budget="+myEvent.getBudget());
System.out.println("StartDate="+myEvent.getStartDate());
System.out.println("EndDate="+myEvent.getEndDate());
System.out.println("Environment="+myEvent.getEnvironment());
try
{
DBAO myDatabase = new DBAO();
ArrayList <AddEvents> myEventList = myDatabase.getAddEvents(); //not needed
//AddEvents myEventDetails =myDatabase.isEvent(myEvent,title, eventDesc, StartTime, EndTime, Budget); //not needed
HttpSession myRequest = request.getSession(true); //not needed
request.setAttribute("EventList",myEventList); //not needed
System.out.println(myEventList.size()); //not needed
// you comment out the method that insert data to database
myDatabase.AddEvents(myEvent);
// the dispatcher can go to RetrieveServlet and let it handle the retrieve
//myDatabase.delete(myEvent,title,eventDesc,StartTime,EndTime,Budget,StartDate,EndDate);
//name of delete database
request.getRequestDispatcher("index.jsp").forward(request, response);
}catch(Exception ex)
{
System.out.println("Error Accessing Database:" +ex);
}
}
}
index.jsp: Displaying the full calendar
<%# 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>
<%#page import="model.AddEvents,java.util.ArrayList,java.util.ListIterator" %>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script type="text/javascript" src= "https://code.jquery.com/jquery-3.2.1.min.js">
$(document).ready(function() {
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
var events_array = [
{
title: 'Test1',
start: new Date(2012, 8, 20),
tip: 'Personal tip 1'},
{
title: 'Test2',
start: new Date(2012, 8, 21),
tip: 'Personal tip 2'}
];
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
dayClick: function(date, jsEvent, view) {
alert('Clicked on: ' + date.format());
alert('Coordinates: ' + jsEvent.pageX + ',' + jsEvent.pageY);
alert('Current view: ' + view.name);
// change the day's background color just for fun
$(this).css('background-color', 'red');
},
selectable: true,
events: events_array,
eventRender: function(event, element) {
element.attr('title', event.tip);
}},
$('#datepicker').datepicker({
inline: true,
onSelect: function(dateText, inst) {
var d = new Date(dateText);
$('#fullcalendar').fullCalendar('gotoDate', d);
}
}));
function changeDate() {
var StartDate = $('#datepicker').val();
$('#calendar').fullCalendar('gotoDate', startDate);
}
});
</script>
<title>Calendar</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" type="text/css" rel="stylesheet" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/2.6.1/fullcalendar.min.css" type="text/css" rel="stylesheet" />
</head>
<body>
<a class= "add_event_label" href="https://www.w3schools.com/tags/tryit.asp?filename=tryhtml_textarea"></a>
<div class="container">
<div class="row">
<div class="col-xs-12">
<h1>Calendar</h1>
<div id="bootstrapModalFullCalendar"></div>
</div>
</div>
</div>
<!-- this is the pop up window when you press the button -->
<div id="fullCalModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span> <span class="sr-only">close</span></button>
<h4 id="modalTitle" class="modal-title"></h4>
</div>
<div id="modalBody" class="modal-body">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<a class="btn btn-primary" id="eventUrl" target="_blank">Event Page</a>
</div>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.8.2/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/2.6.1/fullcalendar.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script>
$(document).ready(function() {
$('#bootstrapModalFullCalendar').fullCalendar({
header: {
left: '',
center: 'prev title next',
right: ''
},
//action after calendar loaded
eventAfterAllRender: function(view){
if(view.name == 'month')
{
//loop all .fc-day elements
$('.fc-day').each(function(){
//jQuery styling
$(this).css({ 'font-weight': 'bold', 'font-size': '100%'});
$(this).css('position','relative');
//add elements to each .fc-day, you can modify the content in append() with your own html button code
$(this).append('<a class="add_event_label" onclick="changeDate()" href ="AddEvent.jsp" style="position:absolute;bottom:0;left:0;right:0;display:block;font-size:12px;color:blue;cursor:pointer;">(+)</a>' );
<%!ArrayList<AddEvents> myEventList; //have to declear in a declaration tag for access in the page %>
<% myEventList = (ArrayList<AddEvents>) request.getAttribute("EventList");
if(myEventList.size() == 0)
{
%>
<h2>No events</h2>
<%
}
else
{
%>
<%
ListIterator<AddEvents> li = myEventList.listIterator();
while(li.hasNext())
{
AddEvents myEvent = new AddEvents();
myEvent= (AddEvents)li.next();
%>
//This part it should add data according to date, now it's just adding all the data of title.
$(this).append('<p><font size="1">Title:</font></p><p><font size="1"><%= myEvent.getTitle() %></font></p></p>');
<%}
%>
<%
}
%>
});
}
},
eventClick: function(event, jsEvent, view) {
//$(".fc-day-number").prepend("(+) ");
$('#modalTitle').html(event.title);
$('#modalBody').html(event.description);
$('#eventUrl').attr('href',event.url);
$('#fullCalModal').modal();
return false;
}
})
})
</script>
</body>
</html>
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.
I have problem with get a value from combobox in my .jsp file to servlet.
I use method request.getParameter i other servlets and it works. In this class it don't.
I was also trying to get value from text field to this servlet but also don't work. I don't have any idea how to solve this problem.
I have combobox like that:
<form action="upload" method="POST" enctype="multipart/form-data">
<p class="folders_save">Folder:
<select name="folders1" id="user">
<%
user = (User)session.getAttribute("user");
listOfFolders = user.listOfFolders();
if(listOfFolders != null){
for(File file : listOfFolders){
out.print("<option value="+file.getName()+">"+file.getName()+"</option>");
}
}
%>
</select>
</p>
<input class="pole" type="file" name="file" />
<input class="wrzuc" type="submit" value="Wrzuc!">
</form>
I'm tring to get value:
String folder = request.getParameter("folders1");
My jsp file
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org /TR/html4/loose.dtd">
<html>
<head>
<%# page import="tools.User" %>
<%# page import="java.io.File" %>
<%# page import="java.text.DecimalFormat" %>
<%#page language="Java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="style.css" />
<title>Serwer dysku sieciowego </title>
</head>
<body>
<div class="container">
<div class="ramka_zaproszenie">
<%
File[] listOfFolders;
User user;
String username;
String status = null;
if(session.getAttribute("user")!=null){
user = (User)session.getAttribute("user");
username = user.getLogin();
status = user.getType().toString();
} else {
username = "unknown";
}
%>
<p class="loguj">Witaj, <%= username %>!</p><br>
<% if(session.getAttribute("user")!=null){ %>
<p class="tekst">Wrzuc plik na serwer:</p>
<form action="upload" method="POST" enctype="multipart/form-data">
<p class="folders_save">Folder:
<select name="folders1" id="user">
<%
user = (User)session.getAttribute("user");
listOfFolders = user.listOfFolders();
if(listOfFolders != null){
for(File file : listOfFolders){
out.print("<option value="+file.getName()+">"+file.getName()+"</option>");
}
}
%>
</select>
</p>
<input class="pole" type="file" name="file" />
<input class="wrzuc" type="submit" value="Wrzuc!">
</form>
<form action="folder" method="get">
<p class="tekst"> Folder: <br><input class="pole" id="Folder" type="text" name="folderName" />
<br /></p>
<input class="zatwierdz" type="submit" id="submit" value="Utwórz" /><br>
</form>
<br />
<% if(status.equalsIgnoreCase("ADMIN")){ %>
<a class="wroc" href="zmiana_rozmiaru.jsp">Zmiana Pojemnosci</a>
<%}%>
<br />
<br />
<p class="tekst">Posiadane pliki na serwerze:</p>
<form method="post">
Folder:
<select name="folders">
<option value=0 selected="selected" >Wybierz folder</option>
<%
user = (User)session.getAttribute("user");
listOfFolders = user.listOfFolders();
if(listOfFolders != null){
for(File file : listOfFolders){
out.print("<option value="+file.getName()+">"+file.getName()+"</option>");
}
}
%>
</select>
<input type="submit" value="Wybierz"><br>
</form>
<br />
Pliki z folderu: <%=request.getParameter("folders")%>
<center><table id="tabela">
<tr class="alt">
<th>Nazwa</th>
<th>Rozmiar</th>
<th>Pobierz</th>
<th>Usun</th>
</tr>
<%
System.out.println(request.getParameter("folders"));
user = (User)session.getAttribute("user");
File[] listOfFiles = user.listOfFiles(request.getParameter("folders"));
if(listOfFiles != null){
for(File file : listOfFiles){
DecimalFormat twoDForm = new DecimalFormat("#.##");
out.print("<tr class=\"alt\"><td>" + file.getName()+"</td><td>" +twoDForm.format((double)file.length()/1024.0)+" KB</td><td align=center> <img border=\"0\" src=\"downloadsmall.png\"></td><td align=center><a src=\"deletesmall.png\" href=\"delete?filePath="+file.getAbsolutePath()+"\" ><img border=\"0\" src=\"deletesmall.png\"></a></td></tr>");
}
}
%>
</table>
</center><br>
<form action="logout" method="post">
<input type="image" src="wylacznik.png" id="submit">
</form>
<br><br>
<%
if (session.getAttribute("warning") != null) {
%>
<span><%= session.getAttribute("warning") %></span>
<%
session.removeAttribute("warning");
}
%>
<% } %>
<div class="footer">Copyright 2013 by JavaProjectTeam.</div>
</div>
</div>
</body>
</html>
And my servlet file
<pre>package servlets;
import java.io.*;
import java.sql.SQLException;
import java.util.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.annotation.WebServlet;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import java.sql.Connection;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import tools.Connector;
import tools.User;
#WebServlet("/upload")
public class UploadServlet extends HttpServlet {
private boolean isMultipart;
private String filePath;
private File file ;
public void init(){
// Get the file location where it would be stored.
filePath = getServletContext().getInitParameter("file-upload");
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, java.io.IOException {
// Check that we have a file upload request
request.setCharacterEncoding("UTF-8");
String folder = request.getParameter("folders1");
HttpSession session = request.getSession(true);
User user = (User)session.getAttribute("user");
isMultipart = ServletFileUpload.isMultipartContent(request);
response.setContentType("text/html");
java.io.PrintWriter out = response.getWriter( );
if( !isMultipart ){
session.setAttribute("warning", "Nie masz zadnych plikow");
response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
response.setHeader("Location", "hello.jsp");
return;
}
DiskFileItemFactory factory = new DiskFileItemFactory();
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// maximum file size to be uploaded.
upload.setSizeMax(user.getSpace() * 1024);
try{
// Parse the request to get file items.
List fileItems = upload.parseRequest(request);
// Process the uploaded file items
Iterator i = fileItems.iterator();
while ( i.hasNext () )
{
FileItem fi = (FileItem)i.next();
if ( !fi.isFormField () )
{
// Get the uploaded file parameters
String fileName = fi.getName();
// Write the file
if( fileName.lastIndexOf("\\") >= 0 ){
file = new File( filePath+"\\"+user.getId()+"\\"+folder+"\\"+
fileName.substring( fileName.lastIndexOf("\\"))) ;
}else{
file = new File( filePath+"\\"+user.getId()+"\\"+folder+"\\"+
fileName.substring(fileName.lastIndexOf("\\")+1)) ;
}
fi.write(file);
System.out.println(file.getName());
try{
Connection connection = new Connector().getConnection();
DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols(Locale.GERMAN);
otherSymbols.setDecimalSeparator('.');
otherSymbols.setGroupingSeparator('.');
DecimalFormat twoDForm = new DecimalFormat("#.##", otherSymbols);
System.out.println(twoDForm.format((double)file.length()/1024.0));
connection.createStatement().executeUpdate("UPDATE `users` SET `space` = `space`-"+twoDForm.format((double)file.length()/1024.0)+" where id="+user.getId());
} catch(SQLException e){
e.printStackTrace();
}
session.setAttribute("warning", "Plik został dodany do wirtualnego dysku.");
response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
response.setHeader("Location", "hello.jsp");
}
}
out.println("</body>");
out.println("</html>");
}catch(Exception ex) {
System.out.println(ex);
session.setAttribute("warning", "File is too big! Only "+user.getSpace()+"KB left.");
response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
response.setHeader("Location", "hello.jsp");
}
}
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, java.io.IOException {
throw new ServletException("GET method used with " +
getClass( ).getName( )+": POST method required.");
}
}<code>
It's because you're sending a multipart/form-data request while that's by default not supported by servlets. I however notice that you're still using the "legacy" Apache Commons FileUpload to obtain the uploaded file instead of new Servlet 3.0 provided HttpServletRequest#getPart(). In that case, you've basically 2 options:
Stick to Commons FileUpload. You should be collecting regular form fields in the else block of your if (!fi.isFormField()) which you're currently completely ignoring.
if (!fi.isFormField()) {
// Collect uploaded file from fi.
} else {
// Collect normal form field from fi.
}
Get rid of Commons FileUpload and use #MultipartConfig annotation.
#WebServlet("/upload")
#MultipartConfig
public class UploadServlet extends HttpServlet {
This way you can get files by request.getPart() and keep using request.getParameter() the usual way for regular form fields.
See also:
How to upload files to server using JSP/Servlet?
Unrelared to the concrete problem, that's not a combobox, but that's a dropdown. A combobox is an editable dropdown. Further, writing Java code in JSP is a bad practice. Java code belongs in Java classes like a servlet. To loop over options, use JSTL <c:forEach>. And, writing HTML code in a Java class like a servlet is a bad practice. HTML code belongs in a JSP file. Use RequestDispatcher#forward() to present results in a JSP. See further also our servlets wiki page.
Oh, you've a major threadsafety problem in your servlet. There's only one instance of a servlet during applications lifetime which is shared across all HTTP requests. Those fields
private boolean isMultipart;
private String filePath;
private File file ;
would be shared across all HTTP requests resulting in potential major problems when multiple users concurrently use the same servlet at the same moment. Get rid of them and move them to inside the doXxx() method block.