我无法为实体bean设置值。问题是,当我填充表单文件将上传但我需要文件路径存储在数据库中。在我的bean中,我使用了setter的employee实体来设置文件url但我认为代码足以设置数据库的文件路径,但数据存储在数据库中,而employeePicture为null ..
@Named
@RequestScoped
public class EmployeeAddController {
private Employees employees;
private String fileNameForDataBase;
private Part file;
@Inject
private EmployeeUpdateService updateService;
@PostConstruct
public void init() {
employees = new Employees();
}
public Employees getEmployees() {
return employees;
}
public void setEmployees(Employees employees) {
this.employees = employees;
}
public String getFileNameForDataBase() {
return fileNameForDataBase;
}
public void setFileNameForDataBase(String fileNameForDataBase) {
this.fileNameForDataBase = fileNameForDataBase;
}
public Part getFile() {
return file;
}
public void setFile(Part file) {
this.file = file;
}
public void upload() throws IOException {
ServletContext ctx = (ServletContext) FacesContext.getCurrentInstance()
.getExternalContext().getContext();
String realPath = ctx.getRealPath("/");
int random =(int) (Math.random() * 10000 + 1);
String fileString= realPath + File.separator + "resources/image/employee"+random+".jpg";
employees.setEmployeePicture(fileString);
try (InputStream input = file.getInputStream()) {
Files.copy(input, new File(fileString).toPath());
}
}
public String addEmployee() {
try {
this.updateService.add(employees);
return "index?faces-redirect=true";
} catch (Exception e) {
return null;
}
}
}
在我的jsf页面
"<div class="form-group">
<h:outputText value=" Employee Picture" class="col-sm-3 control-label"/>
<div class="col-sm-9">
<h:inputFile value="#{employeeAddController.file}">
<f:ajax listener="#{employeeAddController.upload()}"/>
</h:inputFile>
<h:outputText value="#{employeeAddController.fileNameForDataBase}"/>
</div>
<div>
<h:message for="fileUpload" class="text-primary"/>
</div>
</div>"***strong text***