Error in delete a user in spring mvc - java

I can't delete a user. This is the error i get when i click the delete button. org.springframework.dao.TransientDataAccessResourceException: PreparedStatementCallback; SQL [DELETE FROM users WHERE id = '1']; Parameter index out of range (1 > number of parameters, which is 0).; nested exception is java.sql.SQLException: Parameter index out of range (1 > number of parameters, which is 0). Please help thanks a lot
Jdbc function of delete
public int deleteUser(int id){
String SQL = "DELETE FROM users WHERE id = '"+id+"'";
System.out.print(SQL);
int user = jdbcTemplateObject.update(SQL, id);
return user;
}
delete controller
RequestMapping(value = "/delete", method = RequestMethod.GET)
public ModelAndView delete(#ModelAttribute("SpringWeb")User user, ModelMap model, HttpServletRequest request)
{
try
{
SyntacksJdbc syntacksJdbc = (SyntacksJdbc)context.getBean("syntacksJdbc");
System.out.println(request.getParameter("id"));
int id = Integer.parseInt(request.getParameter("id"));
int user1 = syntacksJdbc.deleteUser(id);
model.addAttribute("message", "Questions updated successfully.");
}
catch(Exception e)
{
System.out.print(e);
model.addAttribute("message", "Error occured in posting question.");
}
return new ModelAndView("users");
on my jsp button
<a href="/Project/delete?id=${user.id}" name="delete"><button type= submit>Delete</button>

change query to
DELETE FROM users WHERE id = ?
since you are trying to set parameter value

Related

Problem to implement FindById to a return statement in java with MongoDB

UPDATE: The return statement is still not working as expected to show single user detail by id in the DAO. I could only use for loop to iterate through the _id to match the userId, but when I click the edit button for the number of user will show all previous user Id in the console.
Another problem is when I call this method in the Service class, the output is null. Still crave for the solution to help me get over it.
#Override
public User get(Object userId) {
User user = new User();
FindIterable<Document> userTbl = database.getCollection("User").find();
for (Document doc : userTbl) {
String id = doc.getObjectId("_id").toString();
System.out.println("_id = " + id);
if (id.equals(userId)) {
return user;
}
}
return null;
}
edit user in Service class
public void editUser() throws ServletException, IOException {
Object userId = request.getParameter("id"); // get query string from the jsp
User user = userDAO.get(userId);
System.out.println("User full name is? " + user.getFullName());
}
After getting hints from #Smutje and think through it again, finally figured it out at my 2nd weeks of learning MongoDB. At my level I need to iterate the user document then find the id and return it.it
#Override
public User get(Object userId) {
FindIterable<User> userTbl = database.getCollection("User", User.class).find();
for (User doc : userTbl) {
String id = doc.getId().toHexString();
System.out.println("_id = " + id);
if (id.equals(userId)) {
return doc;
}
}
return null;
}

Spring Data JPA query returns null

My project based on spring boot,Thymeleaf,mysql,html and Jquery.
i wrote a query for checking user name and password is valid or not,if valid means return TRUE otherwise false..This is my scenario..but it passing null...so it becomes nullpointer exception..
Here is my code
public interface RepoUserSignup extends JpaRepository<EntUserSignup, Integer>
{
#Query("SELECT pk FROM EntUserSignup pk WHERE pk.username=:uname AND pk.password=:pwd")
Boolean checkUsername(#Param("uname") String username,#Param("pwd") String password);
}
Please help me..Thanks in advance
Your query return an Object and not a boolean so you have two ways :
Your method should return EntUserSignup checkUsername(#Param("uname") String username,#Param("pwd") String password); instead then check if there are a result or not
Another way is to check the number of result #Query("SELECT COUNT(pk) > 0 FROM EntUserSignup pk WHERE pk.username=:uname AND pk.password=:pwd") so if there are some results COUNT(pk) > 0 will return true else it will return false
Replace your method with this:
Optional<EntUserSignup> findByUsernameAndPassword(String username, String password);
Then in your business layer you can do something like this:
EntUserSignup user = findByUsernameAndPassword(username, password)
.orElseThrow(() -> new UsernameNotFoundException("User not found!"));
And of cause don't forget about password in plain text...
A good tutorial how to implement security in Spring Boot application...
i just change my return type
#Query("SELECT pk FROM EntUserSignup pk WHERE pk.username=:uname AND pk.password=:pwd")
EntUserSignup checkUsername(#Param("uname") String username,#Param("pwd") String password);
So when passing username and password matches menans it will return the entity value otherwise null.so we can decide there is no matched username and password.then we can write the logic as
#Service
public Boolean doCheckUserLogin(EntUserSignup user) {
Boolean result = false;
try {
EntUserSignup entResult = repoSignup.checkUsername(user.getUsername(),user.getPassword());
if(entResult!=null)
{
result = true;
}
else
{
result = false;
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
result = false;
}
return result;
}
This logics works perfectly...

Error while querying for a column in database using spring

I am trying to query an entire column data for eg:
SELECT USER_USERNAME FROM xxxx WHERE USER_USERNAME=?
I'm getting error
org.springframework.dao.EmptyResultDataAccessException: Incorrect result size: expected 1, actual 0
My Dao
#Override
public String getAllUsers(UserRegistration uname) {
System.out.println(uname.getUserName());
return template.queryForObject(GET_USER_USERNAME, new Object[] { uname.getUserName() },
new BeanPropertyRowMapper<String>(String.class));
}
I'm injecting the properties through xml file.
my controller
#RequestMapping(method = RequestMethod.POST,value = "/checkUserName", headers = "Accept=application/json")
public org.weber.nag.model.UserRegistration checkUserName(#RequestBody org.weber.nag.model.UserRegistration userReg) {
userDao.getAllUsers(userReg);
return userReg;
}
So from the above when i am trying to pass the username from postman it takes the values to controller and from there I'm passing it to my dao to compare whether the name exits or not.The name successfully reaches my dao but I get an error.
So I tried to catch the exception
#Override
public String getAllUsers(UserRegistration uname) {
System.out.println(uname.getUserName());
try {
return template.queryForObject(GET_USER_USERNAME, new Object[] { uname.getUserName() },
new BeanPropertyRowMapper<String>(String.class));
} catch (EmptyResultDataAccessException e) {
System.out.println("uname already exists");
return "user exists";
}
}
But every time it prints
"uname already exists"
irrespective of the username given whether it is there in db or not.
In JdbcTemplate , queryForInt, queryForLong, queryForObject all such methods expects that executed query will return one and only one row.
If you get no rows that will result in EmptyResultDataAccessException.
From the javadoc of EmptyResultDataAccessException
Data access exception thrown when a result was expected to have at
least one row (or element) but zero rows (or elements) were actually
returned.
Make sure the query you are using should return only one row.
If at all it is not possible then use query method instead of queryForObject.
Tip: To debug this, run the same query in an SQL IDE directly.
#Override
public String getAllUsers(UserRegistration uname) {
try {
template.queryForObject(GET_USER_USERNAME, new Object[] { uname.getUserName() },
new BeanPropertyRowMapper<String>(String.class));
System.out.println("uname exists");
return "user name is NOT available.";
} catch (EmptyResultDataAccessException e) {
System.out.println("uname do not exists");
}
return "user is available";
}

Spring MVC - delete record from JSP table

I got table in JSP, which is table's mirror image from database (all records and columns are displayed), and next to each row I got button "delete" which deletes row from database by ID. But when I click "delete" button then nothing happens in database, it seems like selected row's ID is null, but at address bar selected ID is displayed. What am I doing wrong?
Controller:
#RequestMapping(value="/checkout.html", method = RequestMethod.POST)
public ModelAndView checkOut(Model model, #RequestParam(value = "id", required = false) String id) throws SQLException{
setAppContext();
clinicService.deletePatient(id);
List<Patient> patients = clinicService.getAllpatients();
model.addAttribute("patients", patients);
ModelAndView checkout = new ModelAndView("CheckOut");
return checkout;
}
DAO:
public void deletePatient(String id) throws SQLException {
String query = "delete FROM virtualclinic.patient WHERE idpatient=?";
Connection con = null;
PreparedStatement ps = null;
con = dataSource.getConnection();
ps = con.prepareStatement(query);
ps.setString(1, id);
int out = ps.executeUpdate();
}
Service:
public void deletePatient(String id) throws SQLException {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("clinicconfig.xml");
patientDAO = ctx.getBean("patientDAO", PatientDAOImpl.class);
patientDAO.deletePatient(id);
}
JSP file:
<c:forEach items="${patients}" var="patient">
<tr style="font-size: 10">
<td>${patient.id}</td>
<td>${patient.name}</td>
<td>${patient.lastName}</td>
<td>${patient.gender}</td>
<td>${patient.age}</td>
<td>${patient.phoneNumber}</td>
<td>${patient.address}</td>
<td>${patient.disease}</td>
<td>${patient.condition}</td>
<td>${patient.roomType}</td>
<td>${patient.roomNumber}</td>
<td>${patient.date}</td>
<td><form action="/VirtualClinic/checkout.html?selectedPatient=${patient.id}" method="post"><input type="submit" value="Delete"/></form></td>
</tr>
</c:forEach>
Error(?):
INFO: Mapped "{[/checkout.html],methods=[GET]}" onto public org.springframework.web.servlet.ModelAndView org.damian.controller.CheckOutController.infoPatient(org.springframework.ui.M odel) throws java.sql.SQLException
lut 17, 2016 3:16:57 AM org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMa pping register
INFO: Mapped "{[/checkoutPatient.html],methods=[GET]}" onto public org.springframework.web.servlet.ModelAndView org.damian.controller.CheckOutController.checkOut(org.springframework.ui.Model,java.lang.String) throws java.sql.SQLException
Use and GET rather than a POST and because on the url you are using the parameter selectedPatient rather than your expected id - change either/or
Make your controller method get
#RequestMapping(value="/checkout.html", method = RequestMethod.GET)
public ModelAndView checkOut(Model model, #RequestParam(value = "selectedPatient", required = false) String id) throws SQLException{
setAppContext();
clinicService.deletePatient(id);
List<Patient> patients = clinicService.getAllpatients();
model.addAttribute("patients", patients);
ModelAndView checkout = new ModelAndView("CheckOut");
return checkout;
}
change your delete link as follow
<td>delete</td>
I dont see anyreason to make the request by post it is just one parameter, you dont need the form

How can I compare request.getParameter(string) in Controller class with MySQL database?

I'm currently working on a (relatively) basic web application that functions as a time clock for a fictional employer. Currently, the application implements HTML, JavaScript, Java, MySQL, the Spring Framework and xml. I have a log in page, and it takes the user input for the Username and Password and stores the information. The problem is, I can't seem to figure out how to take that information and compare it with the MYSQL database to successfully log in. I can post examples of code, if necessary and thanks in advance for the assistance.
This is a piece of the LoginController:
#RequestMapping(value = "/jsp/login")
public ModelAndView existUser(HttpServletRequest request) {
return new ModelAndView("UserPrint.jsp", hashmap.makeHashMap());
}
#RequestMapping(value = "userLogin")
public ModelAndView loginUser(HttpServletRequest request,
HttpSession session) {
String strLoginJsp = "login.jsp";
String strSessionErrorAttribute = "errors";
User sessionUser = getUserFromSession(session);
if (request.getHeader("referer") == null
|| request.getHeader("referer").contains("AddNewUser.html")) {
session.setAttribute(SESSION_USER_ATTRIBUTE, new User());
session.setAttribute(strSessionErrorAttribute, "");
return new ModelAndView(strLoginJsp, hashmap.makeHashMap());
}
User requestUser = new User();
String requestedUserName = request.getParameter("userName");
requestUser.setUserName(requestedUserName);
String requestedPassword = request.getParameter("password");
requestUser.setPassword(requestedPassword);
session.setAttribute(strSessionErrorAttribute, "");
// Check if username and password is in DB
User loginUser = userDao.login(requestUser);
if (loginUser == null) {
// Either the username doesn't exist, or the password was bad.
if (userDao.userNameExist(requestedUserName)) {
// user entered bad password
if (sessionUser.getUserName() != null
&& sessionUser.getUserName().equals(
requestUser.getUserName())) {
} else {
sessionUser.setUserName(requestUser.getUserName());
}
}
} else {// username does not exist in db
session.setAttribute(strSessionErrorAttribute,
"Please register account.");
Here's a piece of the UserDao:
#SuppressWarnings("unchecked")
#Transactional
public List<User> getAllUsers() {
Query query = em.createNamedQuery("fetchAllUsers");
return query.getResultList();
}
public User login(User user) {
Query query = em.createNamedQuery("userLogin");
query.setParameter("userName", user.getUserName());
query.setParameter("password", user.getPassword());
List<User> currentUsers = query.getResultList();
if (currentUsers.size() > 0) {
return (User) currentUsers.get(0);
}
return null;
}
#SuppressWarnings("unchecked")
#Transactional
public Boolean userNameExist(String userName) {
Query query = em.createNamedQuery("getUserWithUsername");
query.setParameter("userName", userName);
List<User> existUser = query.getResultList();
if (existUser.size() > 0) {
return true;
}
return false;
}
To expand on dm03514 's answer - yes you should "sanitize" user input by using prepared statement objects in Java JDBC.
If you're using Spring then you should use spring-security. They have pretty much done this for you already and you just have to configure it.
Normally you would take your login and password and search for a user
String queryStr = "SELECT * FROM users WHERE login='"+sanitize(userLogin)+"' AND password='"+sanitize(userPass)"'";
This is not actual code just psuedo code. I do not know how java or spring handles sanitation but it is of utmost importance that you dont' trust anything input by the user when you are building a query string.
The idea is if this results in 1 user the user is valid, if it returns none the user is not valid!
Using paramaterized queries could be the best approach
Yes, please, post some code.
What exactly is the issue?
On the most basic level you should be able to:
pass the username and password as parameters in the HttpServletRequest object
Retrieve said parameters by "name" from the HSR object in the Controller.
Pass them to the SQL query for comparison against the database field.
Which of the above steps failed?

Categories