Java Bean calling Java function and passing it to Jsp - java

hi all I have a LoginServlet that has the functionality to log in a user however I have a jsp page with the styling I'd to use. I am unsure how I can use the functionality from my LoginServlet in my login.jsp
here is the entirety of my code for the LoginServlet, I am aware I have coded to display a page but I need to use this jsp page to display. This is a uni assignment I have been given and it's part of the requirement that we use JSP for display.
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 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.RequestDispatcher;
/**
* Servlet implementation class LoginServlet
*/
#WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public LoginServlet() {
super();
// TODO Auto-generated constructor stub
}
private void sendLoginForm(HttpServletResponse response,
boolean withErrorMessage)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<HTML>");
out.println("<HEAD>");
out.println("<TITLE>Login</TITLE>");
out.println("</HEAD>");
out.println("<BODY>");
out.println("<CENTER>");
if (withErrorMessage)
out.println("Login failed. Please try again.<BR>");
out.println("<BR>");
out.println("<BR><H2>Login Page</H2>");
out.println("<BR>");
out.println("<BR>Please enter your user name and password.");
out.println("<BR>");
out.println("<BR><FORM METHOD=POST>");
out.println("<TABLE>");
out.println("<TR>");
out.println("<TD>User Name:</TD>");
out.println("<TD><INPUT TYPE=TEXT NAME=uniid></TD>");
out.println("</TR>");
out.println("<TR>");
out.println("<TD>Password:</TD>");
out.println("<TD><INPUT TYPE=PASSWORD NAME=password></TD>");
out.println("</TR>");
out.println("<TR>");
out.println("<TD ALIGN=RIGHT COLSPAN=2>");
out.println("<INPUT TYPE=SUBMIT VALUE=Login></TD>");
out.println("</TR>");
out.println("</TABLE>");
out.println("</FORM>");
out.println("</CENTER>");
out.println("</BODY>");
out.println("</HTML>");
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
sendLoginForm(response, false);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String uniid = request.getParameter("uniid");
String password = request.getParameter("password");
if (login(uniid, password)) {
/*RequestDispatcher rd =
request.getRequestDispatcher("AnotherServlet");
rd.forward(request, response); */
response.sendRedirect("home_student.jsp");
}
else {
sendLoginForm(response, true);
}
}
boolean login(String uniid, String password) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/wae","root","");
System.out.println("got connection");
Statement s = con.createStatement();
String sql = "SELECT uniid FROM user" +
" WHERE uniid='" + uniid + "'" +
" AND password='" + password + "'";
ResultSet rs = s.executeQuery(sql);
if (rs.next()) {
return true;
}
rs.close();
s.close();
con.close();
}
catch (ClassNotFoundException e) {
System.out.println(e.toString());
}
catch (SQLException e) {
System.out.println(e.toString());
}
catch (Exception e) {
System.out.println(e.toString());
}
return false;
}
}
here is my jsp page
<%# 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>Mars University Lab System</title>
<link rel="stylesheet" href="style.css" type="text/css" media="screen">
</head>
<body>
<jsp:include page="header.jsp"/>
<tr>
<td>
</td>
</tr>
<tr>
<td>
<div id = "centrecontent">
<table border="0" cellpadding="2">
<tr>
<td width="500px" align="center">
<br>
<font size="5">Welcome to <i>The Department of <br>Rocket Science</i> Lab System<br></font>
<br>
For <b>Students</b> you can enrol in labs<br> and manage the labs you're enrolled in.<br><br>
For <b>Tutors</b> you can view the labs<br> you're teaching and record attendence.<br><br>
For <b>Lecturers</b> you can create and<br> manage lab classes, register Tutors and<br> assign those Tutors to labs.<br><br>
</td>
<td width="500px">
<table border="0" align="center">
<tr>
<td align="center">
<table border="0" align="center">
<tr> <br><br><b>Existing Member? <br>Sign In Here!</b><br>
<td align="right">
<form name ="login" METHOD=POST ACTION="SaveSession.jsp">
Username: <input type="text" name="username"/><br />
Password: <input type="password" name="pword"/><br />
<input type=SUBMIT value="Login" name="Submit" />
</td>
</tr>
</table>
<br><br><br><br>
<form name="search_cat_bar" method="get" action="">
<input type="hidden" name="dff_view" value="grid">
Search:<input type="text" name="dff_keyword" size="30" maxlength="50"> <br>in
<select name="dff_cat1num" size="1">
<option value="-1">All Subjects
<option value="-2">--------------
<option value="101">CSE2ICE
<option value="193">CSE3PRA
<option value="193">CSE3PRB
<option value="193">CSE3WAE
</select>
<input type="submit" value="Find">
</form>
</td>
</tr>
</table>
</td>
</tr>
</table>
<table>
<tr>
</tr>
</table>
</div>
<jsp:include page="footer.jsp"/>
</body>
</html>
I'd like the login.jsp page to call my LoginServlet for the login functions.

