Student editing does not work (Java + Spring + MySQl)? - java

I have a list of students. I want to do editing. Change the name, surname and avatar. I wrote the code, but it does not work, the data is not edited. You can see why it does not work for me. There is no error, it just does not change anything. After editing the name and surname and avatar do not change
Student Service
public interface StudentService {
List<Student> getAllStudents();
Student getStudentById(Long id);
boolean saveStudent(Student student);
boolean deleteStudentById(Long id);
File loadAvatarByFileName(String filename);
File saveAvatarImage(MultipartFile avatarImage) throws IOException;
Student updateStudent(String name, String surname, MultipartFile avatar, Student targetStudent) throws IOException;
}
Student Service Impl
#Service
#Transactional
public class StudentServiceImpl implements StudentService {
#Value("${storage.location}")
private String storageLocation;
private StudentRepository repository;
public StudentServiceImpl() {
}
#Autowired
public StudentServiceImpl(StudentRepository repository) {
super();
this.repository = repository;
}
#Override
public List<Student> getAllStudents() {
List<Student> list = new ArrayList<Student>();
repository.findAll().forEach(e -> list.add(e));
return list;
}
#Override
public Student getStudentById(Long id) {
Student student = repository.findById(id).get();
return student;
}
#Override
public boolean saveStudent(Student student) {
try {
repository.save(student);
return true;
} catch (Exception ex) {
return false;
}
}
#Override
public boolean deleteStudentById(Long id) {
try {
repository.deleteById(id);
return true;
} catch (Exception ex) {
return false;
}
}
#Override
public File loadAvatarByFileName(String filename) {
return new File(storageLocation + "/" + filename);
}
#Override
public File saveAvatarImage(MultipartFile avatarImage) throws IOException {
File newFile = File.createTempFile(
avatarImage.getName(),
"." + avatarImage.getOriginalFilename().split("\\.")[1],
new File(storageLocation));
avatarImage.transferTo(newFile);
return newFile;
}
#Override
public Student updateStudent(String name, String surname, MultipartFile avatar, Student targetStudent)
throws IOException {
if (name != null && !name.equals(targetStudent.getName())) {
targetStudent.setName(name);
}
if (surname != null && !surname.equals(targetStudent.getSurname())) {
targetStudent.setSurname(surname);
}
String oldAvatarName = targetStudent.getAvatar();
if (oldAvatarName != null) {
Files.deleteIfExists(Paths.get(storageLocation + File.separator + oldAvatarName));
}
File newAvatar = null;
if (avatar != null) {
newAvatar = saveAvatarImage(avatar);
assert newAvatar != null;
targetStudent.setAvatar(newAvatar.getName());
}
boolean isSaved = saveStudent(targetStudent);
if (!isSaved) {
throw new IOException();
}
Files.deleteIfExists(Paths.get(storageLocation + File.separator + oldAvatarName));
return targetStudent;
}
Student Controller
package adil.java.schoolmaven.controller;
import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletContext;
import adil.java.schoolmaven.entity.Student;
import adil.java.schoolmaven.service.StudentService;
import java.nio.file.FileSystemException;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
#Controller
public class StudentController {
#Autowired
private ServletContext servletContext;
// Constructor based Dependency Injection
private StudentService studentService;
public StudentController() {
}
#Autowired
public StudentController(StudentService studentService) {
this.studentService = studentService;
}
#RequestMapping(value = "/allStudents", method = {RequestMethod.GET, RequestMethod.POST})
public ModelAndView displayAllUser() {
System.out.println("User Page Requested : All Students");
ModelAndView mv = new ModelAndView();
List<Student> studentList = studentService.getAllStudents();
mv.addObject("studentList", studentList);
mv.setViewName("allStudents");
return mv;
}
#RequestMapping(value = "/addStudent", method = RequestMethod.GET)
public ModelAndView displayNewUserForm() {
ModelAndView mv = new ModelAndView("addStudent");
mv.addObject("headerMessage", "Add Student Details");
mv.addObject("student", new Student());
return mv;
}
#PostMapping(value = "/addStudent")
public String saveNewStudent(#RequestParam("name") #NonNull String name,
#RequestParam("surname") #NonNull String surname,
#RequestParam("avatar") MultipartFile file)
throws IOException {
Student student = new Student();
student.setSurname(surname);
student.setName(name);
if (file != null && !file.isEmpty()) {
student.setAvatar(studentService.saveAvatarImage(file).getName());
}
studentService.saveStudent(student);
return "redirect:/allStudents";
}
#GetMapping(value = "/editStudent/{id}")
public ModelAndView displayEditUserForm(#PathVariable Long id) {
ModelAndView mv = new ModelAndView("editStudent");
Student student = studentService.getStudentById(id);
mv.addObject("headerMessage", "Редактирование студента");
mv.addObject("student", student);
return mv;
}
#PostMapping(value = "/editStudent")
public String saveEditedUser(
#RequestParam("id") Long id,
#RequestParam("name") String name,
#RequestParam("surname") String surname,
#RequestParam("avatar") MultipartFile file) {
try {
studentService.updateStudent(name, surname, file, studentService.getStudentById(id));
} catch (FileSystemException ex) {
ex.printStackTrace();
} catch (IOException e) {
return "redirect:/error";
}
return "redirect:/allStudents";
}
#GetMapping(value = "/deleteStudent/{id}")
public ModelAndView deleteUserById(#PathVariable Long id) {
studentService.deleteStudentById(id);
ModelAndView mv = new ModelAndView("redirect:/allStudents");
return mv;
}
}
Edit Student JSP
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
<title>Home</title>
</head>
<body>
<center>
<h1>${headerMessage}</h1>
<form:form method="POST" action="${pageContext.request.contextPath}/editStudent" enctype="multipart/form-data">
<table>
<input type="hidden" value="${student.id}" name="id"/>
<tr>
<td><label path="Name">Name</label></td>
<td><input type="text" name="name" value="${student.name}"/></td>
</tr>
<tr>
<td><label path="Surname">Surname</label></td>
<td><input name="surname" value="${student.surname}"/></td>
</tr>
<tr>
<td><label path="Avatar">Avatar:</label></td>
<td>
<img src="${pageContext.request.contextPath}/avatar?avatar=${student.avatar}"
style="max-height: 200px; max-width: 200px;"/>
</td>
<td>
<input type="file" name="avatar"/>
</td>
</tr>
<tr>
<td><input class="btn btn-primary" type="submit" value="Save"></td>
</tr>
</table>
</form:form>
</center>
</body>
</html>
My Log
(the error message translates to "The process cannot access the file because the file is being used by another process." according to google translate)
java.nio.file.FileSystemException: C:\Pictures\avatar3435295369309803118.jpg: Процесс не может получить доступ к файлу, так как этот файл занят другим процессом.
at sun.nio.fs.WindowsException.translateToIOException(WindowsException.java:86)
at sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:97)
at sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:102)
at sun.nio.fs.WindowsFileSystemProvider.implDelete(WindowsFileSystemProvider.java:269)
at sun.nio.fs.AbstractFileSystemProvider.deleteIfExists(AbstractFileSystemProvider.java:108)
at java.nio.file.Files.deleteIfExists(Files.java:1165)
at adil.java.schoolmaven.service.StudentServiceImpl.updateStudent(StudentServiceImpl.java:122)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:338)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:197)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:294)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:98)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212)
at com.sun.proxy.$Proxy402.updateStudent(Unknown Source)
at adil.java.schoolmaven.controller.StudentController.saveEditedUser(StudentController.java:98)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:209)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:870)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:776)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:991)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:978)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:881)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:855)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.sitemesh.webapp.contentfilter.ContentBufferingFilter.bufferAndPostProcess(ContentBufferingFilter.java:169)
at org.sitemesh.webapp.contentfilter.ContentBufferingFilter.doFilter(ContentBufferingFilter.java:126)
Hibernate:
select

