Spring 5 Validator - java

I have User class So I created UserValidator.java using Validator interface of Spring for validation of User while registration.
Problem is that validations are applied successfully but jsp page does not show the error messages.
UserValidator.java
#Component
public class UserValidator implements Validator {
public boolean supports(Class<?> clazz) {
return User.class.equals(clazz);
}
public void validate(Object obj, Errors errors) {
ValidationUtils.rejectIfEmpty(errors, "userName", "Enter a valid name");
ValidationUtils.rejectIfEmpty(errors, "address", " Enter Address");
ValidationUtils.rejectIfEmpty(errors, "mobNo", "Enter valid mobile number");
ValidationUtils.rejectIfEmpty(errors, "emailId", "Enter a valid email");
User user = (User) obj;
System.out.println(""+user.getUserName());
Pattern pattern = Pattern.compile("^[A-Z0-9._%+-]+#[A-Z0-9.-]+\\.[A-Z]{2,6}$",
Pattern.CASE_INSENSITIVE);
if (!(pattern.matcher(user.getEmailId()).matches())) {
errors.rejectValue("emailId", "Invalid email! Please enter valid email");
}
}}
RegistrationController.java
#Controller
public class RegistrationController {
#Autowired
UserValidator userValidator;
#InitBinder
public void initBinder(WebDataBinder webDataBinder){
webDataBinder.setValidator(userValidator);
}
#Autowired
private DepartmentDao departmentDao;
#Autowired
private DesignationDao designationDao;
#Autowired
private ConfigDao configDao;
#Autowired
private HintQuestionDao hintQuestionDao;
#Autowired
private GroupDao groupDao;
#Autowired
private UserDao userDao;
#RequestMapping("Register")
public String getRegisterPage(#ModelAttribute("user") User user, Model model) {
model.addAttribute("departmentList", departmentDao.getDepartments());
model.addAttribute("designationList", designationDao.getDesignation());
model.addAttribute("levelList", configDao.getLevel());
model.addAttribute("questionList",hintQuestionDao.getQuestions());
model.addAttribute("groupList", groupDao.getGroup());
return "Registration";
}
#RequestMapping("newRegisterUser")
public String createUser(#ModelAttribute("user") User user, Model model,#RequestParam("deptId") int deptid,
#RequestParam("desgId") int desgId,#RequestParam("grpId")int grpId,HttpSession session, BindingResult bindingResult) throws Exception{
User userSess= (User) session.getAttribute("userObj");
if(userSess!=null) {
userValidator.validate(user, bindingResult);
if (bindingResult.hasErrors()) {
return "redirect:Register";
}
user.setMobNo(user.getMobNo());
user.setDepartment(departmentDao.getDepartmentById(deptid));
user.setDesignation(designationDao.getDesignationById(desgId));
user.setGroup(groupDao.getGroupById(grpId));
user.setUpw1(user.getUserName().replace(" " , "").substring(0,4)+user.getEmailId().substring(0,2)+"#"+user.getMobNo().toString().substring(8));
user.setCreatedBy(userSess.getUserName());
user.setCreationDate(new Timestamp(System.currentTimeMillis()));
user.setLoginStatus("A");
userDao.createUser(user);
}
else {
model.addAttribute("AddMessage","Login First");
}
return "redirect:ListOfUser";
}}
Registration.jsp
<form:form class="form" modelAttribute="user" method="post" action="newRegisterUser">
<div class="form-group row">
<label class="col-lg-3 col-form-label form-control-label">Name:</label>
<div class="col-lg-9">
<form:input class="form-control" type="text" path="userName"/>
<form:errors path = "userName" cssClass = "error" />
</div>
</div>
<div class="form-group row">
<label class="col-lg-3 col-form-label form-control-label">Address:</label>
<div class="col-lg-9">
<form:textarea class="form-control" rows="2" path="address"></form:textarea>
<form:errors path = "address" cssClass = "error" />
</div>
</div>
<div class="form-group row">
<label class="col-lg-3 col-form-label form-control-label">Mobile:</label>
<div class="col-lg-3">
<form:input class="form-control" type="text" path="mobNo"/>
</div>
<label class="col-lg-2 col-form-label form-control-label">Email:</label>
<div class="col-lg-4">
<form:input class="form-control" type="email" path="emailId"/>
<form:errors path = "emailId" cssClass = "error" />
</div>
</div>
<div class="form-group row">
<label class="col-lg-3 col-form-label form-control-label">Department:</label>
<div class="col-lg-3">
<select name="deptId" id="dept_Id" class="form-control" size="0">
<option value="0">--Select--</option>
<c:forEach var="depts" items="${departmentList}">
<option value="<c:out value="${depts.deptid}" />">${depts.deptnm}</option>
</c:forEach>
</select>
</div>
<label class="col-lg-2 col-form-label form-control-label">Designation:</label>
<div class="col-lg-4">
<select name="desgId" id="design_Id" class="form-control" size="0">
<option value="0">--Select--</option>
<c:forEach var="desig" items="${designationList}">
<option value="<c:out value="${desig.desgid}" />">${desig.desgnm}</option>
</c:forEach>
</select>
</div>
</div>
<div class="form-group row">
<label class="col-lg-3 col-form-label form-control-label">Level:</label>
<div class="col-lg-3">
<select name="userLevel" id="lvl_Id" class="form-control" size="0">
<option value="-1">--Select--</option>
<c:forEach var="levelList" items="${levelList}">
<option value="<c:out value="${levelList.sk}"/>">${levelList.ds}</option>
</c:forEach>
</select>
</div>
<label class="col-lg-2 col-form-label form-control-label">Group:</label>
<div class="col-lg-4">
<select name="grpId" id="grp_Id" class="form-control" size="0">
<option value="-1">--Select--</option>
<c:forEach var="groupList" items="${groupList}">
<option value="<c:out value="${groupList.grpid}" />">${groupList.grpnm}</option>
</c:forEach>
</select>
</div>
</div>
<div class="form-group row">
<label class="col-lg-3 col-form-label form-control-label">Hint Question:</label>
<div class="col-lg-3">
<select name="hintId" id="que_Id" class="form-control" size="0">
<option value="0">--Select--</option>
<c:forEach var="questionList" items="${questionList}">
<option value="<c:out value="${questionList.hintid}" />">${questionList.hintquestion}</option>
</c:forEach>
</select>
</div>
<label class="col-lg-2 col-form-label form-control-label">Answer:</label>
<div class="col-lg-4">
<form:input class="form-control" type="text" path="hintAns"/>
</div>
</div>
<div class="form-group row">
<label class="col-lg-5 col-form-label form-control-label"></label>
<div class="col-lg-7">
<input type="submit" class="btn btn-info" value="Register">
<input type="reset" class="btn btn-primary" value="Cancel">
</div>
</div>
</form:form>
Can anybody help me out?
What i did wrong in this?
Thank you in advance.