You can call servlet by this way:
web.xml
<servlet>
<servlet-name>UserLogin</servlet-name>
<servlet-class>com.servlet.LoginServlet</servlet-class>//full class path
</servlet>
<servlet-mapping>
<servlet-name>UserLogin</servlet-name>
<url-pattern>/servlet/login</url-pattern>
</servlet-mapping>
login.jsp
<form name="login" action="<%=request.getContextPath()%>/servlet/login" method="post">
</form>
Servlet:
Login check and also you can send just error message to login page and display message like,
res.sendRedirect(req.getContextPath()+"/webpages/login.jsp?login=failed");
And in login.jsp you can retrieve parameter request.getParameter("login") and display proper message

add action in the html form tag.
action is LoginServlet URL.

It's easier to have the standard way of doing this:
Have jsp page with a form, to receive inputs from the user.
Have a servlet to process the data.
If there is a problem, set an error message and redirect the user to the login page. Otherwise redirect him to the destination.
Do not forget to set your form's action the address of your servlet.

Related

HTTP Status 405 - Method Not Allowed - while using servlet

My code is to use java servlets and JDBC to store and retrieve the information from a database. There is no error in the IDE the program is running but, the rows aren't inserted into the database and an error occurred in the firefox browser.
The following code is from the SERVLET file
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
public class ServletRegister extends HttpServlet{
public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException
{
res.setContentType("text/html");
PrintWriter out = res.getWriter("text/html");
String uname = req.getParameter("uname");
String passwd = req.getParameter("passwd");
String email = req.getParameter("email");
int phno = Integer.parseInt(req.getParameter("phno"));
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/hack","root","");
PreparedStatement ps = con.prepareStatement("insert into student values(?,?,?,?)");
ps.setString(1,uname);
ps.setString(2,passwd);
ps.setString(3, email);
ps.setInt(4, phno);
int i = ps.executeUpdate();
if(i>0)
out.print("Registerd Successfully");
out.close();
}catch(Exception e) {
System.out.println(e);
}
}
}
The following code is from HTML file
<!DOCTYPE html>
<html>
<head>
<title>Registration</title>
</head>
<body>
<form action="register">
<table>
<tr>
<td>Enter User Name: <input type="text" name="uname"> </td>
</tr>
<tr>
<td>Enter Password: <input type="password" name="passwd"> </td>
</tr>
<tr>
<td>Enter E-mail: <input type="email" name="email"> </td>
</tr>
<tr>
<td>Enter Phone.no: <input type="number" name="phno" min="6000000000" max="9999999999"></td>
</tr>
<tr>
<td><input type="submit"> <input type="reset"></td>
</tr>
</table>
</form>
</body>
</html>
The following code is from web.xml file
<servlet>
<servlet-name>RegisterServlet</servlet-name>
<servlet-class>com.hacker.ServletRegister</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>RegisterServlet</servlet-name>
<url-pattern>/register</url-pattern>
</servlet-mapping>
The Error is:
Error obtained in firefox browser
You can use Postman to send a POST request to your server, or change doPost to doGet
In HTML file tag you did not mention the method= "post" So its taking the value by default "get" request.

