I have problem accessing database with servlet java. I want to add users with an html registration form.
this is the html:
<form name="registration-form" action="RegisterUser" method="post">
<div class="form-group has-feedback">
<label class="control-label">Inserisci nome*</label>
<input type="text" class="form-control" name="name" id="inputName" placeholder="Nome">
<span class="glyphicon form-control-feedback"></span>
</div>
<div class="form-group has-feedback">
<label class="control-label">Inserisci cognome*</label>
<input type="text" class="form-control" name="surname" id="inputLastname" placeholder="Cognome">
<span class="glyphicon form-control-feedback"></span>
</div>
<div class="form-group has-feedback">
<label class="control-label">Inserisci email*</label>
<input type="email" class="form-control" name="email" id="inputEmail" placeholder="Email">
<span class="glyphicon form-control-feedback"></span>
</div>
<div class="form-group has-feedback">
<label class="control-label">Inserisci password (compresa tra 6 e 30 caratteri)*</label>
<input type="password" class="form-control" name="password" id="inputFirstPassword" placeholder="Password">
<span class="glyphicon form-control-feedback"></span>
</div>
<div class="form-group has-feedback">
<label class="control-label">Reinserisci password*</label>
<input type="password" class="form-control" id="inputSecondPassword" placeholder="Password">
<span class="glyphicon form-control-feedback"></span>
</div>
<button id="submitBtn" class="btn btn-lg btn-primary btn-block" >Registrati!</button>
</form>
This is the java class (InsertUser.java):
import java.sql.*;
public class InsertUser {
public static void main(String name, String surname, String email, String password) {
PreparedStatement insert = null;
String queryString = "INSERT INTO Utente(Nome, "
+ "Cognome, Email, Password) VALUES (?, ?, ?, ?)";
Connection conn = null;
try {
new com.mysql.jdbc.Driver();
Class.forName("com.mysql.jdbc.Driver").newInstance();
//Class.forName("org.gjt.mm.mysql.Driver").newInstance();
String connectionUrl = "jdbc:mysql://localhost:3306/NoteDB";
String connectionUser = "root";
// String connectionPassword = "root";
conn = DriverManager.getConnection(connectionUrl, connectionUser, "");
conn.setAutoCommit(false);
insert = conn.prepareStatement(queryString);
insert.setString(1, name);
insert.setString(2, surname);
insert.setString(3, email);
insert.setString(4, password);
insert.executeUpdate();
conn.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
try { if (conn != null) conn.close(); } catch (SQLException e) { e.printStackTrace(); }
}
}
This is the servlet (RegisterUser.java)
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;
/**
* Servlet implementation class RegisterUser
*/
#WebServlet("/RegisterUser")
public class RegisterUser extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public RegisterUser() {
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
String name = request.getParameter("name");
String surname = request.getParameter("surname");
String email = request.getParameter("email");
String password = request.getParameter("password");
//InsertUser myUser = new InsertUser();
InsertUser.main(name, surname, email, password);
}
/**
* #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);
}
}
This is the error I get:
error page
I'm sorry that is a long question, but I am in despair :( Thanks everyone!
EDIT: in this picture you can see the mysql-connector.jar: mysqlconnector
Remove this line conn.setAutoCommit(false);
As Ramanlfc mentioned, you have to add mysql driver to your classpath.
You can do it natively via your ide, or use build managers, like maven, gradle or ant.
In maven, your pom.xml would look like:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>your.app</groupId>
<artifactId>mysql-test</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
</dependencies>
Related
This question already has answers here:
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
(19 answers)
Closed 2 years ago.
im currently doing my final year project about lost and found system using java and oracle database (MVC).
my problem is after I submit the form the page will show this the message says it redirect to the FoundRegisterController
it supposedly register the found item. but it did not. how can I solve this problem? Below are the codes for the jsp, controller and DAO
this is registerFoundItem.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!doctype html>
<html class="no-js" lang="en">
<head>
<jsp:include page="css.jsp"></jsp:include>
</head>
<body>
<jsp:include page="header.jsp" />
<!-- tabs & register form Start -->
<div class="basic-form-area mg-b-15">
<div class="container-fluid">
<div class="row">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div class="sparkline8-list mt-b-30">
<div class="sparkline8-graph">
<div class="basic-login-form-ad">
<div class="row">
<div class="col-lg12 col-md-12 col-sm-12 col-xs-12">
<h2>
<center>Register New Found Item</center>
</h2>
<br> <br>
</div>
</div>
<%
String userEmail = (String) session.getAttribute("currentSessionUser");
%>
<%
String userNoPhone = (String) session.getAttribute("currentSessionUserNoPhone");
%>
<%
String userName = (String) session.getAttribute("currentSessionUserName");
%>
<div class="row">
<form action="FoundRegisterController" method="post">
<div class="col-lg-4 col-md-4 col-sm-4 col-xs-12">
<div class="basic-login-inner">
<h4>Reporter Details:</h4>
<div class="form-group-inner">
<label>Post by:</label> <input type="text"
class="form-control" name="UserName"
value="<c:out value="<%=userName%>" />" disabled />
</div>
<div class="form-group-inner">
<label>Contact Number: </label><input type="text"
class="form-control" name="UserNoPhone"
value="<c:out value="<%=userNoPhone%>" />" disabled />
</div>
<div class="form-group-inner">
<label>Email: </label><input type="text"
class="form-control" name="UserNoPhone"
value="<c:out value="<%=userEmail%>" />" disabled />
</div>
<br>
</div>
</div>
<div class="col-lg-8 col-md-8 col-sm-8 col-xs-12">
<h4>Found Item Details :</h4></div>
<div class="col-lg-4 col-md-4 col-sm-4 col-xs-12">
<label>Date:</label> <input class="form-control"
name="FItemDate" type="date" required />
</div>
<div class="col-lg-4 col-md-4 col-sm-4 col-xs-12">
<label>Time:</label> <input class="form-control"
name="FItemTime" type="time"
required />
</div>
<div class="col-lg-8 col-md-8 col-sm-8 col-xs-12">
<div class="form-group-inner">
<label><br>Found Item Name:</label> <input type="text"
class="form-control" name="FItemName"
placeholder="eg: iPhone 8 Plus | ASUS | GoPro 5 Black"
title="Please enter the valid name. Do not use shortform"
required />
</div>
<div class="form-group-inner">
<label>Found Item Category:</label>
<div class="form-select-list">
<select class="form-control custom-select-value"
name="account" name="FItemCategory">
<option disabled selected value>-- Select
Category --</option>
<option value="FoundItem">Mobile Phone</option>
<option value="FoundItem">Laptop/Notebook</option>
<option value="FoundItem">Keys</option>
<option value="FoundItem">Cards</option>
<option value="FoundItem">UiTM Matrics Card</option>
<option value="FoundItem">Other..</option>
</select>
</div>
</div>
<div class="form-group-inner">
<label>Location:</label> <input class="form-control"
name="FItemLocation"
placeholder="eg: Blok Kuliah 17 | JMK 8 | Cafe Kuliah"
title="Please enter the valid name. Do not use shortform"
required />
</div>
<div class="form-group-inner">
<label>Description: </label>
<div class="form-group edit-ta-resize res-mg-t-15">
<textarea name="description" name="FItemDescription" placeholder="eg: Barang dijumpai di bawah meja/atas lantai/depan pintu/atas meja pensyarah/etc.. anggaran waktu dijumpai 2ptg-6ptg"></textarea>
</div>
</div>
<div class="login-btn-inner">
<div class="inline-remember-me">
<button
class="btn btn-sm btn-primary pull-right login-submit-cs"
type="submit" name="action">
<b>Register</b>
</button>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<br>
</div>
<!-- tabs & Register form End-->
<!-- JS -->
<jsp:include page="js.jsp"></jsp:include>
</body>
</html>
this is my FoundRegisterController.java
package lofo.controller;
import java.io.IOException;
import java.io.PrintWriter;
import java.security.NoSuchAlgorithmException;
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 lofo.dao.foundDAO;
import lofo.model.FoundItemBean;
/**
* Servlet implementation class RegisterController
*/
#WebServlet("/FoundRegisterController")
public class FoundRegisterController extends HttpServlet {
private static final long serialVersionUID = 1L;
private String VIEW ="/lofo/viewFound.jsp";
private foundDAO dao;
String forward="";
String action="";
/**
* #see HttpServlet#HttpServlet()
*/
public FoundRegisterController() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String action = request.getParameter("action");
if(action.equalsIgnoreCase("viewFound")) {
forward = VIEW;
String UserEmail = request.getParameter("UserEmail");
FoundItemBean found = dao.getUserByEmail(UserEmail);
request.setAttribute("found", found);
}
RequestDispatcher view = request.getRequestDispatcher(forward);
view.forward(request, response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
action = request.getParameter("action");
try {
String FItemID = request.getParameter("FItemID");
String UserEmail = request.getParameter("UserEmail");
String FItemName = request.getParameter("FItemName");
String FItemCategory = request.getParameter("FItemCategory");
String FItemDate = request.getParameter("FItemDate");
String FItemTime = request.getParameter("FItemTime");
String FItemLocation = request.getParameter("FItemLocation");
String FItemDescription = request.getParameter("FItemDescription");
FoundItemBean found = new FoundItemBean();
found.setFItemID(FItemID);
found.setUserEmail(UserEmail);
found.setFItemName(FItemName);
found.setFItemCategory(FItemCategory);
found.setFItemDate(FItemDate);
found.setFItemTime(FItemTime);
found.setFItemLocation(FItemLocation);
found.setFItemDescription(FItemDescription);
dao = new foundDAO();
found = foundDAO.getUser(found);
try {
dao.FoundAdd(found);
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<script>");
pw.println("alert('The item post has been created');");
pw.println("window.location.href='FoundController?action=listFoundItem';");
pw.println("</script>");
}
catch (Throwable ex) {
System.out.println(ex);
}
}
}
this is my FoundController.java
package lofo.controller;
import java.io.IOException;
import java.io.PrintWriter;
import java.security.NoSuchAlgorithmException;
import java.util.List;
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 lofo.dao.foundDAO;
import lofo.model.FoundItemBean;
/**
* Servlet implementation class UserController
*/
#WebServlet("/FoundController")
public class FoundController extends HttpServlet {
private static final long serialVersionUID = 1L;
private String VIEW ="viewFound.jsp";
private String VIEWALL ="listFoundItem.jsp";
private static String UPDATE = "updateFound.jsp";
private static String DELETE = "deleteFound.jsp";
private static String SEARCH = "registerFoundItem.jsp";
String forward;
private foundDAO dao;
/**
* #see HttpServlet#HttpServlet()
*/
public FoundController() {
super();
dao = new foundDAO();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String action = request.getParameter("action");
if(action.equalsIgnoreCase("viewFound")) {
forward = VIEW;
String UserEmail = request.getParameter("UserEmail");
FoundItemBean found = foundDAO.getUserByEmail(UserEmail);
List<FoundItemBean> founds = foundDAO.getAllFound();
request.setAttribute("founds", founds );
request.setAttribute("found", found);
}
else if (action.equalsIgnoreCase("listFoundItem")) {
forward = VIEWALL;
request.setAttribute("founds", foundDAO.getAllFound());
}
else if (action.equalsIgnoreCase("updateFound")){
forward = UPDATE;
String UserEmail = request.getParameter("UserEmail");
FoundItemBean found = foundDAO.getUserByEmail(UserEmail);
List<FoundItemBean> founds = foundDAO.getAllFound();
request.setAttribute("founds", founds);
request.setAttribute("found", found);
}
else if (action.equalsIgnoreCase("search")){
forward = SEARCH;
List<FoundItemBean> found = foundDAO.getAllFound();
request.setAttribute("founds", found);
}
else if (action.equalsIgnoreCase("deleteFound")){
forward = DELETE;
String UserEmail = request.getParameter("UserEmail");
FoundItemBean found = foundDAO.getUserByEmail(UserEmail);
request.setAttribute("found", found);
}
RequestDispatcher view = request.getRequestDispatcher(forward);
view.forward(request, response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String action = request.getParameter("action");
if(action.equalsIgnoreCase("Submit")) {
String UserEmail = request.getParameter("UserEmail");
String FItemName = request.getParameter("FItemName");
String FItemCategory = request.getParameter("FItemCategory");
String FItemDate = request.getParameter("FItemDate");
String FItemTime = request.getParameter("FItemTime");
String FItemLocation = request.getParameter("FItemLocation");
String FItemDescription = request.getParameter("FItemDescription");
FoundItemBean found = new FoundItemBean();
found.setUserEmail(UserEmail);
found.setFItemName(FItemName);
found.setFItemCategory(FItemCategory);
found.setFItemDate(FItemDate);
found.setFItemTime(FItemTime);
found.setFItemLocation(FItemLocation);
found.setFItemDescription(FItemDescription);
dao = new foundDAO();
try {
dao.updateFound(found);
/*forward = VIEW;
user = UserDAO.getUserByEmail(UserEmail);
request.setAttribute("user", user); */
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<script>");
pw.println("alert('The account is updated');");
pw.println("window.location.href='/lofo/FoundController?action=viewFound&UserEmail="+ UserEmail +"';");
pw.println("</script>");
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//}
//else if(action.equalsIgnoreCase("Delete")) {
//String UserEmail = request.getParameter("UserEmail");
// = new foundDAO();
//dao.deleteUser(UserEmail);
//response.setContentType("text/html");
//PrintWriter pw = response.getWriter();
//pw.println("<script>");
//pw.println("alert('The account has been deleted');");
//pw.println("window.location.href='/Inventory/UserController?action=listAll';");
//pw.println("</script>");
//}
}
}
}
this is my foundDAO.java
package lofo.dao;
import java.sql.Statement;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import lofo.model.FoundItemBean;
import lofo.model.UsersBean;
import lofo.connection.ConnectionManager;
public class foundDAO {
static Connection currentCon = null;
static ResultSet rs = null;
static PreparedStatement ps = null;
static Statement stmt = null;
static String FItemID, UserEmail, FItemName, FItemCategory, FItemDate, FItemTime, FItemLocation, FItemDescription;
public static FoundItemBean getUser(FoundItemBean bean) {
UserEmail = bean.getUserEmail();
String searchQuery = "select * from founditem where useremail='" + UserEmail + "'";
try {
currentCon = ConnectionManager.getConnection();
stmt = currentCon.createStatement();
rs = stmt.executeQuery(searchQuery);
boolean more = rs.next();
// if user exists set the isValid variable to true
if (more) {
String UserEmail = rs.getString("UserEmail");
bean.setUserEmail(UserEmail);
bean.setValid(true);
}
else if (!more) {
System.out.println("Sorry");
bean.setValid(false);
}
}
catch (Exception ex) {
System.out.println("Log In failed: An Exception has occurred! " + ex);
}
finally {
if (rs != null) {
try {
rs.close();
} catch (Exception e) {
}
rs = null;
}
if (stmt != null) {
try {
stmt.close();
} catch (Exception e) {
}
stmt = null;
}
if (currentCon != null) {
try {
currentCon.close();
} catch (Exception e) {
}
currentCon = null;
}
}
return bean;
}
//get user by email
public static FoundItemBean getUserByEmail(String UserEmail) {
FoundItemBean found = new FoundItemBean();
try {
currentCon = ConnectionManager.getConnection();
ps=currentCon.prepareStatement("select * from founditem where useremail=?");
ps.setString(1, UserEmail);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
found.setFItemID(rs.getString("FItemID"));
found.setUserEmail(rs.getString("UserEmail"));
found.setFItemName(rs.getString("FItemName"));
found.setFItemCategory(rs.getString("FItemCategory"));
found.setFItemDate(rs.getString("FItemDate"));
found.setFItemTime(rs.getString("FItemTime"));
found.setFItemLocation(rs.getString("FItemLocation"));
found.setFItemDescription(rs.getString("FItemDescription"));
}
} catch (SQLException e) {
e.printStackTrace();
}
return found;
}
//create Found Item
public void FoundAdd (FoundItemBean bean) throws NoSuchAlgorithmException {
FItemID = bean.getFItemID();
UserEmail = bean.getUserEmail();
FItemName = bean.getFItemName();
FItemCategory = bean.getFItemCategory();
FItemDate = bean.getFItemDate();
FItemTime = bean.getFItemTime();
FItemLocation = bean.getFItemLocation();
FItemDescription = bean.getFItemDescription();
try {
currentCon = ConnectionManager.getConnection();
ps=currentCon.prepareStatement("insert into founditem(FItemID, UserEmail, FItemName, FItemCategory, FItemDate, FItemTime, FItemLocation, FItemDescription) values (FOUNDITEM_SEQ.nextval,?,?,?,?,?,?,?)");
ps.setString(1,UserEmail);
ps.setString(2,FItemName);
ps.setString(3,FItemCategory);
ps.setString(4,FItemDate);
ps.setString(5,FItemTime);
ps.setString(6,FItemLocation);
ps.setString(7,FItemDescription);
ps.executeUpdate();
System.out.println("Your FItemName is " + FItemName);
}
catch (Exception ex) {
System.out.println("failed: An Exception has occured!" + ex);
}
finally {
if (ps != null) {
try {
ps.close();
} catch (Exception e) {
}
ps = null;
}
if (currentCon != null) {
try {
currentCon.close();
} catch (Exception e) {
}
currentCon = null;
}
}
}
//update account
public void updateFound(FoundItemBean bean) throws NoSuchAlgorithmException {
FItemName = bean.getFItemName();
FItemCategory = bean.getFItemCategory();
FItemDate = bean.getFItemDate();
FItemTime = bean.getFItemTime();
FItemLocation = bean.getFItemLocation();
FItemDescription = bean.getFItemDescription();
String searchQuery = "";
searchQuery = "UPDATE founditem SET FItemName ='"+ FItemName +"', FItemCategory='" + FItemCategory + "', FItemDate='" + FItemDate + "', FItemTime='" + FItemTime + "', FItemLocation='" + FItemLocation + "', FItemDescription='" + FItemDescription + "' WHERE UserEmail= '" + UserEmail + "'";
System.out.println(searchQuery);
try {
currentCon = ConnectionManager.getConnection();
stmt = currentCon.createStatement();
stmt.executeUpdate(searchQuery);
System.out.println(searchQuery);
} catch (SQLException e) {
e.printStackTrace();
}
}
//getAllFound for list table
public static List<FoundItemBean> getAllFound() {
List<FoundItemBean> founds = new ArrayList<FoundItemBean>();
try {
currentCon = ConnectionManager.getConnection();
stmt = currentCon.createStatement();
String q = "select * from founditem";
ResultSet rs = stmt.executeQuery(q);
while (rs.next()) {
FoundItemBean found = new FoundItemBean();
found.setUserEmail(rs.getString("UserEmail"));
found.setFItemName(rs.getString("FItemName"));
found.setFItemCategory(rs.getString("FItemCategory"));
found.setFItemDate(rs.getString("FItemDate"));
found.setFItemTime(rs.getString("FItemTime"));
found.setFItemLocation(rs.getString("FItemLocation"));
found.setFItemDescription(rs.getString("FItemDescription"));
founds.add(found);
}
} catch (SQLException e) {
e.printStackTrace();
}
return founds;
}
}
The error message shown in the attached picture is -
"The origin server did not find a current representation for the target resource..."
This error is usually not due to a problem in the code.
This error is caused due to an issue with the IDE (Common with Eclipse), or due to the way the application is deployed on the Web server.
Here is a workaround for this problem:
Take a backup of the project files.
Delete the project from eclipse.
Make sure that the character encoding is set to 'utf-8' in all the html template files**
<html lang="en">
<head>
<meta charset="utf-8"/>
</head>
Restart eclipse.
Do a fresh import of the project into eclipse.
Verify the web.xml file for the correct mapping of servlets
More help:
https://www.codejava.net/java-ee/servlet/solved-tomcat-error-http-status-404-not-found
The origin server did not find a current representation for the target resource or is not ... error when running jsp page
Tomcat 404 error: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists
I have already coded the servlet and the dao part of the delete method.
Once i want to use the method in jsp page, it returned ERROR 500 / ERROR 404.
I am using tomcat 7,Java 7 and windows 10. Running oracle. I tried to use ajax to link the servlet delete method but it still didn't work.
// deleteStaffServelt
public class DeleteStaffServlet extends HttpServlet {
enter code here
/**
*
*/
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String ids = request.getParameter("userId");
int deleteId = Integer.parseInt(ids);
StaffDao staffDao = new StaffDao();
staffDao.delete(deleteId);
response.sendRedirect("deleteStaffServlet?id=" + deleteId);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
// delete method in Dao
public void delete(int id) {
try {
String sql = "delete from ZZZ_EMPLOYEES where ZE_ID = " + id;
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, id);
ps.executeUpdate();
ps.close();
} catch (Exception ex) {
ex.printStackTrace();
}
// jsp
<body>
<form action="listServletTwo">
<table border="0" cellspacing="0">
<tr>
<td>社員No. <input name="noStart" type="text" size="8" />
~ <input name="noEnd" type="text" size="8" /> <input
type="submit" value="検索" />
</td>
<td>社員名. <input name="name" type="text" size="20" /> <input
type="submit" value="検索" />
</td>
</tr>
</table>
</br>
<%
List<Staff> list1 = (List<Staff>) session.getAttribute("list");
if (list1 != null) {
%>
<table border="1" cellspacing="0">
<tr bgcolor="pink">
<td>社員No.</td>
<td>ユーザーID</td>
<td>社員名</td>
<td>削除機能</td>
<td>更新機能</td>
</tr>
<%
for (Staff s : list1) {
%>
<tr>
<td id="<%=s.getId()%>"><%=s.getId()%></td>
<td><%=s.getNo()%></td>
<td><%=s.getName()%></td>
<td>Delete</td>
<td>名前:<input name="name" type="text" size="10" /> ユーザーID:<input
name="name" type="text" size="10" />
<input type="submit" value="Edit" name="edit" onclick="editRecord(<%=s.getId()%>);">
</td>
</tr>
<%
}
}
session.removeAttribute("list");
%>
</table>
</form>
result is HTTP Status 500 – Internal Server Error
java.lang.NumberFormatException: null
Here ,Delete,you have used id=<%=s.getId()%> i.e : you are getting value <%=s.getId()%> in parameter id but in your servlet ,you are getting parameter using request.getParameter("userId"); just change this to request.getParameter("id");.
Also, your delete query is wrong it should like below :
// delete method in Dao
public void delete(int id) {
try {
//you have to give placeholder(?) in query not the value
String sql = "delete from ZZZ_EMPLOYEES where ZE_ID =?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, id);
ps.executeUpdate();
ps.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
I am not sure what you are doing here :
response.sendRedirect("deleteStaffServlet?id=" + deleteId);
But, I think you have already deleted required row from table ,so there is no need to do that again. So, just change that to below :
response.sendRedirect("yourjsppage");
Actually I am trying to insert values from java servlet to postgres DB but they are not inserting.
Thanks in advance.
My html page is
<div class="container4">
<h2>Registration form</h2>
<form action="Register" method="get" >
<div class="form-group">
<label for="firstname">First Name:</label>
<input type="text" class="form-control" id="firstname" placeholder="Enter firstname" name="firstname">
</div><br><br>
<div class="form-group">
<label for="Username">Username:</label>
<input type="text" class="form-control" id="username" placeholder="Enter username" name="username">
</div><br><br>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" class="form-control" id="email" placeholder="Enter email" name="email">
</div><br><br>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="pwd" placeholder="Enter password" name="pwd">
</div><br><br>
<div class="form-group">
<label for="address">Address:</label>
<input type="text" class="form-control" id="address" placeholder="Enter address" name="address">
</div><br><br>
<button type="submit" class="btn btn-default" id="submit">Submit</button>
</form>
</div>
My dbconnection page is
package dbConnection;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;
/**
*
* #author java2
*/
public class Dbconn {
public static Connection getConnection() {
Connection con = null;
try {
Class.forName("org.postgresql.Driver");
con = DriverManager.getConnection("jdbc:postgresql://localhost:5432/classes","postgres", "admin123$");
System.out.println("db successfull");
} catch (Exception ex) {
ex.printStackTrace();
System.out.println("db not successfull");
}
return con;
}
}
Register.java
package register;
import dbConnection.Dbconn;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.Statement;
import java.util.Random;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Register extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Connection con = null;
Statement st = null;
String n=request.getParameter("firstname");
String p=request.getParameter("username");
String e=request.getParameter("email");
String c=request.getParameter("pwd");
String d=request.getParameter("address");
try {
con = Dbconn.getConnection();
st = con.createStatement();
int i = st.executeUpdate(
"insert into register (firstname, username, email, pwd, address) values('"+n+"','"+p+"','"+e+"','"+c+"','"+d+"')");
con.commit();
System.out.println("hello successfull");
if (i == 0) {
response.sendRedirect("login.html?msg=success");
} else {
response.sendRedirect("register.html?msg=failed");
}
} catch (Exception ex) {
ex.printStackTrace();
}
}}
When I run this program I am getting like
http://localhost:8088/trial/Register?firstname=jack&username=jack&email=jack%40gmail.com&pwd=jack&address=hyd
I am getting all the details in url and displays blank page without errors. I am not understanding where I went wrong.
I have this:
In addMusic.jsp:
<form method="post" action="Handler" enctype="multipart/form-data">
<div class="form-group">
<label>Musica:</label>
<input type="text" class="form-control" name="add_musica_nome" placeholder="Nome Musica">
</div>
<div class="form-group">
<label>Localização:</label>
<input type="file" class="form-control" name="add_musica_path" accept="audio/*">
</div>
<div class="form-group">
<label>Ano:</label>
<input type="text" class="form-control" name="add_musica_ano" pattern="[0-9]{4,4}">
</div>
<div class="form-group">
<input type="hidden" name="logica" id="logica" value="SMusica"/>
<input type="hidden" name="acao" id="acao" value="addMusica"/>
<input class="btn btn-success" type="submit" value="Inserir" name="inserir"/>
</div>
</form>
In Handler:
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String parametro = request.getParameter("logica"); // Recebe como parametro do jsp, qual a class do service que
// irá atuar
String nomeDaClasse = "services." + parametro; // Nome da Classe
try {
Class<?> classe = Class.forName(nomeDaClasse);
Logica logica = (Logica) classe.newInstance();
String pagina = logica.executa(request, response);
request.getRequestDispatcher(pagina).forward(request, response);
} catch (Exception e) {
throw new ServletException("A lógica causou uma exceção", e);
}
}
and in SMusica:
final String Dest = "/data/";
public void addMusica(String musica_nome, Part musica, String ano) throws IOException {
String fileName = Paths.get(musica.getSubmittedFileName()).getFileName().toString(); // MSIE fix.
try {
File music = new File(fileName);
System.out.println("Path: " + music.getAbsolutePath());
if (music.renameTo(new File(Dest + music.getName()))) {
System.out.println("File is moved successful!");
} else {
System.out.println("File is failed to move!");
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public String executa(HttpServletRequest req, HttpServletResponse res) throws Exception {
if (req.getParameter("acao").equals("addMusica")) {
addMusica(req.getParameter("add_musica_nome"), req.getPart("add_musica_path"),
req.getParameter("add_musica_ano"));
}
return "/index.jsp";
}
And i made a print of absolutePath of music(File) and it returns C:\Users\Fabio\Desktop\eclipse\ProfJam_-_Mortalhas.mp3, not the real path.
My question is how can i get the real path of the file?
There is a method in path called
Path _rp = p.toRealPath();
Maybe you Can search in this direction
I am creating an online bank. On login, it created a session for that user. The user than has options to click on different transaction types.So when the user clicks on open an account button, it will go to openAccount.jsp page. I also have a form with a users first name, last name, and email in the openAccount.jsp. When the user clicks on the open account button and is redirected to the openAccount.jsp, I want the form to be prefilled from the database based. I am not sure how? Here is my code so far:
home-page.jsp
<div class="col-md-4">
<form name = "OpenAccount" action="open-account.jsp" id="openaccount">
<p>
<button type="submit" class="btn btn-primary btn-lg">Open Account</button>
</p>
</form>
</div>
open-account.jsp
<!DOCTYPE html>
<html>
<head>
<title>Open Account</title>
</head>
<body>
<h3>Please fill in the details</h3>
<form name="predifinedFields">
First Name: <input type="text" name="firstname" value= <%= request.getAttribute("firstname") %> > <br/><br/>
Last Name: <input type="text" name="lastname" value= <%= request.getAttribute("lastname") %>> <br/><br/>
Email: <input type="text" name="email" value= <%= request.getAttribute("email") %>> <br/><br/>
</form>
<form name="openAccount" action="OpenAccount" method="POST">
Select the type of account:
<select name="accounttype">
<option>Checking</option>
<option>Saving</option>
</select> <br/><br/>
Initial Deposit: $<input type="text" name="deposit"> <br/><br/>
Please check the box if everything above is complete:
Agree <input type="radio" name="agree" value="Agree">
Disagree <input type="radio" name="agree" value="Disagree">
<br/><br/>
<input type="submit" value="submit" name="Submit">
</form>
</body>
</html>
OpenAccount.java
public class OpenAccount extends HttpServlet
{
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
String username = "";
HttpSession session = request.getSession(false);
if(session != null)
{
username = (String) session.getAttribute("username");
Users users = new Users();
users = DBConnection.getUsers(username);
request.setAttribute("firstname", users.getFirstName());
request.setAttribute("lastname", users.getLastName());
request.setAttribute("email", users.getEmail());
//request.setAttribute("username", users.getUsername());
}
// String firstName = (String) request.getParameter("firstname");
// String lastname = (String) request.getParameter("lastname");
String email = (String) request.getParameter("email");
String accountType = (String) request.getParameter("accounttype");
String accept = (String) request.getParameter("agree");
String deposit = (String) request.getParameter("deposit");
if(accept.equals("Agree"))
{
if(accountType.equals("Checking"))
{
DBConnection.newCheckingAccount(email, deposit);
RequestDispatcher dispatcher = request.getRequestDispatcher("home-page.jsp");
dispatcher.forward(request, response);
}
else if(accountType.equals("Saving"))
{
DBConnection.newSavingAccount(email, deposit);
RequestDispatcher dispatcher = request.getRequestDispatcher("home-page.jsp");
dispatcher.forward(request, response);
}
}
else
{
System.out.println("Please modify the changes");
RequestDispatcher dispatcher = request.getRequestDispatcher("open-account.jsp");
dispatcher.forward(request, response);
}
}
}
Database.java
public static Users getUsers(String username)
{
Users user = new Users();
try
{
DBConnection.connectToDB();
String query = "SELECT * FROM userlogin where username=?";
stmt = DBConnection.conn.prepareStatement(query);
stmt.setString(1,username);
ResultSet rs = stmt.executeQuery();
while(rs.next())
{
user.setFirstName(rs.getString("firstname"));
user.setLastName(rs.getString("lastname"));
user.setEmail(rs.getString("email"));
user.setUsername(rs.getString("username"));
user.setPassword(rs.getString("password"));
}
}
catch(Exception e)
{
System.out.println(e);
}
return user;
}
In your case (basic servlet), you should follow this logic :
->browser
->servlet which loads and prepares required data from database into request attributes as you have done and finally forwards to open-account.jsp
->open-account.jsp use request attributes to render dynamically fields with your data retrieved from your database.
For other use cases, try to keep this simple logic :
->browser
->servlet processing ....
->jsp rendering ....
Your form in home-page.jsp should post to the servlet (controller) :
<div class="col-md-4">
<form name = "OpenAccount" action="/OpenAccount" id="openaccount">
<p>
<button type="submit" class="btn btn-primary btn-lg">Open Account</button>
</p>
</form>
</div>
You should rename OpenAccount to OpenAccountServlet (keeping conventions is better) and configure correctly the servlet of OpenAccountServlet in your web.xml (or with annotations).
If you use web.xml file for the servlet configuration, the url posted in the previous jsp (action="/OpenAccount") should match with the value in <url-pattern>/OpenAccount</url-pattern>
The forward should do like that :
getServletContext().getRequestDispatcher("yourRequiredPath/open-account.jsp ").forward(request, response);