First of all: I'm a beginner in Spring and this is my first try to implement an web application with Spring MVC.
Here is what I've done yet:
Entities:
#Entity
#Table(name = "coins")
public class Coin
{
#Id
#GeneratedValue
private Integer id;
#OneToOne
private Country country;
private double value;
private int year;
}
#Entity
#Table(name = "countries")
public class Country
{
#Id
#GeneratedValue
private Integer id;
private String name;
}
Controller:
#Controller
public class CoinViewController {
#Autowired
private CoinService service;
#Autowired
private CountryService countryService;
#ModelAttribute("countries")
public List<Country> frequencies() {
return countryService.get();
}
#RequestMapping(value = "/coins/add", method = RequestMethod.GET)
public String addCoin(Model model) {
model.addAttribute("coin", new Coin());
return "coins/add";
}
#RequestMapping(value = "/coins/add", method = RequestMethod.POST)
public String addCoinResult(#ModelAttribute("coin") Coin coin, BindingResult result) {
// TODO: POST HANDLING
return "/coins/add";
}
}
JSP:
<form:form action="add" method="POST" modelAttribute="coin">
<div class="form-group">
<label for="country">Country:</label>
<form:select path="country" class="form-control" >
<form:option value="" label="-- Choose one--" />
<form:options items="${countries}" itemValue="id" itemLabel="name" />
</form:select>
</div>
<div class="form-group">
<label for="value">Value:</label>
<form:input path="value" class="form-control" />
</div>
<div class="form-group">
<label for="year">Year:</label>
<form:input path="year" class="form-control" />
</div>
<button type="submit" value="submit" class="btn btn-default">Erstellen</button>
</form:form>
But when I try to save the input from the JSP I always get this:
Field error in object 'coin' on field 'country': rejected value [1];
codes
[typeMismatch.coin.country,typeMismatch.country,typeMismatch.Country,typeMismatch];
arguments
[org.springframework.context.support.DefaultMessageSourceResolvable:
codes [coin.country,country]; arguments []; default message
[country]]; default message [Failed to convert property value of type
'java.lang.String' to required type 'Country' for property 'country';
nested exception is java.lang.IllegalStateException: Cannot convert
value of type [java.lang.String] to required type [Country] for
property 'country': no matching editors or conversion strategy found]
So my questions are:
What should I use Editor / Converter?
How do I register one of them in my Controller?
You can register a custom editor into initBinder of your controller class:
#Controller
public class CoinViewController {
#Autowired
private CountryEditor countryEditor;
#InitBinder
protected void initBinder(final WebDataBinder binder, final Locale locale) {
binder.registerCustomEditor(Country.class, countryEditor);
}
......
}
(locale parameter is not needed in this case, but it can be useful if you need locale to make conversion - for example if you are working with dates)
and you can define your CountryEditor like the following:
#Component
public class CountryEditor extends PropertyEditorSupport {
#Autowired
private CountryService countryService;
#Override
public void setAsText(final String text) throws IllegalArgumentException {
try{
final Country country = countryService.findById(Long.parseLong(text));
setValue(cliente);
}catch(Exception e){
setValue(country);
// or handle your exception
}
}
}
I let spring handle injection of my editors with #Component annotation. So if you like to do in that way remember to enable package scan for that class!
Hope this help!
Related
I'm trying to add data to my database and reload the same page using spring boot and thymeleaf but when I save data I face this error
org.springframework.beans.TypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'org.closure.gcp.entities.QuestionEntity'; nested exception
is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [java.lang.Integer] for value 'adsf'; nested exception is java.lang.NumberFormatException: For input string: "adsf"
controller code :
#Controller
#RequestMapping(path = "/Questions")
public class QuestionView {
#Autowired
QuestionRepo questionRepo;
#RequestMapping(path = "/")
public String index(#ModelAttribute("question") QuestionEntity question, Model model)
{
List<QuestionEntity> list = questionRepo.findAll();
model.addAttribute("questions", list);
return "Questions";
}
#RequestMapping(value="/add", method=RequestMethod.POST)
public String addQuestion(Model model,#ModelAttribute("question") QuestionEntity question) {
questionRepo.save((QuestionEntity)model.getAttribute("question"));
List<QuestionEntity> list = questionRepo.findAll();
model.addAttribute("questions", list);
return "Questions";
}
}
thymeleaf page :
<html>
<header>
<title>Questions</title>
</header>
<body>
<h2>hello questions</h2>
<hr>
<tr th:each="q: ${questions}">
<td th:text="${q.question}"></td>
<br>
<td th:text="${q.question_type}"></td>
<hr>
</tr>
<!-- <form th:action="#{/add}" th:object="${question}" method="post"> -->
<form action="./add" th:object="${question}" method="POST">
<input type="text" th:field="*{question}" />
<br >
<input type="text" th:field="*{question_type}" />
<br >
<input type="submit" value="save" >
</form>
</body>
</html>
#Entity
#Table(name="question")
public class QuestionEntity {
#Id
#GeneratedValue(strategy = GenerationType.TABLE)
private Integer id;
#Column(nullable=false)
private String question;
#Column(nullable=false)
private String question_type;
#ManyToOne(optional = true)
private InterestEntity interest;
#ManyToOne(optional = true)
private LevelEntity level;
#Column(nullable = true)
private String sup_file;
#Column(nullable = false)
private int pionts;
#ManyToMany
private List<ContestEntity> contest;
#OneToMany(mappedBy ="question")
private List<AnswerEntity> answers;
// getters and setters
}
notice when I try to open another page in "/add" it works
I found this to solve
I just made a model class and use it instead of entity
and I used just one method to handle index and add requests
#Controller
#RequestMapping(path = "/Questions")
public class QuestionView {
#Autowired
QuestionRepo questionRepo;
#RequestMapping(path = {"/",""},method = {RequestMethod.POST,RequestMethod.GET})
public String index(#ModelAttribute("question") QuestionModel question, Model model,HttpServletRequest request)
{
if(request.getMethod().equals("POST"))
{
questionRepo.save(new QuestionEntity().question(question.getQuestion()).question_type(question.getQuestion_type()));
}
List<QuestionEntity> list = questionRepo.findAll();
model.addAttribute("questions", list);
return "Questions";
}
}
It is better to have 2 separate methods, one for GET and one for POST and to use redirect after the POST (see https://en.wikipedia.org/wiki/Post/Redirect/Get). This is how I would code this based on your separate QuestionModel class:
#Controller
#RequestMapping(path = "/Questions")
public class QuestionView {
#Autowired
QuestionRepo questionRepo;
#GetMapping
public String index(Model model)
{
List<QuestionEntity> list = questionRepo.findAll();
model.addAttribute("questions", list);
model.addAttribute("question", new QuestionModel());
return "Questions";
}
#PostMapping("/add")
public String addQuestion(#Valid #ModelAttribute("question") QuestionModel question, BindingResult bindingResult, Model model) {
if(bindingResult.hasErrors()) {
return "Questions";
}
questionRepo.save(new QuestionEntity().question(question.getQuestion()).question_type(question.getQuestion_type()));
return "redirect:/Questions";
}
}
Main points:
Use separate methods for GET and POST
Add the #Valid annotation to the #ModelAttribute in the POST method so any validation annotations on QuestionModel are checked (Because you probably want to make sure the question has at least some text in it for example).
Use BindingResult as parameter to check if there are validation errors.
Use "redirect:" to force a new GET after the POST to help avoid double submissions if a user would refresh the browser.
please help me.
I'm working validate form. The fields of class student as "name","address","email" display message when i click submit form but my problem is the fields that class student contains relationship as class major is not display message. I tried to put #Valid annotations and i get the same a result.
I get an errors: Failed to convert property value of type java.lang.String to required type com.springmvc.entities.Major for property major; nested exception is java.lang.IllegalStateException: Cannot convert value of type java.lang.String to required type com.springmvc.entities.Major for property major: no matching editors or conversion strategy found.
Can someone help me or give me solutions ? I'm so grateful !
I sincerely apologize if my English is not good
#Entity(name="student")
public class Student{
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
int id;
#NotNull(message="Your name must not null !")
String name;
#NotNull(message="Your address must not null !")
String address;
#NotNull(message="Your email must not null !")
String email;
#NotNull(message="Select a major !")
#Valid
#OneToOne(fetch=FetchType.EAGER)
#JoinColumn(name="idMajor")
private Major major;
//getter - setter ...
}
#Entity(name="major")
public Class Major{
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
int idMajor;
String major;
//getter - setter ...
}
//My controller
#Controller
public class StudentController{
#Autowired
StudentService studentService;
#InitBinder
public void InitBinder(WebDataBinder binder){
StringTrimmerEditor stringTrimmerEditor = new StringTrimmerEditor(true);
binder.registerCustomEditor(String.class, stringTrimmerEditor);
}
#ModelAttribute("studentForm")
public Student studentForm()
{
return new Student();
}
#RequestMapping(value="/saveStudent",method= RequestMethod.POST)
public String SaveStudent(#Valid #ModelAttribute("studentForm") Student
student,BindingResult bindingResult, ModelMap model) {
if (bindingResult.hasErrors())
{
return "page-student";
}
else {
model.addAttribute("msg", "Save success!");
studentService.SaveStudent(student);
return "page-student;
}
}
}
//My View (page-student.jsp)
<form:form action="saveStudent" enctype="multipart/form-data" method="post"
modelAttribute="studentForm" >
<p>Name:<form:input path="name"/></p>
<form:errors path="name" cssClass="error" /> // Validate ok !
<p>Address:<form:input path="address"/></p>
<form:errors path="address" cssClass="error" /> // Validate ok !
<p>Email:<form:input path="email"/></p>
<form:errors path="email" cssClass="error" /> // Validate ok !
<p>Major:<form:select path="major">
<form:option value="0">-- Select --</form:option>
<c:forEach var="major" items="${major}">
<form:option value="${major.getIdMajor()}">
${major.getMajor()}
</form:option>
</c:forEach>
</form:select></p>
<form:errors path="major" cssClass="error" />
// I get an errors as I mentioned in my description above.
<form:button type="submit" >Submit</form:button>
</form:form>
I need help with this. I've spent 2 hrs and can't find anything.
The problem: I'm entering Text in Skill and Proficiency field in an html form. The model takes String. But I get the error saying failed to convert to number.
This is the error I'm getting:
Failed to bind request element:
org.springframework.beans.TypeMismatchException: Failed to convert value of
type 'java.lang.String' to required type 'com.byAJ.persistence.models.Skills';
nested exception is
org.springframework.core.convert.ConversionFailedException: Failed to convert
from type [java.lang.String] to type [java.lang.Long] for value 'Designing
engines'; nested exception is java.lang.NumberFormatException: For input
string: "Designingengines"
2017-07-09 15:48:57.233 WARN 16312 --- [nio-8080-exec-9]
.w.s.m.s.DefaultHandlerExceptionResolver : Resolved exception caused by
Handler execution: org.springframework.beans.TypeMismatchException: Failed to
convert value of type 'java.lang.String' to required type
'com.byAJ.persistence.models.Skills'; nested exception is
org.springframework.core.convert.ConversionFailedException: Failed to convert
from type [java.lang.String] to type [java.lang.Long] for value 'Designing
engines'; nested exception is java.lang.NumberFormatException: For input
string: "Designingengines"
HTML Page:
<form autocomplete="off" action="#" th:action="#{/skill}"
th:object="${skill}" method="post">
<div class="form-group">
<!-- <label for="degree">Degree <mark><strong><span th:if="${#fields.hasErrors('firstName')}" th:errors="*{firstName}">First Name Error</span></strong></mark></label>-->
<label for="skill">Skill<mark><strong><span th:if="${#fields.hasErrors('skill')}" th:errors="*{skill}">can't be empty</span></strong></mark></label>
<input type="text" class="form-control" id="skill" placeholder="Engineer" th:field="*{skill}" />
</div>
<div class="form-group">
<label for="proficiency">Proficiency( Beginner, Proficient, Expert) <mark><strong><span th:if="${#fields.hasErrors('proficiency')}" th:errors="*{proficiency}"> can't be empty</span></strong></mark></label>
<input type="text" class="form-control" id="proficiency" placeholder="Expert" th:field="*{proficiency}" />
</div>
<div class="form-group">
<p>Enter More Skills?</p>
<input type="radio" name="yesOrNo" value="yes"> Yes
<input type="radio" name="yesOrNo" value="no" checked> No
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
Skill Controllers:
#RequestMapping(value="/skill", method = RequestMethod.GET)
public String getSkill(Model model)
{
model.addAttribute("skill", new Skills());
return "skillForm";
}
#RequestMapping(value="/skill", method = RequestMethod.POST)
public String processSkil(#Valid #ModelAttribute("skill") Skills skill, BindingResult result, Model model, #RequestParam("yesOrNo") String yesNo){
System.out.println("helo");
System.out.println(result.toString());
if (result.hasErrors()) {
return "skillForm";
} else {
skill.setUsername(userService.getUserDetails().getUsername());
userService.saveSkill(skill);
}
if( yesNo.equals("yes")){
return "redirect:/skill";
}
return "myResume";
}
Skill Model:
#Entity
public class Skills {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
#NotEmpty
private String skill, proficiency;
private String username;
public String getSkill() {
return skill;
}
public void setSkill(String skill) {
this.skill = skill;
}
public String getProficiency() {
return proficiency;
}
public void setProficiency(String proficiency) {
this.proficiency = proficiency;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public long getId() {
return id;
}
}
Finally Skill Repository CRUD:
import com.byAJ.persistence.models.Skills;
import org.springframework.data.repository.CrudRepository;
public interface SkillRepository extends CrudRepository<Skills, Long>{
}
Any tip is greatly appreciated. Thanks!
UPDATE: When I try entering a number in the skill field, I don't get any error and the value gerts stored in the databse. This is really confusing, as I don't have field that's expecting integer for those values.
I noticed that I had the same name for Object and field and mapping. So I changed them to different names and Now the program is working.
In a spring mvc application that utilizes hibernate and jpa, I have a form that needs to store a document including metadata about the document such as the current date when the form is submitted. I have the model, controller, and jsp all set up, but when it runs, the create or add jsp is returned when the user clicks on the button to submit a document to the database. The error indicates that the problem is that the code is not handling the conversion from String to Blob. I HAVE NOTED THE LOCATION IN THE processCreationForm() METHOD WHERE THE CODE IS RETURNING THE createOrUpdateDocumentForm.jsp INSTEAD OF REDIRECTING TO THE LIST JSP AND I HAVE INCLUDED THE ERROR MESSAGE AT THE BOTTOM OF THIS POSTING.
How can I change my code below so that document is saved to the database when the user clicks on the submit button?
Here is my createOrUpdateDocumentForm.jsp:
<body>
<script>
$(function () {
$("#created").datepicker({ dateFormat: 'yy/mm/dd'});
});
</script>
<div class="container">
<jsp:include page="../fragments/bodyHeader.jsp"/>
<c:choose>
<c:when test="${document['new']}">
<c:set var="method" value="post"/>
</c:when>
<c:otherwise>
<c:set var="method" value="put"/>
</c:otherwise>
</c:choose>
<h2>
<c:if test="${document['new']}">New </c:if>
Document
</h2>
<form:form modelAttribute="document" method="${method}"
class="form-horizontal">
<div class="control-group" id="patient">
<label class="control-label">Patient </label>
<c:out value="${document.patient.firstName} ${document.patient.lastName}"/>
</div>
<petclinic:inputField label="Name" name="name"/>
<petclinic:inputField label="Description" name="description"/>
<div class="control-group">
<petclinic:selectField name="type" label="Type " names="${types}" size="5"/>
</div>
<td><input type="file" name="content" id="content"></input></td>
<div class="form-actions">
<c:choose>
<c:when test="${document['new']}">
<button type="submit">Add Document</button>
</c:when>
<c:otherwise>
<button type="submit">Update Document</button>
</c:otherwise>
</c:choose>
</div>
</form:form>
<c:if test="${!document['new']}">
</c:if>
<jsp:include page="../fragments/footer.jsp"/>
</div>
</body>
Here are the relevant parts of the controller:
#RequestMapping(value = "/patients/{patientId}/documents/new", method = RequestMethod.GET)
public String initCreationForm(#PathVariable("patientId") int patientId, Map<String, Object> model) {
Patient patient = this.clinicService.findPatientById(patientId);
Document document = new Document();
patient.addDocument(document);
model.put("document", document);
return "documents/createOrUpdateDocumentForm";
}
#RequestMapping(value = "/patients/{patientId}/documents/new", method = RequestMethod.POST)
public String processCreationForm(#ModelAttribute("document") Document document, BindingResult result, SessionStatus status) {
document.setCreated();
//THE FOLLOWING LINE PRINTS OUT A VALID DATE FOR document.getCreated()
System.out.println("document.getCreated() is: "+document.getCreated());
new DocumentValidator().validate(document, result);
if (result.hasErrors()) {
System.out.println("result.getFieldErrors() is: "+result.getFieldErrors());
//THIS IS BEING RETURNED BECAUSE result.getFieldErrors() RETURNS WHAT IS BEING
//SHOWN AT THE BOTTOM OF THIS POSTING, BELOW
return "documents/createOrUpdateDocumentForm";
}
else {
this.clinicService.saveDocument(document);
status.setComplete();
return "redirect:/patients?patientID={patientId}";
}
}
And here is the the model, which are parts of Document.java:
#Entity
#Table(name = "documents")
public class Document {
#Id
#GeneratedValue
#Column(name="id")
private Integer id;
#ManyToOne
#JoinColumn(name = "client_id")
private Patient patient;
#ManyToOne
#JoinColumn(name = "type_id")
private DocumentType type;
#Column(name="name")
private String name;
#Column(name="description")
private String description;
#Column(name="filename")
private String filename;
#Column(name="content")
#Lob
private Blob content;
#Column(name="content_type")
private String contentType;
#Column(name = "created")
private Date created;
public Integer getId(){return id;}
public void setId(Integer i){id=i;}
protected void setPatient(Patient patient) {this.patient = patient;}
public Patient getPatient(){return this.patient;}
public void setType(DocumentType type) {this.type = type;}
public DocumentType getType() {return this.type;}
public String getName(){return name;}
public void setName(String nm){name=nm;}
public String getDescription(){return description;}
public void setDescription(String desc){description=desc;}
public String getFileName(){return filename;}
public void setFileName(String fn){filename=fn;}
public Blob getContent(){return content;}
public void setContent(Blob ct){content=ct;}
public String getContentType(){return contentType;}
public void setContentType(String ctype){contentType=ctype;}
public void setCreated(){created=new java.sql.Date(System.currentTimeMillis());}
public Date getCreated() {return this.created;}
#Override
public String toString() {return this.getName();}
public boolean isNew() {return (this.id == null);}
}
The above code compiles, but when the user presses the submit button after entering the information to upload a document, the same add or update form is returned instead of redirecting to the summary page. This indicates from the controller method above that result.haserrors is true even though none of the errors checked for by system.out.println are true. The eclipse console does not show an error. However result.getFieldErrors() prints out the following:
[
Field error in object 'document' on field 'content':
rejected value [mydocname.txt];
codes [typeMismatch.document.content,typeMismatch.content,typeMismatch.java.sql.Blob,typeMismatch];
arguments [org.springframework.context.support.DefaultMessageSourceResolvable:
codes [document.content,content];
arguments []; default message [content]];
default message
[
Failed to convert property value of type 'java.lang.String' to required type 'java.sql.Blob' for property 'content';
nested exception is java.lang.IllegalStateException:
Cannot convert value of type [java.lang.String] to required type [java.sql.Blob] for property 'content':
no matching editors or conversion strategy found
]
]
First of all Your form is missing the tag enctype="multipart/form- data",
If it not still working you may consider using the MultipartFile interface
UPDATE
You can read the spring documentation, it is really straightforward .
Now, to apply it in your situation you can follow this tutorial : Saving/Retreving BLOB object in Spring 3 MVC and Hibernate
I am having difficulties binding the spring form value to a backing object.
The following are the related parts of the code.
This is from page.jsp
<form:form method="post" commandName="building" action="addBuilding">
<div>
<div>
<form:label path="buildingName">Building Name:</form:label>
<form:input path="buildingName" />
<form:errors path="buildingName"></form:errors>
</div>
<div>
<form:label path="buildingType">Building Type:</form:label>
<form:select path="buildingType">
<form:option value="none">--Select One--</form:option>
<form:options items="${buildingTypeList}" itemValue="id" itemLabel="typeName"/>
</form:select>
<form:errors path="buildingType"></form:errors>
</div>
</div>
</form:form>
Model classes I want to bind are as the following. I add these for the sake of completeness
#Entity
#Table(name="tablename")
class Building {
#Column
private buildingName;
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "buildingType", referencedColumnName = "id", nullable = false)
private BuildingType buildingType;
//other fields, getters and setters etc.
}
#Entity
#Table(name="tablename")
class BuildingType {
#Id
#Column
private int id;
#Column
private String typeName;
//getters, setters
}
At this point I can see the building type name in the combo-box just fine (in a GET request). The problem happens when I post the form. Itemvalue from combo-box is int and I want to bind it to the buildingType field in the Building model. The code will explain it better I guess. Related controller functions:
#RequestMapping(value = "addBuilding", method = RequestMethod.GET)
public String addBuildingPage(Model model) {
Building building = new Building();
model.addAttribute("building", building);
List<BuildingType> buildingTypeList = buildingTypeDao.findAll();
model.addAttribute("buildingTypeList", buildingTypeList);
return "addBuilding";
}
#RequestMapping(value = "addBuilding", method = RequestMethod.POST)
public String submitNewBuilding(#ModelAttribute(value = "building") #Valid Building building,
BindingResult result, Model model) {
if (result.hasErrors()) {
return "addBuilding";
}
model.addAttribute("building", building);
return "addBuilding";
}
I get a cannot cast int to BuildingType exception, after some search I followed the blog post written here. So I decided to write a custom Formatter and use ConversionService.
This is the formatter class
#Component
public class BuildingTypeFormatter implements Formatter<BuildingType> {
#Autowired
private BuildingTypeDao buildingTypeDao;
#Override
public String print(BuildingType buildingType, Locale arg1) {
return buildingType.getName();
}
#Override
public BuildingTypeDBO parse(String id, Locale arg1) throws ParseException {
return buildingTypeDao.findOne(Long.parseLong(id));
}
}
And this is the spring configuration class. (I don't use xml configuration.)
#EnableWebMvc
#Configuration
#ComponentScan({ "my.packages" })
public class MvcConfig extends WebMvcConfigurerAdapter {
#Autowired
private BuildingTypeDBOFormatter formatter;
public MvcConfig() {
super();
}
#Bean(name = "conversionService")
public FormattingConversionServiceFactoryBean conversionService() {
FormattingConversionServiceFactoryBean bean = new FormattingConversionServiceFactoryBean();
Set<Formatter<?>> formatters = new HashSet<Formatter<?>>();
formatters.add(formatter);
bean.setFormatters(formatters);
return bean;
}
I think I need to register conversion service as explained in the blog post. Using and init binder in my controller like this.
#Autowired
ConversionService conversionService;
#InitBinder
public void initBinder(WebDataBinder binder) {
binder.setConversionService(conversionService);
}
The problem is I get the following exception when using setConversionException. And when I debug it I see that binder is initialized with a default conversionService.
java.lang.IllegalStateException: DataBinder is already initialized with ConversionService
at org.springframework.util.Assert.state(Assert.java:385)
at org.springframework.validation.DataBinder.setConversionService(DataBinder.java:562)
at my.package.controller.MyController.initBinder(MyController.java:138)
I came across with many answers suggesting setConversionService but it just doesn't work, how can I fix this? (PS: Sorry for the long post, but I think there may be couple of ways to fix this, so I preferred to post the whole thing.)
You can try add custom property editor in your controller
#InitBinder
public void initBinder(ServletRequestDataBinder binder) {
binder.registerCustomEditor(BuildingType.class, "buildingType", new PropertyEditorSupport() {
public void setAsText(String text) {
Long buildingTypeId = Long.parseLong(text);
BuildingType buildingType = (BuildingType) buildingTypeDao.findOne(buildingTypeId);
setValue(buildingType);
}
});
}