File does not upload properly

here I want to upload my file into my upload folder but in my scenario, it cannot store in that folder. The file name is printed in the console but the file does not store in the upload folder. In the Developer tool console, I get an error called Failed to load resource: the server responded with a status of 404 (Not Found).
DemoForm.java
package controller;
import java.io.*;
import java.util.* ;
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 DemoForm
*/
#WebServlet("/DemoForm")
#MultipartConfig(
fileSizeThreshold = 1024 * 1024 * 10, //10MB
maxFileSize = 1024 * 1024 * 50, //50MB
maxRequestSize = 1024 * 1024 * 100 //100MB
)
public class DemoForm extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final String UPLOAD_DIR = "upload";
/**
* #see HttpServlet#HttpServlet()
*/
public DemoForm() {
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 {
request.setAttribute("username", request.getParameter("username"));
request.setAttribute("password", request.getParameter("password"));
request.setAttribute("sex", request.getParameter("sex"));
request.setAttribute("favious", Arrays.toString(request.getParameterValues("favious")));
request.setAttribute("description", request.getParameter("description"));
request.setAttribute("experience", request.getParameter("experience"));
request.setAttribute("fileName", uploadFile(request));
request.getRequestDispatcher("form_result.jsp").forward(request, response);
}
private String uploadFile(HttpServletRequest request) {
String fileName = "";
try {
Part filePart = request.getPart("photo");
fileName = getfileName(filePart);
String applicationPath = request.getServletContext().getRealPath("");
String basePath = applicationPath + File.separator + UPLOAD_DIR
+ File.separator;
// creates the save directory if it does not exists
File fileSaveDir = new File(basePath);
if (!fileSaveDir.exists()) {
fileSaveDir.mkdir();
}
InputStream inputStream = null;
OutputStream outputStream = null;
try {
File outputFilePath = new File(basePath + fileName);
inputStream =filePart.getInputStream();
outputStream = new FileOutputStream(outputFilePath);
int read = 0;
final byte[] bytes = new byte[1024];
while((read = inputStream.read(bytes))!= -1) {
outputStream.write(bytes,0,read);
}
}catch(Exception ex) {
ex.printStackTrace();
fileName="";
}finally {
if(outputStream != null) {
outputStream.close();
}
if(inputStream != null) {
inputStream.close();
}
}
}catch(Exception ex){
fileName = "";
}
return fileName;
}
private String getfileName(Part part) {
final String partHeader = part.getHeader("content-disposition");
System.out.println("*****partHeader:" + partHeader);
for(String content : part.getHeader("content-disposition").split(";")) {
if(content.trim().startsWith("fileName")) {
return content.substring(content.indexOf('=')+ 1).trim()
.replace("\"", "");
}
}
return null;
}
}
Form.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Upload file</title>
</head>
<body>
<form method="post" action="DemoForm" enctype="multipart/form-data">
<table border="0" cellpadding="2" cellspacing="2" width="300">
<tr>
<td> username:</td>
<td><input type="text" name="username"/></td>
</tr>
<tr>
<td> Password:</td>
<td><input type="password" name="password"/></td>
</tr>
<tr>
<td valign="top"> Sex </td>
<td>
<input type="radio" name="sex" value="male" checked="checked"/>Male
<br>
<input type="radio" name="sex" value="female"/>Female
</td>
</tr>
<tr>
<td valign="top"> Favious </td>
<td>
<input type="checkbox" name="favious" value="fav1"/>Favios 1<br>
<input type="checkbox" name="favious" value="fav2"/>Favios 2<br>
<input type="checkbox" name="favious" value="fav1"/>Favios 3<br>
<input type="checkbox" name="favious" value="fav1"/>Favios 4<br>
<input type="checkbox" name="favious" value="fav1"/>Favios 5<br>
</td>
</tr>
<tr>
<td valign="top"> Description:</td>
<td><textarea rows="10" cols="20" name="description"></textarea></td>
</tr>
<tr>
<td>Experiences</td>
<td>
<select name="experience">
<option value="1"> 1 year </option>
<option value="2"> 2 year </option>
<option value="3"> 3 year </option>
<option value="4"> 4 year </option>
</select>
</td>
</tr>
<tr>
<td valign="top"> Photo</td>
<td><input type="file" name="photo "/></td>
</tr>
<tr>
<td>&nbsp</td>
<td><input type="submit" name="save"/></td>
</tr>
</table>
</form>
</body>
</html>
Form_result.jsp
[<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#page isELIgnored="false" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h3>Account Information</h3>
<table border="0" cellpadding="2" cellspacing="2" width="300">
<tr>
<td>Username</td>
<td> ${username}</td>
</tr>
<tr>
<td>Password</td>
<td> ${password}</td>
</tr>
<tr>
<td valign="top">Sex</td>
<td> ${sex}</td>
</tr>
<tr>
<td valign="top">Favious</td>
<td> ${favious}</td>
</tr>
<tr>
<td valign="top">Description</td>
<td> ${description}</td>
</tr>
<tr>
<td>Experience</td>
<td> ${experience}</td>
</tr>
<tr>
<td valign="top">Photo</td>
<td><img src="upload/${fileName}"></td>
</tr>
</table>
</body>
</html>][1]
I think the error is not in your file uploading. Your request has not been received by your servelet. Just comment out all the codes and check whether your doPost is working or not? Check the URL you are hitting.
The endpoint on which you are trying to upload the file is invalid.
Errorcode 404 means that the endpoint can not be found.