Related

Dropdown menu for editing categories doesn't work

I'm making a simple blog using springframework. I'm trying to make Categories for my posts/articles. When I create articles, I have the option to choose a Category and it works fine. However, when I try to edit an Article, the drop-down menu for choosing a Category is not working. It's just and empty field with a 'down arrow' sidebad and nothing happens when I click on it
//ARTICLE EDIT--------------------------------------------------
#GetMapping("/article/edit/{id}")
#PreAuthorize("isAuthenticated()")
public String edit(#PathVariable Integer id, Model model)
{
if(!this.articleRepository.exists(id))
{
return "redirect:/";
}
Article article = this.articleRepository.findOne(id);
if(!isUserAuthorOrAdmin(article))
{
return "redirect:/article/"+id;
}
List<Category> categories = this.categoryRepository.findAll();
String tagString = article.getTags().stream().map(Tag::getName).collect(Collectors.joining(", "));
model.addAttribute("view", "article/edit");
model.addAttribute("article", article);
model.addAttribute("category", categories);
model.addAttribute("tags", tagString);
return "base-layout";
}
#PostMapping("/article/edit/{id}")
#PreAuthorize("isAuthenticated()")
public String editProcess(#PathVariable Integer id, ArticleBindingModel articleBindingModel)
{
if(!this.articleRepository.exists(id))
{
return "redirect:/";
}
Article article = this.articleRepository.findOne(id);
Category category = this.categoryRepository.findOne(articleBindingModel.getCategoryId());
HashSet<Tag> tags = this.findTagsFromString(articleBindingModel.getTagString());
if(!isUserAuthorOrAdmin(article))
{
return "redirect:/article/"+id;
}
article.setContent(articleBindingModel.getContent());
article.setTitle(articleBindingModel.getTitle());
article.setCategory(category);
article.setTags(tags);
this.articleRepository.saveAndFlush(article);
return "redirect:/article/" + article.getId();
}
The html file is:
<main>
<div class="container body-content span=8 offset=2">
<div class="well">
<form class="form-horizontal" th:action="#{/article/edit/{id}(id=${article.id})}" method="POST">
<fieldset>
<legend>Edit Post</legend>
<div class="form-group">
<label class="col-sm-4 control-label" for="article_title">Post Title</label>
<div class="col-sm-4 ">
<input type="text" class="form-control" id="article_title" placeholder="Post Title" name="title" th:value="${article.title}"/>
</div>
</div>
<div class="form-group">
<label class="col-sm-4 control-label" for="article_content">Content</label>
<div class="col-sm-6">
<textarea class="form-control" rows="6" id="article_content" name="content" th:field="${article.content}"></textarea>
</div>
</div>
<div class="form-group">
<label class="col-sm-4 control-label" for="article_tags">Tags</label>
<div class="col-sm-6">
<input type="text" class="form-control" id="article_tags" placeholder="Tags" name="tagString" th:value="${tags}"/>
</div>
</div>
<div class="form-group">
<label class="col-sm-4 control-label" for="article_category">Category</label>
<div class="col-sm-6">
<select class="form-control" id="article_category" name="categoryId">
<option th:each="category : ${categories}" th:value="${category.id}" th:text="${category.name}" th:selected="${category.id == article.category.id}">
</option>
</select>
</div>
</div>
<div class="form-group">
<div class="col-sm-4 col-sm-offset-4">
<a class="btn btn-default" th:href="#{/article/{id}(id = ${article.id})}">Cancel</a>
<input type="submit" class="btn btn-success" value="Edit"/>
</div>
</div>
</fieldset>
</form>
</div>
</div>
You should use model attributes' names inside ${}. There is a mismatch between model.addAttribute("category", categories); and th:each="category : ${categories}".
Change model attribute name to "categories" and it should be fine
model.addAttribute("categories", categories);

Spring boot post parameter as array getting null value

#PostMapping(value=("/addMessage"))
public String addMessagePostPicture(#RequestParam("picture") MultipartFile picture, Map<String, Object> model, HttpServletRequest request, #ModelAttribute MessageForm message) {
String[] contacts = request.getParameterValues("contacts");
if(message.getContacts() == null){
System.out.println("yes");
message.setContact(contacts);
}
public class MessageForm {
private String[] contacts;
public String[] getContacts() {
return contacts;
}
public void setContact(String[] contacts) {
this.contacts = contacts;
}
}
Why is message.getContacts value null? Request parameter with name contacts excisting.
addMessage.html code part where is getting that contacts parameter value
<form id="addMessageForm" class="form-horizontal" method="post" action="addMessage" enctype="multipart/form-data">
<div class="form-group ">
<label class="control-label col-sm-3 requiredField" for="contacts"> Kontaktid
<span class="asteriskField">* </span>
</label>
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#addContactModal">Lisa kontakt</button>
<div class="col-sm-9">
<select id="contacts" name="contacts" multiple="multiple">
options added here by javascript
</select>
</div>
</div>
<div class="form-group">
<div class="col-sm-9 col-sm-offset-3">
<button class="btn btn-primary " name="submit" type="submit" th:text="#{save}"> Salvesta</button>
</div>
</div>
</form>
example with javascript generated code
<select id="contacts" name="contacts" multiple="multiple">
<option value="2">test#mail.ee</option>
<option value="3">mail#mail.ee</option>
<option value="4">isik#mail.ee</option>
</select>

How to bind an input value in a list to a bean attribute with Spring

I need to bind an object with a list of objects as an attribute. It is a static list and it is created and partially filled in the Controller. It is displayed correctly in the view, however the value in the input field is not set when the form is sent to the controller. I did some research and found several similar questions, however none of the proposed solutions worked for me.
edit.jsp
<c:forEach items="${priceConfigurationForm.priceList}" var="price" varStatus="priceStatus">
<tr>
<td>
<spring:bind path="priceConfigurationForm.priceList[${priceStatus.index}].country">
${price.country}
<input type="hidden" name="<c:out value="${status.expression}"/>"
id="<c:out value="${status.expression}"/>"
value="<c:out value="${status.value}"/>"/>
</spring:bind>
</td>
<td>
<spring:bind path="priceConfigurationForm.priceList[${priceStatus.index}].amount">
<input type="text" name="price" value="${price.amount}"/>
<input type="hidden"
name="<c:out value="${status.expression}"/>"
id="<c:out value="${status.expression}"/>"
value="<c:out value="${status.value}"/>"/>
</spring:bind>
</td>
<td>
<spring:bind path="priceConfigurationForm.priceList[${priceStatus.index}].currency">
${price.currency}
<input type="hidden" name="<c:out value="${status.expression}"/>"
id="<c:out value="${status.expression}"/>"
value="<c:out value="${status.value}"/>"/>
</spring:bind>
</td>
</tr>
</c:forEach>
Abstract from Controller populating the list:
#RequestMapping(value = "/price/create", method = RequestMethod.GET)
public String toCreatePriceConfiguratioView(Model model) {
log.info("::createPriceConfiguration: {}");
final PriceConfigurationForm priceConfigurationForm = new PriceConfigurationForm();
final List<PriceConfigurationForm.Price> prices = new ArrayList<>();
for (Country country : Country.values()) {
PriceConfigurationForm.Price price = new PriceConfigurationForm.Price();
price.setAmount(100);
price.setCountry(country.getCountryCode());
price.setCurrency(country.getCurrency());
prices.add(price);
}
priceConfigurationForm.setPriceList(prices);
model.addAttribute("priceConfigurationForm", priceConfigurationForm);
return "/secured/sources/onboarding/price/edit";
}
Abstract from Controller for storing the list:
#RequestMapping(value = "/price/create", method = RequestMethod.POST)
public String createPriceConfiguration(Model model, #ModelAttribute("priceConfigurationForm") #Valid PriceConfigurationForm priceConfigurationForm, BindingResult bindingResult, RedirectAttributes attributes) {
log.info("::createPriceConfiguration {}", priceConfigurationForm);
// TODO: Validate, before create
/* transform form to domain object */
PriceConfiguration configuration = PriceConfigurationForm.toPriceConfiguration(priceConfigurationForm);
onboardingApi.createPriceConfiguration(configuration);
attributes.addFlashAttribute("message", success("price configuration saved", priceConfigurationForm.getName()));
return "/secured/sources/onboarding/price/index";
}
Object:
#Data
public class PriceConfigurationForm {
private String name;
private String description;
private List<Price> priceList;
private Map<String, Long> countryToPriceMap;
public static PriceConfiguration toPriceConfiguration(PriceConfigurationForm form) {
final PriceConfiguration pc = new PriceConfiguration();
pc.setName(form.getName());
pc.setDescription(form.getDescription());
final Map<String, Long> prices = form.getPriceList().stream().collect(toMap(Price::getCountry, Price::getAmount));
pc.setCountryToPriceMap(prices);
return pc;
}
#Data
public static class Price {
private String country;
private long amount;
private String currency;
}
}
This is example of how I sucessfully parsed nested objects in one project :
<c:forEach var="block" items="${newplaceform.blocks}" varStatus="counter">
<fieldset data-block-order="${counter.index}" data-block-index="${counter.index}">
<c:if test='${block.type=="quizSingleAnswer"}'>
<legend><s:message code='blocks.type.quizSingleAnswer'/> <a class="glyphicon glyphicon-move move-block pull-right" href="#"></a><a data-remove="block" class="glyphicon glyphicon-remove pull-right" href="#"></a><a data-reordering="up" class="glyphicon glyphicon-chevron-up pull-right" href="#"></a><a data-reordering="down" class="glyphicon glyphicon-chevron-down pull-right" href="#"></a></legend>
<div class="form-group production-hide">
<label class="col-sm-3 control-label">id:</label>
<div class="col-sm-9"><input type="text" name="blocks[${counter.index}].id" value="${block.id}" data-row="blockId" data-disabled class="form-control"/></div>
</div>
<div class="form-group production-hide">
<label class="col-sm-3 control-label">type:</label>
<div class="col-sm-9"><input type="text" name="blocks[${counter.index}].type" value="${block.type}" data-disabled class="form-control"/></div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label"><s:message code='blocks.description'/>:</label>
<div class="col-sm-9"><textarea class="form-control" name="blocks[${counter.index}].description" data-description rows="3">${block.description}</textarea></div>
</div>
<div class="row">
<div class="col-sm-6">
<div class="col-sm-6 control-label">
<label class="inner-header"><s:message code='blocks.answers'/>:</label>
</div>
<div class="col-sm-6">
<div class="btn-group m-t-9">
<a class="btn btn-primary btn-xs" href="#" data-add-answer data-add-answer-block-index="${counter.index}"><i class="glyphicon glyphicon-plus"></i> <s:message code="blocks.add-answer" /></a>
</div>
</div>
</div>
</div>
<div class="row quiz-answers" data-count-answer="${block.answers.size()}">
<c:forEach var="answer" items="${block.answers}" varStatus="counterInner">
<div class="col-sm-6">
<fieldset>
<legend>
<div class="bootstrap-center">
<span><s:message code="blocks.answerNo"/> ${counterInner.index+1}</span>
<a data-remove="answer" class="glyphicon glyphicon-remove pull-right" href="#"></a>
</div>
</legend>
<div class="form-group production-hide">
<label class="col-sm-6 control-label">id:</label>
<div class="col-sm-6"><input type="text" name="blocks[${counter.index}].answers[${counterInner.index}].id" value="${answer.id}" data-row="answerId" data-disabled class="form-control"/></div>
</div>
<div class="form-group">
<label class="col-sm-6 control-label"><s:message code="blocks.answer"/>:</label>
<div class="col-sm-6"><input type="text" name="blocks[${counter.index}].answers[${counterInner.index}].text" value="${answer.text}" class="form-control"/></div>
</div>
<div class="form-group">
<div class="col-sm-6 col-sm-offset-6">
<div class="checkbox">
<label>
<input type="checkbox" name="blocks[${counter.index}].answers[${counterInner.index}].right" value="true" ${answer.checked()}/>
<s:message code="blocks.right"/>
</label>
</div>
</div>
</div>
</fieldset>
</div>
</c:forEach>
</div>

Edit value is not updated in Spring CRUD example

Here is my code.When I check checkbox and click the edit button the value is fetched correctly.But edited value is not updated in mysql database as well as table.I'm using jdbc template for this example."location" field is select option value.
controller get the checkbox value and fetch data from database.after that the updated value is not shown in the table.
HomeController.java
#RequestMapping("/edit")
public String update(Model model,#RequestParam Map<String,String> req){
updateValue = new Integer(req.get("checkId"));
List<Users> users = userdao.getUpdateRecord(updateValue);
model.addAttribute("result",users);
return "formedit";
}
#RequestMapping("/saveUpdate")
public String saveUpdate(Model model,#RequestParam Map<String,String> req){
String name,storage,location,address;
name = req.get("name");
storage=req.get("storage");
location=req.get("location");
address = req.get("address");
int row = userdao.updateRecord(updateValue,name,storage,location,address);
String message = row+ "updated";
model.addAttribute("message", message);
result(model);
return "home";
}
UsersDAO doesn't get the update value from formedit page.
UsersDAO.java
public List<Users> getUpdateRecord(int updateValue){
System.out.println("update value"+updateValue);
String sql="select id,name,storage,location,address from customer where id="+updateValue;
return jdbc.query(sql,new UsersMapper());
}
public int updateRecord(int id,String name,String storage,String location,String address){
return jdbc.update("update customer set name = ?,storage = ?,location = ?,address=? where id = ?",id,name,storage,location,address);
formedit.jsp
<form role="form" action="saveUpdate" method="post" class="form-horizontal">
<c:forEach var="row" items="${result}">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="control-label col-xs-4 text">Customer Name</label>
<div class="col-xs-8">
<input type="text" class="form-control" name="name" value=${row.name }>
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-4 text">Storage Location*</label>
<div class="col-xs-8">
<input type="text" class="form-control" name="storage" value=${row.storage }>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="control-label col-xs-4 text">Location</label>
<div class="col-xs-8">
<input type="text" class="form-control" name="location" value=${row.location }>
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-4 text">Customer Address</label>
<div class="col-xs-8">
<textarea class="form-control" name="address">${row.address }</textarea>
</div>
</div>
</div>
<input type="submit" class="btn btn-success btn-md col-md-offset-6" value="Update">
</div>
</c:forEach>
</form>
}
Because this is wrong:
return jdbc.update("update customer set name = ?,storage = ?,location = ?,address=? where id = ?",id,name,storage,location,address);
The parameters order is incorrect, it doesnt find id with value address.

File uploading not working in spring mvc using spring form

I have a jsp page in which i have used spring form tag so that i can use model attribute and bind data to it. It was working fine on submit the form but after adding enctype="multipart/form-data" model attributes are returing null to the controller. What is wrong here ?
My Code is -
proflie.jsp
<sf:form method="POST" action="update" modelAttribute="user" class="form-horizontal" >
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">Avatar</label>
<div class="col-md-6">
<div class="media v-middle">
<div class="media-left">
<div class="icon-block width-100 bg-grey-100">
<i class="fa fa-photo text-light"></i>
</div>
</div>
<div class="media-body">
<i class="fa fa-upl"><sf:input path="imageFile" type="file" class="btn btn-white btn-sm paper-shadow relative" placeholder="Add Image" id="imageFile" />
</i>
</div>
</div>
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-md-2 control-label">Full Name</label>
<div class="col-md-8">
<div class="row">
<div class="col-md-6">
<div class="form-control-material">
<sf:input path="firstName" type="text" class="form-control" id="firstName" placeholder="Your first name" value="${user.firstName}" />
<sf:input path="id" type="hidden" class="form-control" id="id" value="${user.id}" />
<label for="firstName">First name</label>
</div>
</div>
<div class="col-md-6">
<div class="form-control-material">
<sf:input path="lastName" class="form-control" id="lastName" placeholder="Your last name" value="${user.lastName}" />
<label for="lastName">Last name</label>
</div>
</div>
</div>
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-md-2 control-label">Email</label>
<div class="col-md-6">
<div class="form-control-material">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-envelope"></i></span>
<sf:input path="email" type="email" class="form-control" id="inputEmail3" placeholder="Email" value="${user.email}" />
<label for="inputEmail3">Email address</label>
</div>
</div>
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-md-2 control-label">Phone</label>
<div class="col-md-6">
<div class="form-control-material">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-envelope"></i></span>
<sf:input path="phone" type="number" class="form-control" id="inputEmail3" placeholder="Phone" value="${user.phone}" />
<label for="phone">Phone</label>
</div>
</div>
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-md-2 control-label">Address</label>
<div class="col-md-6">
<div class="form-control-material">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-link"></i></span>
<sf:input path="address" type="text" class="form-control used" id="website" placeholder="Address" value="${user.address}" />
<label for="address">Address</label>
</div>
</div>
</div>
</div>
<div class="form-group">
<label for="inputPassword3" class="col-md-2 control-label">Change Password</label>
<div class="col-md-6">
<div class="form-control-material">
<sf:input path="password" type="password" class="form-control" id="inputPassword3" placeholder="Password" value="${user.password}" />
<label for="password">Password</label>
</div>
</div>
</div>
<div class="form-group margin-none">
<div class="col-md-offset-2 col-md-10">
<button type="submit" class="btn btn-primary paper-shadow relative" data-z="0.5" data-hover-z="1" data-animated>Save Changes</button>
</div>
</div>
</sf:form>
AccountController class
package com.vc.teacher.controller;
import java.io.File;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
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.servlet.mvc.support.RedirectAttributes;
import com.vc.teacher.db.dao.UserDao;
import com.vc.teacher.entities.User;
import com.vc.teacher.util.Constants;
#Controller
public class AccountController {
#Autowired
UserDao userDao;
#RequestMapping("/login")
public String loginUser(#RequestParam("email") String email,
#RequestParam("password") String password, Model model) {
User user = userDao.checkCreditionals(email, password);
if (user != null) {
model.addAttribute("user", user);
return "jsp/profile";
} else {
model.addAttribute("error", "Wrong creditionals");
return "jsp/signin";
}
}
#RequestMapping("/signUp")
public String initilize(Model model) {
model.addAttribute(new User());
return "jsp/signup";
}
#RequestMapping(method = RequestMethod.POST, value = "/register")
public String signUpUser(User user, RedirectAttributes attributes) {
boolean result = false;
File imageFile = null;
try {
imageFile = user.getImageFile();
if (imageFile != null) {
File imageFileSave = new File(Constants.MEDIA_FILE_PATH);
FileUtils.copyFile(imageFile, imageFileSave);
user.setImageFileName(imageFile.getName());
}
user.setStatus("Deactive");
result = userDao.registerUser(user);
if (result == true) {
attributes.addFlashAttribute("message",
"You are ready to go now !");
return "redirect:/signUp";
} else {
attributes.addFlashAttribute("message", "Something went wrong");
return "redirect:/signUp";
}
} catch (Exception e) {
attributes.addFlashAttribute("message", "Something went wrong");
return "redirect:/signUp";
}
}
#RequestMapping(method = RequestMethod.POST, value = "/update")
public String updateUser(User user, RedirectAttributes attributes) {
boolean result = false;
File imageFile = null;
try {
System.out.println("=================================="+user.getEmail());
System.out.println("=================================="+user.getId());
System.out.println("=================================="+user.getFirstName());
imageFile = user.getImageFile();
if (imageFile != null) {
File imageFileSave = new File(Constants.MEDIA_FILE_PATH);
FileUtils.copyFile(imageFile, imageFileSave);
user.setImageFileName(imageFile.getName());
}
user.setStatus("Active");
result = userDao.updateUser(user);
if (result == true) {
attributes.addFlashAttribute("message", "Profile Updated !");
return "jsp/profile";
} else {
attributes.addFlashAttribute("message", "Something went wrong");
return "jsp/profile";
}
} catch (Exception e) {
attributes.addFlashAttribute("message", "Something went wrong");
return "jsp/profile";
}
}
}
On its own, DispatcherServlet doesn't know how to handle multipart form data; that's why we require multipart resolver.
You should register it in your servlet-config:
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="500000" />
</bean>
Use CommonsMultipartFile or MultipartFile instead of File in your User object:
private CommonsMultipartFile imageFile;
You can try this code to save file:
File imageFileSave = new File(Constants.MEDIA_FILE_PATH);
FileUtils.writeByteArrayToFile(imageFileSave , imageFile.getBytes());

Categories

Resources