The error says that another process is using the file and therefore it cannot be deleted.
Do you have the given file open in another program?
Could it be that your code opens the file/keeps it open in another place while you are trying to delete it?
I see your StudentServiceImpl.updateStudent is calling Files.deleteIfExists(Paths.get(storageLocation + File.separator + oldAvatarName)); twice. According to the stack trace, the offending line is StudentServiceImpl.java:122. Which of the two lines is number 122 ?

Related

In Rest CRUD with OneToOne,when i am inserting data with form it working fine.But the problem comes with updating and deleting

--> when i am Updating it was not saving the entered details insted it was saving null. when deleting it throws error.
DataBase : restonetoone
application.properties
/*****************************/
crm.rest.url=http://localhost:8080/restonetoone/api/details
-->when i use to update it was taking null value insted of inserted data.
Details [id=25, city=null, mobileno=0, student=Student [id=25, name=null, clas=0]]
->when i was deleting it throws this error.
Mar 06, 2021 4:09:53 PM org.springframework.web.servlet.DispatcherServlet noHandlerFound
WARNING: No mapping for GET /restclient/student/delete
the Details.java class Onetoone with student.java class
Details.java
/******************/
package com.rest.entity;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
#Entity
#Table(name="details")
public class Details {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
private String city;
private long mobileno;
#OneToOne(cascade=CascadeType.ALL)
#JoinColumn(name="student_id")
private Student student;
public Details(){
}
public Details(int id, String city, long mobileno, Student student) {
super();
this.id = id;
this.city = city;
this.mobileno = mobileno;
this.student = student;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public long getMobileno() {
return mobileno;
}
public void setMobileno(long mobileno) {
this.mobileno = mobileno;
}
public Student getStudent() {
return student;
}
public void setStudent(Student student) {
this.student = student;
}
#Override
public String toString() {
return "Details [id=" + id + ", city=" + city + ", mobileno=" + mobileno + ", student=" + student + "]";
}
}
student.java class
Student.java
/******************/
package com.rest.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="student")
public class Student {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
private String name;
private int clas;
public Student() {
}
public Student(int id, String name, int clas) {
super();
this.id = id;
this.name = name;
this.clas = clas;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getClas() {
return clas;
}
public void setClas(int clas) {
this.clas = clas;
}
#Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", clas=" + clas + "]";
}
}
DetailsServImpl.java class(service layers)
DetailsServImpl.java
/******************/
package com.rest.service;
import java.util.List;
import java.util.logging.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import com.rest.entity.Details;
#Service
public class DetailsServImpl implements DetailsServ {
private RestTemplate restTemplate;
private String crmRestUrl;
private Logger logger = Logger.getLogger(getClass().getName());
#Autowired
public DetailsServImpl(RestTemplate theRestTemplate,
#Value("${crm.rest.url}") String theUrl) {
restTemplate = theRestTemplate;
crmRestUrl = theUrl;
logger.info("Loaded property: crm.rest.url=" + crmRestUrl);
}
#Override
public List<Details> getDetails() {
logger.info("in getDetails(): Calling REST API " + crmRestUrl);
// make REST call
ResponseEntity<List<Details>> responseEntity =
restTemplate.exchange(crmRestUrl, HttpMethod.GET, null,
new ParameterizedTypeReference<List<Details>>() {});
// get the list of customers from response
List<Details> theDetails = responseEntity.getBody();
logger.info("in getDetails(): details" + theDetails);
return theDetails;
}
#Override
public Details getDetails(int theId) {
logger.info("in getDetails(): Calling REST API " + crmRestUrl);
// make REST call
Details theDetails =
restTemplate.getForObject(crmRestUrl + "/" + theId,
Details.class);
logger.info("in saveDetails(): theDetails=" + theDetails);
return theDetails;
}
#Override
public void saveDetails(Details theDetails) {
logger.info("in saveSt(): Cudentalling REST API " + crmRestUrl);
int detailsId = theDetails.getId();
// make REST call
if (detailsId == 0) {
// add employee
restTemplate.postForEntity(crmRestUrl, theDetails, String.class);
} else {
// update employee
restTemplate.put(crmRestUrl, theDetails);
}
logger.info("in saveDetails(): success");
}
#Override
public void deleteDetails(int theId) {
logger.info("in deleteDetails(): Calling REST API " + crmRestUrl);
// make REST call
restTemplate.delete(crmRestUrl + "/" + theId);
logger.info("in deleteDetails(): deleted Details theId=" + theId);
}
}
StudentServImpl.java class
StudentServImpl.java
/******************/
package com.rest.service;
import java.util.List;
import java.util.logging.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import com.rest.entity.Details;
import com.rest.entity.Student;
#Service
public class StudentServImpl implements StudentServ {
private RestTemplate restTemplate;
private String crmRestUrl;
private Logger logger = Logger.getLogger(getClass().getName());
#Autowired
public StudentServImpl(RestTemplate theRestTemplate,#Value("${crm.rest.url}") String theUrl){
restTemplate = theRestTemplate;
crmRestUrl = theUrl;
logger.info("Loaded property: crm.rest.url=" + crmRestUrl);
}
#Override
public List<Student> getStudent() {
logger.info("in getCustomers(): Calling REST API " + crmRestUrl);
// make REST call
ResponseEntity<List<Student>> responseEntity =
restTemplate.exchange(crmRestUrl, HttpMethod.GET, null,
new ParameterizedTypeReference<List<Student>>() {});
// get the list of customers from response
List<Student> theStudent = responseEntity.getBody();
logger.info("in getCustomers(): customers" + theStudent);
return theStudent;
}
#Override
public void saveStudent(Student theStudent) {
logger.info("in saveSt(): Cudentalling REST API " + crmRestUrl);
int studentId = theStudent.getId();
// make REST call
if (studentId == 0) {
// add employee
restTemplate.postForEntity(crmRestUrl, theStudent, String.class);
} else {
// update employee
restTemplate.put(crmRestUrl, theStudent);
}
logger.info("in saveStudent(): success");
}
#Override
public Student getStudent(int theId) {
logger.info("in getCustomer(): Calling REST API " + crmRestUrl);
// make REST call
Student theStudent =
restTemplate.getForObject(crmRestUrl + "/" + theId,
Student.class);
logger.info("in saveCustomer(): theCustomer=" + theStudent);
return theStudent;
}
#Override
public void deleteStudent(int theId) {
logger.info("in deleteStudent(): Calling REST API " + crmRestUrl);
// make REST call
restTemplate.delete(crmRestUrl + "/" + theId);
logger.info("in deleteStudent(): deleted Student theId=" + theId);
}
}
Now the controller class(here i am using single controller for multiple entites).
ClientController.java
/******************/
package com.rest.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.rest.entity.Details;
import com.rest.entity.Student;
import com.rest.service.DetailsServ;
import com.rest.service.StudentServ;
#Controller
#RequestMapping("/cont")
public class ClientController {
#Autowired
private DetailsServ detailsServ;
#Autowired
private StudentServ studentServ;
#GetMapping("/showForm")
public String showForm(Model theModel){
Details theDetails = new Details();
Student theStudent = new Student();
theDetails.setStudent(theStudent);
theModel.addAttribute("for",theDetails);
return "the-for";
}
#PostMapping("/saveForm")
private String saveForm(#ModelAttribute("for") Details theDetails) {
detailsServ.saveDetails(theDetails);
return "redirect:/cont/list";
}
#GetMapping("/list")
public String showList(Model theModel) {
List<Details> theDetails = detailsServ.getDetails();
theModel.addAttribute("details", theDetails);
return "list-table";
}
#GetMapping("/update")
public String updateDetails(#RequestParam("detailsId") int theId, Model theModel) {
Details theDetails =detailsServ.getDetails(theId);
theModel.addAttribute("for",theDetails);
return "the-for";
}
#GetMapping("/delete")
public String deleteDetails(#RequestParam("detailsId") int theId) {
detailsServ.deleteDetails(theId);
return "redirect:/cont/list";
}
}
I use this form for both saving and updating.
the-for.jsp
/******************/
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%# page import="java.sql.*"%>
<!DOCTYPE html>
<html>
<head>
<title>Save Customer</title>
<link type="text/css"
rel="stylesheet"
href="${pageContext.request.contextPath}/resources/css/style.css">
<link type="text/css"
rel="stylesheet"
href="${pageContext.request.contextPath}/resources/css/add-customer-style.css">
</head>
<body>
<div id="wrapper">
<div id="header">
<h2>Form</h2>
</div>
</div>
<div id="container">
<h3>Save StudentDetails</h3>
<form:form action="saveForm" modelAttribute="for" method="POST">
<!-- need to associate this data with customer id -->
<form:hidden path="id" />
<table>
<tbody>
<tr>
<td><label>City name:</label></td>
<td><form:input path="city" /></td>
</tr>
<tr>
<td><label>mobileno:</label></td>
<td><form:input path="mobileno" /></td>
</tr>
<tr>
<td><label>name:</label></td>
<td><form:input path="student.name" /></td>
</tr>
<tr>
<td><label>class:</label></td>
<td><form:input path="student.clas" /></td>
</tr>
<tr>
<td><label></label></td>
<td><input type="submit" value="Save" class="save" /></td>
</tr>
</tbody>
</table>
</form:form>
<div style="clear; both;"></div>
<p>
Back to List
</p>
</div>
</body>
</html>
Now the table which shows the CRUD dynamically.
list-table.jsp
/******************/
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# page import = "java.sql.*" %>
<!DOCTYPE html>
<html>
<head>
<title>List</title>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap CSS -->
<link
href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1"
crossorigin="anonymous">
</head>
<body>
<div class="container">
<h2 class="pt-2">Student Manager</h2>
<!-- put new button: Add Student -->
<input type="button" value="Add Student"
onclick="window.location.href='showForm'; return false;"
class="btn btn-primary btn-sm mb-3" />
<!-- add our html table here -->
<table class="table table-bordered table-striped">
<thead class="table-dark">
<tr>
<th>city</th>
<th>mobileno</th>
<th>name</th>
<th>class</th>
<th>Action</th>
</tr>
</thead>
<!-- loop over and print our students -->
<tbody>
<c:forEach var="tempDetails" items="${details}">
<!-- construct an "update" link with student id -->
<c:url var="updateLink" value="/cont/update">
<c:param name="detailsId" value="${tempDetails.id}" />
</c:url>
<!-- construct an "delete" link with student id -->
<c:url var="deleteLink" value="/student/delete">
<c:param name="studentId" value="${tempStudent.id}" />
</c:url>
<tr>
<td>${tempDetails.city}</td>
<td>${tempDetails.mobileno}</td>
<td>${tempDetails.student.name}</td>
<td>${tempDetails.student.clas}</td>
<td>
<!-- display the update link -->
Update
|
<a href="${deleteLink}"
onclick="if (!(confirm('Are you sure you want to delete this student?'))) return false">Delete</a>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</body>
</html>
For more clearity sake i am shering the link of my project which include Both client side and backend code files with database.
LINK( https://drive.google.com/file/d/128pvCd6bYdCNhOiG6ERRXbPRUlnhZlTp/view?usp=sharing )

Problems with Glassfish5 and servlet

I'm relatively new to Java. Tried my first web application with server Tomcat, which went rather well. However, with another server Glassfish, problems arouse. After application deployment jsp doesn't connect to servlet, therefore error 404 appears. I added project structure and several classes. Any help appreciated.
empBean:
package app.bean;
import app.entity.Emp;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import java.util.List;
#Stateless
public class EmpBean {
#PersistenceContext(unitName = "DEVMODE")
private EntityManager em;
public Emp add(Emp emp) {
return em.merge(emp);
}
public Emp get(Integer empno) {
return em.find(Emp.class, empno);
}
public void update(Emp emp) {
add(emp);
}
public void delete(long empno){
em.remove(get((int) empno));
}
public List<Emp> getAll(){
TypedQuery<Emp> namedQuery = em.createNamedQuery("Emp.getAll", Emp.class);
return namedQuery.getResultList();
}
}
Emp:
package app.entity;
import javax.persistence.*;
import java.sql.Date;
#Entity(name="emp")
#NamedQuery(name = "Emp.getAll", query = "SELECT e from emp e")
public class Emp {
#Id
#Column(name="empno")
private Integer empno ;
#Column(name="ename")
private String ename;
#Column(name="job")
private String job;
#Column(name="mgr")
private Integer mgr;
#Column(name="hiredate")
private Date hiredate;
#Column(name="sal")
private Integer sal;
#Column(name="comm")
private Integer comm;
#Column(name="deptno")
private Integer deptno;
public Emp(Integer empno, String ename, String job, Integer mgr, Date hiredate, Integer sal, Integer comm, Integer deptno, String id) {
this.empno = empno;
this.ename = ename;
this.job = job;
this.mgr = mgr;
this.hiredate = hiredate;
this.sal = sal;
this.comm = comm;
this.deptno = deptno;
}
public Emp() {
}
public Integer getEmpno() {
return empno;
}
public void setEmpno(Integer empno) {
this.empno = empno;
}
public String getEname() {
return ename;
}
public void setEname(String ename) {
this.ename = ename;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
public Integer getMgr() {
return mgr;
}
public void setMgr(Integer mgr) {
this.mgr = mgr;
}
public Date getHiredate() {
return hiredate;
}
public void setHiredate(Date hiredate) {
this.hiredate = hiredate;
}
public Integer getSal() {
return sal;
}
public void setSal(Integer sal) {
this.sal = sal;
}
public Integer getComm() {
return comm;
}
public void setComm(Integer comm) {
this.comm = comm;
}
public Integer getDeptno() {
return deptno;
}
public void setDeptno(Integer deptno) {
this.deptno = deptno;
}
}
Select1Servlet:
package app.servlets;
import app.bean.DeptBean;
import app.bean.EmpBean;
import app.bean.SalgradeBean;
import app.entity.Dept;
import app.entity.Emp;
import app.entity.Salgrade;
import javax.ejb.EJB;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.io.PrintWriter;
import java.sql.*;
import java.util.ArrayList;
#WebServlet("/search")
public class Select1Servlet extends HttpServlet {
#EJB
private EmpBean empBean;
private DeptBean deptBean;
private SalgradeBean salgradeBean;
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html");
req.setCharacterEncoding("UTF-8");
req.getRequestDispatcher("/searchview.jsp").forward(req, resp);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException {
// response.setContentType("text/html");
PrintWriter out = response.getWriter();
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/users";
String userName = "root";
String password = "7777";
Statement st;
try {
// Class.forName("com.mysql.jdbc.Driver");
// conn = DriverManager.getConnection(url , userName, password);
System.out.println("Connected!");
String numb = request.getParameter("numb");
ArrayList al = null;
ArrayList pid_list = new ArrayList();
// String query = "SELECT emp.ename, emp.job, emp.sal, dept.dname, salgrade.grade FROM dept,emp,salgrade WHERE (emp.empno = '" + numb + "' ) AND (emp.deptno = dept.deptno) and (emp.sal BETWEEN losal and hisal) ";
// System.out.println("query " + query);
st = conn.createStatement();
// ResultSet rs = st.executeQuery(query);
Emp emp = empBean.get(Integer.valueOf(numb));
String ename= emp.getEname();
String job = emp.getJob();
Integer sal = emp.getSal();
Integer deptnoEmp= emp.getDeptno();
Dept dept = deptBean.get(Integer.valueOf(deptnoEmp));
String dname = dept.getDname();
Salgrade salgrade = salgradeBean.get(sal);
Integer grade = salgrade.getGrade();
// while (rs.next()) {
al = new ArrayList();
// out.println(rs.getString(1));
// out.println(rs.getString(2));
// out.println(rs.getString(3));
// out.println(rs.getString(4));
al.add(ename);
al.add(job);
al.add(sal);
al.add(dname);
al.add(grade);
System.out.println("al :: " + al);
pid_list.add(al);
// }
request.setAttribute("piList", pid_list);
RequestDispatcher view = request.getRequestDispatcher("/searchview.jsp");
view.forward(request, response);
conn.close();
System.out.println("Disconnected!");
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Returns a short description of the servlet.
* #return a String containing servlet description
*/
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
select1.jsp:
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title> Enter the number </title>
<link rel="stylesheet" href="design/w3.css">
</head>
<body>
<br/><br/>
<form method="post" name="frm" action="search">
<table border="0" width="375" align="center" class = "w3-pink w3-text-white" >
<tr><td colspan=2 style="font-size:12pt;" align="center">
<h3>Search User</h3></td></tr>
<br/>
<tr><td ><b>User Number</b></td>
<td>: <input type="number" name="numb" id="numb">
</td></tr>
<tr><td colspan=2 align="center">
<br/>
<input type="submit" name="submit" value="Search" onclick="form.action='/search';"></td></tr>
</table>
</form>
</body>
</html>
searchview.jsp:
<%# page import="java.util.*" %>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%--<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>--%>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title> List of emp </title>
<link rel="stylesheet" href="design/w3.css">
</head>
<body>
<form method="get" name="frm" action="searchview">
<table width="700px"
class = "w3-text-pink">
<tr>
<td colspan=5 align="center"
class = "w3-black w3-text-pink">
<b>User Record</b></td>
</tr>
<tr class = "w3-black ">
<td><b>User Name</b></td>
<td><b>Job</b></td>
<td><b>Sal</b></td>
<td><b>Dname</b></td>
<td><b>Grade</b></td>
</tr>
<%
int count = 0;
String color = "#ffffff";
if (request.getAttribute("piList") != null) {
ArrayList al = (ArrayList) request.getAttribute("piList");
System.out.println(al);
Iterator itr = al.iterator();
while (itr.hasNext()) {
if ((count % 2) == 0) {
color = "#ffffff";
}
count++;
ArrayList pList = (ArrayList) itr.next();
%>
<tr style="background-color:<%=color%>;">
<td><%=pList.get(0)%></td>
<td><%=pList.get(1)%></td>
<td><%=pList.get(2)%></td>
<td><%=pList.get(3)%></td>
<td><%=pList.get(4)%></td>
</tr>
<%
}
}
if (count == 0) {
%>
<tr>
<td colspan=5 align="center"
style="background-color:#ffffff"><b>No Record Found..</b></td>
</tr>
<% }
%>
</table>
</form>
</body>
</html>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<servlet>
<servlet-name>Select1</servlet-name>
<servlet-class>app.servlets.Select1Servlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Select1</servlet-name>
<url-pattern>/search</url-pattern>
</servlet-mapping>

Spring MVC wrong entity id after an attempt to update it

I try to write simple Spring MVC CRUD webapp and I got a problem updating my rows. I have a table with some users and I can edit any of them clicking "Edit" button in the table (look at the picture). Then I can change its fields in a form, but when I click "Edit" under the form, the id of user entity, that is conveyed to the addUser() method, is 0, though, when I got the entity from db, it wasn't. Also "createdDate" field becomes null. I can't find out the reason of it, so I need some help... This is my code and the picture with my app:
The picture
user.jsp
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib uri="http://www.springframework.org/tags" prefix="spring" %>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%#page isELIgnored="false" %>
<%# page session="false" %>
<html>
<head>
<title>Users</title>
<style type="text/css">
.tg {border-collapse:collapse;border-spacing:0;border-color:#ccc;}
.tg td{font-family:Arial, sans-serif;font-size:14px;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:#ccc;color:#333;background-color:#fff;}
.tg th{font-family:Arial, sans-serif;font-size:14px;font-weight:normal;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:#ccc;color:#333;background-color:#f0f0f0;}
.tg .tg-4eph{background-color:#f9f9f9}
</style>
</head>
<body>
<h1>
Add a user
</h1>
<c:url var="addAction" value="/user/add" />
<form:form action="${addAction}" commandName="user">
<table>
<c:if test="${!empty user.name}">
<tr>
<td>
<form:label path="id">
<spring:message text="ID"/>
</form:label>
</td>
<td>
<form:input path="id" readonly="true" size="8" disabled="true" />
</td>
</tr>
</c:if>
<tr>
<td>
<form:label path="name">
<spring:message text="Name"/>
</form:label>
</td>
<td>
<form:input path="name" />
</td>
</tr>
<tr>
<td>
<form:label path="age">
<spring:message text="Age"/>
</form:label>
</td>
<td>
<form:input path="age" />
</td>
</tr>
<tr>
<td>
<form:label path="isAdmin">
<spring:message text="Is admin"/>
</form:label>
</td>
<td>
<form:input path="isAdmin"/>
</td>
</tr>
<tr>
<td colspan="2">
<c:if test="${!empty user.name}">
<input type="submit"
value="<spring:message text="Edit"/>" />
</c:if>
<c:if test="${empty user.name}">
<input type="submit"
value="<spring:message text="Add"/>" />
</c:if>
</td>
</tr>
</table>
</form:form>
<br>
<h3>Users list</h3>
<table class="tg">
<tr>
<th width="80">ID</th>
<th width="120">Name</th>
<th width="120">Age</th>
<th width="60">IsAdmin</th>
<th width="120">Created date</th>
<th width="60">Edit</th>
<th width="60">Delete</th>
</tr>
<c:forEach items="${users}" var="user">
<tr>
<td>${user.id}</td>
<td>${user.name}</td>
<td>${user.age}</td>
<td>${user.isAdmin}</td>
<td>${user.createdDate}</td>
<td><a href="<c:url value='/edit/${user.id}' />" >Edit</a></td>
<td><a href="<c:url value='/remove/${user.id}' />" >Delete</a></td>
</tr>
</c:forEach>
</table>
</body>
</html>
UserController
package com.mihusle;
import com.mihusle.model.User;
import com.mihusle.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* Created by MHSL on 16.06.2017.
*/
#Controller
public class UserController {
private UserService userService;
#Autowired
#Qualifier("userService")
public void setUserService(UserService userService) {
this.userService = userService;
}
#RequestMapping(value = "/users", method = RequestMethod.GET)
public String showUsersList(Model model) {
model.addAttribute("user", new User());
model.addAttribute("users", userService.getUsers());
return "user";
}
#RequestMapping(value = "/user/add", method = RequestMethod.POST)
public String addUser(#ModelAttribute("user") User user) {
if (user.getId() == 0) {
userService.addUser(user);
} else {
userService.updateUser(user);
}
return "redirect:/users";
}
#RequestMapping("/remove/{id}")
public String removeUser(#PathVariable("id") int id) {
userService.removeUser(id);
return "redirect:/users";
}
#RequestMapping("/edit/{id}")
public String editUser(#PathVariable("id") int id, Model model) {
model.addAttribute("user", userService.getUserById(id));
model.addAttribute("users", userService.getUsers());
return "user";
}
}
UserDAOImpl
package com.mihusle.dao;
import com.mihusle.model.User;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.List;
/**
* Created by MHSL on 16.06.2017.
*/
#Repository
public class UserDAOImpl implements UserDAO {
private static final Logger LOGGER = LoggerFactory.getLogger(UserDAOImpl.class);
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
#Override
public void addUser(User user) {
Session session = sessionFactory.getCurrentSession();
Calendar calendar = Calendar.getInstance();
Timestamp currentTime = new Timestamp(calendar.getTimeInMillis());
user.setCreatedDate(currentTime);
session.persist(user);
LOGGER.info(user + " was added successfully");
}
#Override
public void updateUser(User user) {
Session session = sessionFactory.getCurrentSession();
session.update(user);
LOGGER.info(user + " was updated successfully");
}
#SuppressWarnings("unchecked")
#Override
public List<User> getUsers() {
Session session = sessionFactory.getCurrentSession();
List<User> users = session.createQuery("FROM User").list();
users.forEach(user -> LOGGER.info(user + " is in the list"));
return users;
}
#Override
public User getUserById(int id) {
Session session = sessionFactory.getCurrentSession();
User user = session.load(User.class, id);
LOGGER.info(user + " was loaded successfully");
return user;
}
#Override
public void removeUser(int id) {
Session session = sessionFactory.getCurrentSession();
User user = session.load(User.class, id);
if (user != null)
session.delete(user);
LOGGER.info(user + " was deleted successfully");
}
}
User
package com.mihusle.model;
import javax.persistence.*;
import java.sql.Timestamp;
import java.util.Objects;
/**
* Created by MHSL on 16.06.2017.
*/
#Entity
#Table(name = "user", schema = "test")
public class User {
private int id;
private String name;
private Integer age;
private Boolean isAdmin;
private Timestamp createdDate;
#Id
#Column(name = "id", nullable = false)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Basic
#Column(name = "name", nullable = true, length = 25)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Basic
#Column(name = "age", nullable = true)
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
#Basic
#Column(name = "isAdmin", nullable = true, columnDefinition = "BIT", length = 1)
public Boolean getIsAdmin() {
return isAdmin;
}
#Column(name = "isAdmin", columnDefinition = "BIT", length = 1)
public void setIsAdmin(Boolean admin) {
isAdmin = admin;
}
#Basic
#Column(name = "createdDate", nullable = true)
public Timestamp getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Timestamp createdDate) {
this.createdDate = createdDate;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User that = (User) o;
return id == that.id &&
Objects.equals(name, that.name) &&
Objects.equals(age, that.age) &&
Objects.equals(createdDate, that.createdDate);
}
#Override
public int hashCode() {
return Objects.hash(id, name, age, createdDate);
}
#Override
public String toString() {
return "User{" +
"id = " + id +
", name = '" + name + '\'' +
", age = " + age +
", isAdmin = " + isAdmin +
", createdDate = " + createdDate +
'}';
}
}
I have no idea where the problem may be, so if you need more code, I'm ready to write it. Thanks
I solved this. I had to add <form:hidden path="id" /> to the id input field. I suppose I need to do the same with createdDate field.

In eclipse java-ee curd program update is not working

## i am now coading on eclipse java-ee , in curd mvc program i have generated four methods all are working except update method while compiling i can able to read data but when i am updateing i got error 400 ,i have given my controller and dao classes ##
## my controller ##
----------
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.``ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import java.util.List;
import dao.UserDaoImpl;
import model.User;
#Controller
public class Firstcontroller {
#Autowired
UserDaoImpl userDao;
#RequestMapping(value="/add")
public ModelAndView redirectUser()
{
ModelAndView m=new ModelAndView("add");
return m;
}
#RequestMapping(value="/table")
public ModelAndView viewUser()
{
List<User> list=userDao.viewUsers();
return new ModelAndView("All_User","list",list);
}
#RequestMapping(value="/register",method=RequestMethod.POST)
public ModelAndView processSaveUser(#ModelAttribute User user)
{
if(userDao.saveUser(user))
{
ModelAndView m=new ModelAndView("login","response","Successfully Registered");
return m;
}
ModelAndView m1=new ModelAndView("signup","response","Failed Registeration");
return m1;
}
#RequestMapping(value="deleteuser/{id}" ,method = RequestMethod.GET)
public ModelAndView deleteuser(#PathVariable int id)
{
userDao.delete(id);
return new ModelAndView("redirect:/table");
}
#RequestMapping(value="/edituser/{id}")
public ModelAndView edit(#PathVariable int id){
User user=userDao.getUserById(id);
return new ModelAndView("edituser","command",user);
}
#RequestMapping(value="/save",method = RequestMethod.POST)
public ModelAndView edituser(#PathVariable String id){
System.out.println("Got In");
//userDao.update(user);
return new ModelAndView("redirect:/table");
}
}
and my dao is
package dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import handler.UserRowMapper;
import model.User;
public class UserDaoImpl implements UserDao {
private JdbcTemplate jdbcTemp;
public void setJdbcTemp(JdbcTemplate jdbcTemp) {
this.jdbcTemp = jdbcTemp;
}
public boolean saveUser(User user) {
String sql_query="INSERT INTO userdata (username,password) VALUES (?,?)";
int x=jdbcTemp.update(sql_query,user.getLunm(),user.getLpwd());
if(x>0)
{
return true;
}
return false;
}
public List<User>viewUsers()
{
return jdbcTemp.query("select * from userdata",new RowMapper<User>()
{
public User mapRow(ResultSet rs,int row)throws SQLException
{
User u=new User();
u.setId(rs.getInt(1));
u.setLunm(rs.getString(2));
u.setLpwd(rs.getString(3));
return u;
}
}
);
}
public User getUserById(int id)
{
String sql="select * from userdata where id=?";
return (User)jdbcTemp.queryForObject(sql,new Object[]{id},new UserRowMapper());
}
public int delete(int id)
{
String sql="delete from userdata where id=?";
int x=jdbcTemp.update(sql,id);
if(x>0)
{
return(x);
}
return (0);
}
public int update(User user)
{
String sql="update userdetails set username=? and password=? where id=?";
return jdbcTemp.update(sql,user.getLunm(),user.getLpwd(),user.getId());
}
}
EditUser.jsp
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# page isELIgnored="false" %>
<h1>Edit User</h1>
<h1>${command.id }</h1>
<form:form method="POST" action="save?id=${command.id }">
<table >
<tr>
<td></td>
<td><form:hidden path="id" /></td>
</tr>
<tr>
<td>Username : </td>
<td><form:input path="lunm" /></td>
</tr>
<tr>
<td>password :</td>
<td><form:input path="lpwd" /></td>
<tr>
<td> </td>
<td><input type="submit" value="Edit" /></td>
</tr>
</table>
</form:form> [ this is my error msg][1]
getting the values from table
#RequestMapping(value="/save",method = RequestMethod.POST)
public ModelAndView edituser(#PathVariable String id){
System.out.println("Got In");
//userDao.update(user);
return new ModelAndView("redirect:/table");
}
if above code is for Store updated username and password means change #PathVariable into #ModelAttribute User user
for Example:
#RequestMapping(value="edituser/save",method = RequestMethod.POST)
//#RequestMapping(value="/save",method=RequestMethod.PUT)
public ModelAndView edituser(#ModelAttribute User user){
System.out.println("Got In");
userDao.update(user);
return new ModelAndView("redirect:/table");
}
different table names are there
public int delete(int id)
{
String sql="delete from userdata where id=?";
int x=jdbcTemp.update(sql,id);
if(x>0)
{
return(x);
}
return (0);
}
public int update(User user)
{
String sql="update userdata set username=?,password=? where id=?";
return jdbcTemp.update(sql,user.getLunm(),user.getLpwd(),user.getId());
}

How to upload file in spring?

I am not able to get the file name in spring controller
<form:form method="post" modelAttribute="sampleDetails"
enctype="multipart/form-data">
<input type="file" name="uploadedFileName" id="fileToUpload" required="" >
<input type="submit" name="import_file" value="Import File" id="" />
</form:form>
Its my post method in controller
#RequestMapping(method = RequestMethod.POST)
public String importQuestion(#Valid #RequestParam("uploadedFileName")
MultipartFile multipart, #ModelAttribute("sampleDetails") SampleDocumentPojo sampleDocument, BindingResult result, ModelMap model) {
logger.debug("Post method of uploaded Questions ");
logger.debug("Uploaded file Name : " + multipart.getName());
return "importQuestion";
}
After submit get the warning message.
warning [http-nio-8080-exec-9] WARN
org.springframework.web.servlet.PageNotFound - Request method 'POST' not
supported
[http-nio-8080-exec-9] WARN
org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver
- Handler execution resulted in exception: Request method 'POST' not
supported
You can also use MutlipartFile in order to upload file as follow.
#RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
#ResponseBody
public String uploadFile(#RequestParam("file") MultipartFile file) {
try {
String uploadDir = "/uploads/";
String realPath = request.getServletContext().getRealPath(uploadDir);
File transferFile = new File(realPath + "/" + file.getOriginalFilename());
file.transferTo(transferFile);
} catch (Exception e) {
e.printStackTrace();
return "Failure";
}
return "Success";
}
You don't need to use spring form for file upload, you can do it with plain HTML
<html>
<body>
<h2>Spring MVC file upload using Annotation configuration Metadata</h2>
Upload File :
<form name="fileUpload" method="POST" action="uploadFile" enctype="multipart/form-data">
<label>Select File</label> <br />
<input type="file" name="file" />
<input type="submit" name="submit" value="Upload" />
</form>
</body>
</html>
You need to configure MultipartResolver object in yours application configuration as follow
#Bean(name="multipartResolver")
public CommonsMultipartResolver multipartResolver() {
CommonsMultipartResolver multi = new CommonsMultipartResolver();
multi.setMaxUploadSize(100000);
return multi;
}
You can follow complete tutorial on how to upload file in Spring Framework Upload File in Spring MVC framework
in your controller you need to specify that you are expecting mutlipart
using
consumes = {"multipart/form-data"}
and to ge the file name using getOriginalFileName()
#RequestMapping(method = RequestMethod.POST, consumes = {"multipart/form-data"})
public String importQuestion(#Valid #RequestParam("uploadedFileName")
MultipartFile multipart, BindingResult result, ModelMap model) {
logger.debug("Post method of uploaded Questions ");
logger.debug("Uploaded file Name : " + multipart.getOriginalFilename());
return "importQuestion";
}
Also in your html the name of your input of type file should be the same as the RequestParam "uploadedFileName"
<input type="file" name="uploadFileName" id="fileToUpload" required="" >
change it to
<input type="file" name="uploadedFileName" id="fileToUpload" required="" >
I think you form is not handled by the method importQuestion,you can remove method = RequestMethod.POST to make sure it.
your model name not reference to MultipartFile
can have cross reference in yours mappings
try this:
<form:form method="post" action="testcontrol" enctype="multipart/form-data">
<input type="file" name="uploadedFileName" id="fileToUpload" required="" >
<input type="submit" name="import_file" value="Import File" id="" />
and set in your controller
#RequestMapping(method = RequestMethod.POST,path="/testcontrol")
public String importQuestion(#RequestParam("uploadedFileName")
MultipartFile multipart, BindingResult result, ModelMap model) {
logger.debug("Post method of uploaded Questions ");
logger.debug("Uploaded file Name : " + multipart.getName());
return "importQuestion";
}
package com.form.demo.Controll;
import com.form.demo.Repo.CustoRepo;
import com.form.demo.Serv.CustoSevice;
import com.form.demo.model.Customer;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.validation.Valid;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
#Controller
#RequestMapping("/")
public class SimpleWebController {
private CustoSevice custoSevice;
public SimpleWebController(CustoSevice custoSevice) {
this.custoSevice = custoSevice;
}
public static String uploadDirectory = System.getProperty("user.dir")+"/uploads";
#RequestMapping(value={"/","/form"}, method=RequestMethod.GET)
public String customerForm(Model model) {
model.addAttribute("customer", new Customer());
return "form";
}
#RequestMapping(value="/form", method=RequestMethod.POST)
public String customerSubmit(#ModelAttribute Customer customer,Model model,#RequestParam("files") MultipartFile[] files) {
StringBuilder fileNames = new StringBuilder();
String path1 = "";
for (MultipartFile file : files) {
Path fileNameAndPath = Paths.get(uploadDirectory, file.getOriginalFilename());
fileNames.append(file.getOriginalFilename()+" ");
try {
Files.write(fileNameAndPath, file.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
path1=fileNameAndPath.toString();
}
customer.setImage(path1);
model.addAttribute("customer", customer);
custoSevice.save(customer);
return "result";
}
#RequestMapping(value = "/vewall")
public String vew(Model model){
List<Customer>customers=custoSevice.findAll();
model.addAttribute("cus",customers);
return "vewall";
}
#RequestMapping(value={"/","/update/{id}"}, method=RequestMethod.GET)
public String showUpdateForm(#PathVariable("id") long id, Model model) {
Customer customer = custoSevice.findById(id);
model.addAttribute("user", customer);
return "update";
}
#RequestMapping(value={"/","/update/{id}"}, method=RequestMethod.POST)
public String updateUser(#Valid Customer customer,Model model) {
custoSevice.save(customer);
model.addAttribute("cus", custoSevice.findAll());
return "vewall";
}
#RequestMapping(value = "/delete/{id}",method = RequestMethod.GET)
public String deleteUser(#PathVariable("id") long id, Model model) {
Customer customer = custoSevice.findById(id);
custoSevice.delete(customer);
model.addAttribute("cus", custoSevice.findAll());
return "vewall";
}
}
package com.form.demo.model;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Objects;
#Entity
#Table(name = "cust4")
public class Customer implements Serializable {
#Id
// #GeneratedValue(strategy = GenerationType.AUTO)
private long id;
#Column(name = "firstname")
private String firstname;
#Column(name = "lastname")
private String lastname;
#Column(name = "image")
private String image;
public Customer() {
this.id = id;
this.firstname = firstname;
this.lastname = lastname;
this.image = image;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Customer customer = (Customer) o;
return id == customer.id &&
Objects.equals(firstname, customer.firstname) &&
Objects.equals(lastname, customer.lastname) &&
Objects.equals(image, customer.image);
}
#Override
public int hashCode() {
return Objects.hash(id, firstname, lastname, image);
}
#Override
public String toString() {
return "Customer{" +
"id=" + id +
", firstname='" + firstname + '\'' +
", lastname='" + lastname + '\'' +
", image='" + image + '\'' +
'}';
}
}
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<meta>
<meta charset="UTF-8"></meta>
<title>Title</title>
</head>
<body>
<h1>Customer Form</h1>
<form action="#" th:action="#{/form}" th:object="${customer}" method="post" enctype="multipart/form-data">
<p>First Name: <input type="text" th:field="*{firstname}" /></p>
<p>Last Name: <input type="text" th:field="*{lastname}" /></p>
<p>Image: <input type="file" name="files" multiple></p>
<p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p>
<br>
Viewall
</form>
</body>
</html>
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>Title</title>
</head>
<body>
<h2>List of cities</h2>
<table>
<tr>
<th>ID</th>
<th>FName</th>
<th>LName</th>
<th>Path</th>
<th>Edit</th>
<th>Delete</th>
</tr>
<tr th:each="city : ${cus}">
<td th:text="${city.id}">Id</td>
<td th:text="${city.firstname}">Name</td>
<td th:text="${city.lastname}">Population</td>
<td th:text="${city.image}">Path </td>
<td><a th:href="#{/update/{id}(id=${city.id})}">Edit</a></td>
<td><a th:href="#{/delete/{id}(id=${city.id})}">Delete</a></td>
</tr>
</table>
</body>
</html>
spring.datasource.url=jdbc:mysql://localhost:3306/new1
spring.datasource.username=root
spring.datasource.password=root
spring.servlet.multipart.max-file-size=15MB
spring.servlet.multipart.max-request-size=15MB
//
package com.example.demo;
import java.io.File;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import controller.FileUploadController;
#Configuration
#EnableAutoConfiguration
#ComponentScan({"demo","controller"})
public class FileUploadApplication {
public static void main(String[] args) {
new File(FileUploadController.uploadDirectory).mkdir();
SpringApplication.run(FileUploadApplication.class, args);
}
}

Categories

Resources