I am trying to delete users from my database using Ajax, Servlet and HTML. when I submit data Illegal Invocation occurs. I think that there won't be any problems with connection or SQL statement
delete.html
<input type="text" id="delete">
<input type="submit" onclick="deleteUSer()" value="Delete">
delete.js
function deleteUSer(){
var username = document.getElementById("delete");
var params = {
username: username
}
$.post("Delete", params, function(data){}
)
}
Delete.java servlet
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = null;
DBUtils dbutils = null;
Connection conn = null;
try{
String username = request.getParameter("username");
dbutils = new DerbyUtils();
conn = dbutils.getConnection();
DeleteDAO dao = new DeleteDAO(conn);
dao.deleteUser(username);
RequestDispatcher dispatcher =
getServletContext().getRequestDispatcher("/index.html");
dispatcher.forward(request, response);
}
DeleteDAO.java
public void deleteUser(String username) throws SQLException{
try{
String sql = "delete from users where username='"+username+"'";
PreparedStatement ps = this.conn.prepareStatement(sql);
ps.executeQuery();
you are sending html doc elemect not username ...
try this --
<input type="text" id="delete" value="vivek">
<input type="submit" onclick="deleteUSer()" value="Delete">
function deleteUSer(){
var username = document.getElementById("delete");
var params = {
username: username.value
}
$.post("Delete", params, function(data){}
)
}
If you're trying to enact the "delete" command that you can use with HTTP requests, you're going to want to use $.ajax, not $.post.
To quote the docs (https://api.jquery.com/jQuery.post/):
This is a shorthand Ajax function, which is equivalent to:
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});
if you're trying to enact the "delete", you'd want to do something like:
var dataObj = {
'username': document.getElementById("delete").value;
}
$.ajax({
type:"DELETE",
data: dataObj,
url: 'url/to/your/servlet'
});
You may also want to include a datatype in there but for this example jquery can figure it out.
Related
Not sure how to solve this, need some help here.
Ajax call brings user information to servlet, I save user object in HttpSession and control goes back to Ajax from where i redirect control to next JSP page via controller servlet. However, if i try to retrieve object from HttpSession it is null .. not sure how to solve this issue.
here is my code for firstservlet:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// get values from http request
// persist "user" object to database
HttpSession session = request.getSession(); //
session.setAttribute("user", user); //setting session variable
Gson gson = new Gson();
JsonElement jsonElement = null;
jsonElement = gson.toJsonTree("/nextservlet");
response.setContentType("text/plain");
PrintWriter out=response.getWriter();
}
here is my Javascript / AJAX code to redirect request to nextservlet
$.ajax({
type: 'POST',
url: ‘firstservlet’,
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify(quiz),
success: function(result) {
//result = /nextservlet
window.location.href = result;
},
error:function(data,status,er) {
console.log("Error:",er);
}
});
and finally control comes to nextservlet - where i would like to process data and then show new JSP page.
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
HttpSession session = request.getSession();
User user = session.getAttribute(“user”); //<--- this is NULL
LOG.warning("User id is : " + user.getId()); //<--- hence error here
RequestDispatcher dispatcher = request.getRequestDispatcher
("/anotherpage.jsp");
dispatcher.forward(request, response);
}
is issue because i am using -> window.location.href = result to send request to nextservlet .. and it goes to doGet??
I am not sure it but I see in Ajax
url: ‘firstservlet’,
type: 'POST'
and control goes to doGet method of nextservlet. It should be nextservlet of post method so use method doPost.
18.12.22
i'm not sure... but try it
success: function(result) {
// result = /nextservlet
var form = document.createElement('form');
form.action = result;
form.method = 'GET'
form.submit();
}
18.12.26
Javascript
$.ajax({
type: 'POST',
url: '/firstservlet',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringfy(quiz),
success: function(result) {
console.info(result);
var form = document.createElement('form');
form.action = result;
form.method = 'GET';
document.body.appendChild(form);
form.submit();
},
error: function(data, status, err) {
console.log("Error: ", err);
}
});
Servlet
HttpSession session = request.getSession();
session.setAttribute("test", "test");
Gson gson = new Gson();
JsonElement jsonElement = gson.toJsonTree("/nextservlet");
response.setContentType("text/plain");
PrintWriter out = response.getWriter();
out.print(gson.toJson(jsonElement));
It can read session attribute in doGet Method try it.
I have a user Sign in Html form where I get the user's email and password and check them against a database. So far I have the following code but when I submit the form it does not go to the specified JSP page. What can I do to improve my code and how can I just generate an error message when the user presses submit but still stay on the same page?
Thank you in advance.
//SERVLET doPost Method
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String userinp = request.getParameter("userinp"); //hidden type in html sign up form
HttpSession s = request.getSession();
User u = new User();
if(userinp.equals("signup")) {
u.setName(request.getParameter("name"));
u.setLname(request.getParameter("lname"));
u.setEmail(request.getParameter("email"));
u.setPassword(request.getParameter("password"));
s.setAttribute("User", u);
//Save to DB
u = (User)s.getAttribute("User");
s.invalidate();
UserM ud = new UserM(); //class which contains CRUD methods
ud.createTable();
ud.insert(u);
ServletContext ctx = request.getSession().getServletContext();
forwardTo(ctx, request, response, "/Somepage.jsp");
} else if(userinp.equals("login")) {
String pass1 = request.getParameter("pass");
String email = request.getParameter("useremail");
Connection conn = null;
PreparedStatement stm = null;
try {
conn = ConnectionConfiguration.getConnection();
stm = conn.prepareStatement("SELECT password FROM users WHERE email = ?");
stm.setString(4, email);
ResultSet resultSet = stm.executeQuery();
while(resultSet.next()) {
String pass2 = resultSet.getString("password");
if(pass1.equals(pass2)) {
ServletContext ctx = request.getSession().getServletContext();
forwardTo(ctx, request, response, "/Somepage.jsp");
} else {
//code to generate "Wrong Password" message
}
}
} catch(Exception e) {
e.printStackTrace();
} finally {
if(stm != null) {
try {
stm.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(conn != null) {
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
//ForwardTo Method
public static void forwardTo(ServletContext ctx, HttpServletRequest req, HttpServletResponse resp, String dest) throws ServletException
{
RequestDispatcher rd = ctx.getRequestDispatcher(dest);
try
{
rd.forward(req, resp);
}
catch(Throwable t)
{
t.printStackTrace();
throw new ServletException(t);
}
}
//HTML FORM
<html>
<head>
<meta charset="ISO-8859-1">
</head>
<body>
<form action = "UserServ" method="POST">
<h3>Enter the details below to Sign In</h3><br>
Email: <input type="text" name="useremail" required><br>
Password: <input type="password" name="pass" required><br>
<input type="submit" value="Sign In">
</form>
</body>
</html>
You have an error in your database preparedStatement:
stm.setString(4, email);
What is 4 supposed to be here? The first parameter of setString corresponds to the '?' in your prepared statement.
stm = conn.prepareStatement("SELECT password FROM users WHERE email = ?");
You only have 1 question mark, so it should be:
stm.setString(1, email);
What can I do to improve my code
Seperate the database logic from your servlet. Use the MVC pattern, it will make your life easier.
and how can I just generate an error
You can easily achieve this with JSTL/EL in your JSP. Set an attribute in your servlet and forward that to the jsp page. JSTL will check if the attribute exists and show the appropriate message.
You could also just forward the user to a specific page if the details are wrong, like i have shown in the example below.
A more advanced way would be to implement AJAX, this is basically using javascript to make asynchronous calls to your servlet so that you don't have to refresh the page. You could use this to check see if the details are correct.
message when the user presses submit but still stay on the same page?
You mean if they haven't typed in any details? You could use javascript/jquery to do this. Maybe disable the submit btn/form from submitting when the text fields are empty.
Below is your servlet code, i condensed your database logic. Much easier to manage this way:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String userinp = request.getParameter("userinp"); //hidden type in html sign up form
HttpSession s = request.getSession();
User u = new User();
ServletContext ctx = s.getServletContext();
//check for null first, because if userinp is empty, then you will get a NPE
if(userinp != null && userinp.equals("signup")) {
u.setName(request.getParameter("name"));
u.setLname(request.getParameter("lname"));
u.setEmail(request.getParameter("email"));
u.setPassword(request.getParameter("password"));
s.setAttribute("User", u);
//Save to DB
u = (User)s.getAttribute("User");
s.invalidate();
UserM ud = new UserM(); //class which contains CRUD methods
ud.createTable(); //why are you creating a table for each user? (you need to create a table called 'users' and just insert the new user there.
ud.insert(u);
forwardTo(ctx, request, response, "/Somepage.jsp");
} else if( userinp != null && userinp.equals("login")) { //you should separate the register and login logic (easier to maintain in two different servlets
String pass1 = request.getParameter("pass");
String email = request.getParameter("useremail");
//so instead of getting the password from the database, you can check to see if the details exist instead and return a boolean.
if(validate(email,pass1)){
forwardTo(ctx, request, response, "/Welcome.jsp"); //user is logged in
}else{
forwardTo(ctx, request, response, "/Error.jsp"); //user is not logged in, details do not match
}
}
}
validate method:
//this should be in a different class. So it's easier to maintain and can be used elsewhere. It's bad practice to have database logic in your servlet. Because what if you want to use this in a different servlet or another part of your application? (you don't want to copy and pasta it everywhere do you?)
public static boolean validate(String email, String password){
boolean status = false;
PreparedStatement pst = null;
ResultSet rs = null;
//if you put your getConnection method as a try condition, it will automagically close the connection for you.
try(Connection conn= ConnectionConfiguration.getConnection()){
pst = conn.prepareStatement("select * from users where email=? and password=?;");
pst.setString(1, email); //1 here corresponds to the first '?' in preparedStatement
pst.setString(2, password); //2 corresponds to the second '?'
rs = pst.executeQuery();
status = rs.next(); //if there are any results, then status is true.
} catch (SQLException e) {
e.printStackTrace();
}
return status;
}
Let me know if you have problems anywhere or other questions, happy to help.
I've searched for username availability in google. There was no any good solution to this problem. Here I'm trying to check username availability in database table user. I have following code
<input type="text" name="username" id="usernamee" tabindex="1"class="form-control" placeholder="Username"><span class="status">
this is my script code
<script>
$(function(){
$("#usernamee").blur(function(){
var uname = $('#usernamee').val();
if(uname.length >= 3){
$(".status").html("<font> Checking availability...</font>");
$.ajax({
type: "GET",
url: "/exist/"+uname,
success: function(msg){
$(".status").html(msg);
}
});
}
else{
$(".status").html("<font color=red>Username should be <b>3</b> character long.</font>");
}
});
});
</script>
this is my controller code
#RequestMapping(value = { "/exist/{name}" }, method = RequestMethod.POST)
public void checkUsername(#PathVariable("name") String username, HttpServletResponse response , HttpServletRequest request) throws IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
String connectionURL = "jdbc:mysql://localhost:81/name"; // students is my database name
Connection connection = null;
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = (Connection) DriverManager.getConnection(connectionURL, "root", "root");
PreparedStatement ps = (PreparedStatement) connection.prepareStatement("select username from users where username=?");
ps.setString(1,username);
ResultSet rs = ps.executeQuery();
if (!rs.next()) {
out.println("<font color=green><b>"+username+"</b> is avaliable");
}
else{
out.println("<font color=red><b>"+username+"</b> is already in use</font>");
}
out.println();
} catch (Exception ex) {
out.println("Error ->" + ex.getMessage());
} finally {
out.close();
}
}
When I run these code the statusspan tag only shows checking availability..... only. My controller haven't been invoked.
Above code is copied from internet. Any suggestions are welcomed.
Thank you in advance
You send GET request
$.ajax({
type: "GET"
But your controller expect POST
#RequestMapping(value = { "/exist/{name}" }, method = RequestMethod.POST)
Either change ajax to POST or controller to GET
I haven't get you question from what you said above, but you should add #ResponseBody for ajax request.
I recall what I said above, PrintWriter is used and #ResponseBody is not needed, but use #ResponseBody will be better
I have read the similar topics like this, and that one but it did not help with my problem.
I created a simple JavaEE mvc web app. The jsp page contains a form with two text fields and two buttons. The first text field to enter an Id, the second to enter a name. Depending on which button is clicked a Servlet routes to the appropriate method (Search by ID or Search by Name).
Search by id method works correctly. And I see the following path in the address bar: http://localhost:8080/employees_war_exploded/ControllerServlet?textEmployeeId=1&command=Search_ID&employeeName=
However there is a problem with a Search by name method. It does not show any results. Here is what I see in the address bar: http://localhost:8080/employees_war_exploded/ControllerServlet?textEmployeeId=&employeeName=ann&command=Search_Name
I guess the problem is that in both cases it gets the parameters of both text fields ("textEmployeeId" and "employeeName"). How can I make it process both inputs separately in the same form? Maybe there is some other reason for the problem that I do not see?
<form class="form-style" name="form1">
<label>ID:
<input type="text" name="textEmployeeId" value="${tempEmployee.id}" />
</label>
<input type="submit" name="command" value="Search_ID">
<br>
<br>
<label>Name:
<input type="text" name="employeeName" value="${tempEmployee.name}" />
</label>
<input type="submit" name="command" value="Search_Name">
<br>
<br>
</form>
ControllerServlet.java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
String theCommand = request.getParameter("command");
if (theCommand == null) {
theCommand = "EMPLOYEE_LIST";
}
// route to the appropriate method
switch (theCommand) {
case "EMPLOYEE_LIST":
listEmployees(request, response);
break;
case "Search_ID":
searchById(request, response);
break;
case "Search_Name":
searchByName(request, response);
break;
default:
listEmployees(request, response);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void searchByName(HttpServletRequest request, HttpServletResponse response) throws Exception {
String nameString = request.getParameter("employeeName");
List<Employee> namedEmployees = employeeDbUtil.searchEmployees(nameString);
request.setAttribute("EMPLOYEES", namedEmployees);
RequestDispatcher dispatcher = request.getRequestDispatcher("/search-by-name.jsp");
dispatcher.forward(request, response);
}
private void searchById(HttpServletRequest request, HttpServletResponse response) throws Exception {
String textString = request.getParameter("textEmployeeId");
Employee theEmployee = employeeDbUtil.getEmployeeById(textString);
request.setAttribute("THE_EMPLOYEE", theEmployee);
RequestDispatcher dispatcher = request.getRequestDispatcher("/show-employee.jsp");
dispatcher.forward(request, response);
}
}
Update: I'm getting a NullPointerException for the searchByName method. Could there be a problem with this method from a DAO class that is called from ControllerServlet?
public List<Employee> searchEmployees(String employeeName) throws Exception {
List<Employee> employeeList = new ArrayList();
Connection myConnection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
employeeName += "%";
preparedStatement = myConnection.prepareStatement("SELECT * FROM employees WHERE LOWER(name) like LOWER(?)");
preparedStatement.setString(1, employeeName);
resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
Employee tempEmployee = resultSetToEmployee(resultSet);
employeeList.add(tempEmployee);
}
return employeeList;
}
finally {
DbExceptions.close(resultSet);
DbExceptions.close(preparedStatement);
DbExceptions.close(myConnection);
}
}
Iam trying to validate and insert a data. here if the username exists in file service it should dispatch with error message but after the validation it is dispatched with error message with inserting data in file service. I cant fine where am failing in code.
My JSP:
<form name="create" id="myform" action="/create" method="post">
User Name: <input type="text" name="cliname"/>
<input type ="submit" value="submit"/>
</form>
My Servlet:
public class CreateForm extends HttpServlet {
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException, ServletException {
String uname = req.getParameter("cliname");
Query query1 = new Query("Users");
List<Entity> cli_id = datastore.prepare(query1).asList(FetchOptions.Builder.withDefaults());
for (Entity client : cli_id){
username = (String)client.getProperty("User Name");
if(username.equals(uname)) {
RequestDispatcher rd = req.getRequestDispatcher("/Create.jsp");
req.setAttribute("errormsg", "User Name Already Exists");
rd.forward(req, resp);}}
Entity userInput = new Entity("Users");
userInput.setProperty("User Name", uname);
datastore.put(userInput);
}}
Kindly suggest me an idea,
Your help is appreciated.
I have updated your code.
public class CreateForm extends HttpServlet {
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
String uname = req.getParameter("cliname");
Query query1 = new Query("Users");
List<Entity> cli_id = datastore.prepare(query1).asList(FetchOptions.Builder.withDefaults());
RequestDispatcher rd = null;
for (Entity client : cli_id){
username = (String)client.getProperty("User_Name");
if(username.equals(uname)) {
req.setAttribute("errormsg", "User Name Already Exists");
rd = req.getRequestDispatcher("/error.jsp");
}else{
Entity userInput = new Entity("Users");
userInput.setProperty("User_Name", uname);
datastore.put(userInput);
req.setAttribute("success", "User Name Added");
rd = req.getRequestDispatcher("/Create.jsp");
}
}
rd.forward(req, resp);
}
}