How to redirect jsp

I have LoginServlet like this:
package servlets;
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;
#WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public LoginServlet() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
if (username.equals("gogikole") && password.equals("1234")) {
response.sendRedirect("mainMenu.jsp");
return;
}
}
}
And login.jsp like this:
<%# 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>Login page</title>
</head>
<body>
<form method="post" action="LoginServlet"></form>
<table>
<tr>
<td>User name</td>
<td><input type="text" name="username"></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="password"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Login"></td>
</tr>
</table>
</body>
</html>
For some reason when I input correct username: (gogikole) and password: (1234) and click on submit button it won't to redirect me to mainMenu.jsp
When I click on button, nothing happen it just stay on login page like I didn't even click or type anything.
How to fix that problem and redirect when I click on submit button (Login)?
I created mainMenu.jsp and, for now that is one allmost blank page only with message "Welcome".
Your submit button is not submitting the form.
i.e., you have closed the form immediately:
<form method="post" action="LoginServlet"></form>
The problem is that your form inputs and submit button are outside the form You have to enclose as below.
<form method="post" action="LoginServlet">
<table>
<tr>
<td>User name</td>
<td><input type="text" name="username"></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="password"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Login"></td>
</tr>
</table>
</form>

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.

How to set values for hidden variable using javascript when processing using servlet? [duplicate]

This question already has an answer here:
HTTP request parameters are not available by request.getAttribute()
(1 answer)
Closed 6 years ago.
Hi all this is how i set value is hidden variable through java script,
function logintosystem(){
document.forms["frmLogon"].funtiontype.value="logon";
document.forms["frmLogon"].submit();
}
and this is what is my jsp page :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%
String path = "", userName = "", message = "", userType = "";
path = request.getContextPath();
if(request.getAttribute("message")!=null) message =(String)request.getAttribute("message");
%>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta name="description" content="ACCT"/>
<meta name="keywords" content="acct,accesscardcomparision" />
<meta name="author" content="slingmedia" />
<link rel="stylesheet" type="text/css" href="acct.css" title="andreas09" media="screen,projection" />
<title>ACCT</title>
<script>
function logintosystem(){
document.forms["frmLogon"].funtiontype.value="logon";
document.forms["frmLogon"].submit();
}
</script>
</head>
<body>
<div id="container">
<div id="sitename">
<h1>ACCT</h1>
<h2>Access Card data comparision with Leave portal</h2>
</div>
<div id="mainmenu">
<ul>
<%
if (userName.length() > 0 || !userName.equals(null) || !userName.equals("")) {
%>
<li><a href="#" class="current" >Welcome <%=userName%></a></li>
<%}%>
<%
if (userName.length() > 0 && userType.length() > 0) {
%>
<li>Tempcard</li>
<%}%>
<%
if (userType.equals("HR")) {
%>
<li>Report</li>
<%}%>
<%
if (userName.length() > 0 && userType.length() > 0) {
%>
<li>Logout</li>
<%}%>
</ul>
</div>
<div id="wrap">
<div id="content">
<h1>Please Enter your code</h1>
<form name="frmLogon" id="frmLogon" action="LogonServlet" method="post">
<table align="center" border="0" cellpadding="0" cellspacing="0" width="100%">
<tr align="center" valign="middle">
<td width="100%" align="center" valign="middle">
<table width="100%" align="left" border="0" cellspacing="0" cellpadding="2" >
<tr>
<td width="5%" align="left"> </td>
<td width="35%" align="right">ACCT Code</td>
<td width="20%"><input type="text" name="acctcode" id="acctcode" class="inputBoxes" /></td>
<td width="15%" align="left"><input type="button" class="submitButton" value="Logon" onclick="logintosystem();"/></td>
<td width="15%"> </td>
<td width="10%" align="center"> </td>
</tr>
<br></br>
</table>
</td>
</tr>
</table>
<input type="hidden" name="funtiontype" id="funtiontype" value=""/>
</form>
<table width="100%" border="0" cellspacing="0" cellpadding="0" bgcolor="#FFFFF0">
<tr>
<td id="message" align="center">
<b><font color="brown" size="3"><%=message%></font></b>
</td>
</tr>
</table>
</td>
</tr>
</table>
</div>
<div class="clearingdiv"> </div>
</div>
</div>
<div id="footer">
<p>© 2012 slingmedia | ACCT </p>
</div>
</body>
</html>
and my servlet is :
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.slingmeadia.notifier.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;
/**
*
* #author anthony.savarimut
*/
public class LogonServlet extends HttpServlet {
/**
* Processes requests for both HTTP
* <code>GET</code> and
* <code>POST</code> methods.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
/*
* TODO output your page here. You may use following sample code.
*/
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet LogonServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet LogonServlet at " + request.getContextPath() + "</h1>");
out.println("</body>");
out.println("</html>");
} finally {
out.close();
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP
* <code>GET</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// processRequest(request, response);
String funtiontype = "",acctcode="",pageRedirect="";
if(request.getAttribute("funtiontype")!=null) funtiontype =(String)request.getAttribute("funtiontype");
if(request.getAttribute("acctcode")!=null) acctcode =(String)request.getAttribute("acctcode");
if(funtiontype.equals("logon")){
request.setAttribute("message","Loggedon code is "+acctcode);
pageRedirect="notifier/notifier.jsp";
}else{
request.setAttribute("message","loggedout code is "+acctcode);
pageRedirect="index.jsp";
}
response.sendRedirect(pageRedirect);
}
/**
* Handles the HTTP
* <code>POST</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//processRequest(request, response);
System.out.println("Called logon");
doGet(request,response);
}
/**
* Returns a short description of the servlet.
*
* #return a String containing servlet description
*/
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
the page is getting submited but the values that i set for hidden variable is not coming in servlet also i have a text box that value also is not coming to servlet when submitting the page.
Kindly help me to find out this.
You should do this:
funtiontype =request.getParameter("funtiontype");
acctcode = request.getParameter("acctcode");
Try this..
function logintosystem(){
document.frmLogon.funtiontype.value="logon";
document.frmLogon.submit();
}
Update:
String funtionType = request.getAttribute("funtiontype") == null ? request.getParameter("funtiontype") : request.getAttribute("funtiontype");
String acctCode = request.getAttribute("acctcode") == null ? request.getParameter("acctcode") : request.getAttribute("acctcode");

Categories