This question already has answers here:
JQuery, Spring MVC #RequestBody and JSON - making it work together
(5 answers)
Spring MVC + JSON = 406 Not Acceptable
(22 answers)
Closed 7 years ago.
I'm having a hard time fixing this 406 error with spring MVC. What I want to do is to make an Ajax call and get a json response. Also I'm trying to output that json using alert(js). This is how I implement it.
My Controller:
#RequestMapping(value="/search", headers="Accept=*/*", produces=MediaType.APPLICATION_JSON_VALUE) // no 'params' argument
#ResponseBody
public Customer findByFirstName() {
Customer test = new Customer();
test.setFirstName("test");
return test;
}
Customer:
#Entity
#Table(name="customer",catalog="revised_cws_db")
public class Customer implements java.io.Serializable {
#Id #GeneratedValue(strategy=IDENTITY)
#Column(name="id", unique=true, nullable=false)
private int id;
#Version #Temporal(TemporalType.TIMESTAMP)
#Column(name="timestamp", nullable=false)
private Date timestamp;
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name="address_id", nullable=false)
private Address address;
#Temporal(TemporalType.DATE)
#Column(name="birth_date", nullable=false, length=10)
private Date birthDate;
#Column(name="first_name", nullable=false, length=45)
private String firstName;
#Column(name="middle_name", nullable=false, length=45)
private String middleName;
#Column(name="gender", nullable=false, length=45)
private String gender;
#Column(name="contact_number", length=45)
private String contactNumber;
#Column(name="family_members_count", nullable=false, length=45)
private String familyMembersCount;
#Column(name="occupation_id", nullable=false)
private int occupationId;
#Column(name="active", nullable=false)
private boolean active;
#OneToMany(fetch=FetchType.LAZY, mappedBy="customer")
private Set<Issues> issueses = new HashSet<Issues>(0);
#OneToMany(fetch=FetchType.LAZY, mappedBy="customer")
private Set<Account> accounts = new HashSet<Account>(0);
public Customer() {
}
public Customer(int id, Address address, Date birthDate, String firstName, String middleName, String gender, String familyMembersCount, int occupationId, boolean active) {
this.id = id;
this.address = address;
this.birthDate = birthDate;
this.firstName = firstName;
this.middleName = middleName;
this.gender = gender;
this.familyMembersCount = familyMembersCount;
this.occupationId = occupationId;
this.active = active;
}
public Customer(int id, Address address, Date birthDate, String firstName, String middleName, String gender, String contactNumber, String familyMembersCount, int occupationId, boolean active, Set<Issues> issueses, Set<Account> accounts) {
this.id = id;
this.address = address;
this.birthDate = birthDate;
this.firstName = firstName;
this.middleName = middleName;
this.gender = gender;
this.contactNumber = contactNumber;
this.familyMembersCount = familyMembersCount;
this.occupationId = occupationId;
this.active = active;
this.issueses = issueses;
this.accounts = accounts;
}
//getters, setters omitted
servlet:
<bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>
<mvc:annotation-driven/>
<context:component-scan base-package="com.controller" />
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="cacheSeconds" value="0" />
</bean>
<!--
Most controllers will use the ControllerClassNameHandlerMapping above, but
for the index controller we are using ParameterizableViewController, so we must
define an explicit mapping for it.
-->
<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="index.htm">indexController</prop>
</props>
</property>
</bean>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/"
p:suffix=".jsp" />
<!--
The index controller.
-->
<bean name="indexController"
class="org.springframework.web.servlet.mvc.ParameterizableViewController"
p:viewName="index" />
jsp:
<%#taglib uri = "http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
$(document).ready(function() {
$(".search-form").keyup(function() {
if ($(this).val().length >= 2) {
$('#searchForm').submit();
}
});
$('#searchForm').submit(function(event) {
$.ajax({
dataType: 'json',
data : $(this).serialize(),
url: $(this).attr("action"),
success: function( result ) {
alert("test");
}
});
event.preventDefault();
});
});
</script>
</head>
<body>
<h1>Customers</h1>
<form id="searchForm" action="search.htm">
Search Customer:
<input class="search-form" name="firstName" placeholder="First Name">
<input type="submit">
</form>
</body>
I already added the following jars:
jackson-core-asl 1.9.13
jackson-mapper-asl 1.9.13
jackson-core 2.4.4
jackson-databind 2.4.4
jackson-annotations 2.4.4
I dont know what's wrong. I'll appreciate any suggestions.
Related
#OneToMany
I have this error "Can't find inverse attribute" while going through the Spring course. In the course there is no issue with this code but I have. Maybe some one could help?
Instructor.class
#Entity
#Table(name = "instructor")
#Getter
#Setter
#NoArgsConstructor
public class Instructor {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private int id;
#Column(name = "first_name")
private String firstName;
#Column(name = "last_name")
private String lastName;
#Column(name = "email")
private String email;
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "instructor_detail_id")
private InstructorDetail instructorDetail;
#OneToMany(mappedBy = "instructor")
private List<Course> courses;
public Instructor(String firstName, String lastName, String email) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}
#Override
public String toString() {
return "Instructor{" +
"id=" + id +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", email='" + email + '\'' +
", instructorDetail=" + instructorDetail +
'}';
}
}
Course.class
#Entity
#Table(name = "course")
#Getter
#Setter
#NoArgsConstructor
public class Course {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private int id;
#Column(name = "title")
private String title;
#ManyToOne(cascade = {CascadeType.DETACH, CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH})
#JoinColumn(name = "instructor_id")
private Instructor instructor;
public Course(String title) {
this.title = title;
}
#Override
public String toString() {
return "Course{" +
"id=" + id +
", title='" + title + '\'' +
", instructor=" + instructor +
'}';
}
}
hibernate.cfg.xml
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- JDBC Database connection settings -->
<property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/hb-03-one-to-many?useSSL=false&serverTimezone=UTC</property>
<property name="connection.username"></property>
<property name="connection.password"></property>
<!-- JDBC connection pool settings ... using built-in test pool -->
<property name="connection.pool_size">1</property>
<!-- Select our SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Echo the SQL to stdout -->
<property name="show_sql">false</property>
<!-- Set the current session context -->
<property name="current_session_context_class">thread</property>
</session-factory>
</hibernate-configuration>
I found that it could be fixed by "inverse" attribute in some POJO mapping xml classes. But I don't use them and in lesson there is no using of this classes too.
Inverse attribute is normally used to let hibernate know which side is the relationship owner. In hibernate, only the 'relationship owner' should maintain the relation, means updating the foreign key column in case of any update. But in your case it is one-to-many bi directional in which case the inverse is by default true for the many side. You can try manually mentioning inverse=true in the courses side though it is not actually necessary.
I have a Spring Boot application that needs adds a post to a feed list. A post is written by a user and consists of a content and several attachments. The database has 3 tables: post, attachment and user.
The main class of the application is:
#SpringBootApplication
public class SocialMediaApplication {
public static void main(String[] args) {
SpringApplication.run(SocialMediaApplication.class, args);
}
}
The entities are the following:
Post.java
#Entity
public class Post implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#Column(nullable = false)
private String content;
#ManyToOne
#JoinColumn(name = "user_id")
private User user;
#Column(nullable = false)
private Timestamp createdAt;
#Column
private String location;
#OneToMany(mappedBy = "post", cascade = CascadeType.ALL)
private List<Attachment> attachmentList;
#OneToMany(mappedBy = "post", cascade = CascadeType.ALL)
private List<Rating> ratingList;
public Post() {
}
public Post(String content, User user, Timestamp createdAt, String location, List<Attachment> attachmentList, List<Rating> ratingList) {
super();
this.content = content;
this.user = user;
this.createdAt = createdAt;
this.location = location;
this.attachmentList = attachmentList;
this.ratingList = ratingList;
}
// ...
}
Attachment.java
#Entity
public class Attachment implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#Lob
#Column(length = 100_000, nullable = false)
private byte[] content;
#ManyToOne
#JoinColumn(name = "post_id")
private Post post;
public Attachment() {
}
public Attachment(byte[] content, Post post) {
super();
this.content = content;
this.post = post;
}
// ...
}
User.java
#Entity
public class User implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue
private Long id;
#Column(nullable = false)
private String firstName;
#Column(nullable = false)
private String lastName;
#Column(nullable = false)
private Date dateOfBirth;
#Column(nullable = false)
private String credential;
#Column(nullable = false)
private String password;
#Column
private String location;
#Lob
#Column(length = 100_000)
private byte[] photo;
#Column
private String motto;
public User() {
}
public User(String firstName, String lastName, Date dateOfBirth, String credential, String password,
String location, byte[] photo, String motto) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.dateOfBirth = dateOfBirth;
this.credential = credential;
this.password = password;
this.location = location;
this.photo = photo;
this.motto = motto;
}
// ...
}
All repositories extend CrudRepository and are annotated with #Transactional:
PostRepository.java
#Transactional
public interface PostRepository extends CrudRepository<Post, Long> {
}
AttachmentRepository.java
#Transactional
public interface AttachmentRepository extends CrudRepository<Attachment, Long> {
}
UserRepository.java
#Transactional
public interface UserRepository extends CrudRepository<User, Long> {
}
The controller that should add a post to the feed is the following:
#Controller
#RequestMapping("/post")
public class PostController {
#Autowired
PostRepository postRepository;
#GetMapping("/add")
public String greetingForm(Model model) {
model.addAttribute("post", new Post());
return "addPost";
}
#PostMapping("/add")
public String addPost(#ModelAttribute Post post, #RequestParam("attachment") MultipartFile uploadingFile) throws IOException {
User user = new User();
user.setId(1L);
post.setUser(user);
post.setCreatedAt(Timestamp.valueOf(LocalDateTime.now()));
List<Attachment> attachmentList = new ArrayList<>();
Attachment attachment = new Attachment();
attachment.setContent(uploadingFile.getBytes());
attachment.setPost(post);
attachmentList.add(attachment);
post.setAttachmentList(attachmentList);
List<Rating> ratingList = new ArrayList<>();
post.setRatingList(ratingList);
postRepository.save(post);
return "allPosts";
}
}
The addPost.html page has the following content:
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Add Post</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<h1>Add Post</h1>
<form action="#" th:action="#{/post/add}" th:object="${post}" method="post" enctype="multipart/form-data">
<table border="0">
<tr>
<td>Content</td>
<td><textarea id="content" th:field="*{content}" rows="5" cols="50"></textarea></td>
</tr>
<tr>
<td>Location</td>
<td><input type="text" id="location" th:field="*{location}"/></td>
</tr>
<tr>
<td>Attachment</td>
<td><input type="file" id="attachment" name="attachment"/></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Submit" />
<input type="reset" value="Reset" />
</td>
</tr>
</table>
</form>
</body>
</html>
The application.properties file has the following content:
spring.datasource.url=jdbc:mysql://localhost:3306/****?useSSL=false
spring.datasource.username=root
spring.datasource.password=****
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.properties.hibernate.id.new_generator_mappings=false
spring.jpa.show-sql=true
spring.thymeleaf.cache=false
spring.thymeleaf.enabled=true
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
However, when I press the submit button, nothing is persisted into the database, although the queries are being displayed in the console:
Hibernate: insert into post (content, created_at, location, user_id) values (?, ?, ?, ?)
Hibernate: insert into attachment (content, post_id) values (?, ?)
What could be the cause?
I'd like someone could explication about converter in spring mvc.
My domain class:
#Entity
#Table(name = "TIME_SHEET")
public class TimeSheet implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "ID_TIME_SHEET")
private Long id;
#NotNull(message = "timesheet.cadastro.horainicio.obrigatorio")
#Temporal(TemporalType.TIME)
#Column(name = "INICIO", nullable = false)
private Date horaInicio;
#NotNull(message = "timesheet.cadastro.horafim.obrigatorio")
#Temporal(TemporalType.TIME)
#Column(name = "FIM", nullable = false)
private Date horaFim;
#Column(name = "LATITUDE", nullable = true)
private Double latitude;
#Column(name = "LONGITUDE", nullable = true)
private Double longitude;
#Size(max = 300,message = "timesheet.cadastro.observacao.acimaDoPermitido")
#Column(name = "OBSERVACAO", nullable = true)
private String observacao;
//#NotNull(message = "timesheet.cadastro.dia.obrigatorio")
#ManyToOne(cascade = javax.persistence.CascadeType.ALL)
#JoinColumn(name = "ID_DIAS")
private Dias dia;
//#NotNull(message = "timesheet.cadastro.usuario.obrigatorio")
#ManyToOne(cascade = javax.persistence.CascadeType.ALL)
#JoinColumn(name = "ID_USUARIO")
private Usuario usuario;
...
My class converter:
public class IdToUsuarioConverter implements Converter<String, Usuario> {
#Autowired
private IusuarioService usuarioService;
public Usuario convert(String id) {
return usuarioService.buscaPorId(Long.valueOf(id));
}
}
In my springmvc.xml:
<mvc:annotation-driven conversion-service="conversionService"/>
<bean id="conversionService"
class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<set>
<bean class="br.com.infowhere.timeSheet.converter.IdToUsuarioConverter"/>
</set>
</property>
</bean>
I don't have problem, but my question is:
1-) When my converter will act ?
2-) My .jsp will post a form where I have one list similar:
<form:select path="user" items="${userList}" multiple="false" />
HTML:
<select id="user" name="user">
<option value="1">User 1</option>
<option value="2">User 2</option>
</select>
At what time my converter will work ?
I'm sorry but I'm trying to understand about converter.
thanks !!!
Your converter will convert id's to Usario objects in your controllers.
For example:
#Controller
public class MyController {
#RequestMapping("/showUsario")
public String showUsario(#RequestParam("id") Usario usario, Model model) {
model.addAttribute("usario", usario);
return "showUsario";
}
}
Then a request to /showUsario?id=123 will convert String "123" to Usario using the converter. If you didn't have a converter you would have to put String id (instead of Usario) in method parameters and manually convert the id to Usario. This way, Spring does it for you using your converter.
I was building an simple application using spring roo. After doing certain job, I have removed roo completely.
So here is my controller methods for creating new data..
#RequestMapping(params = "form", produces = "text/html")
public String createForm(Model uiModel) {
populateEditForm(uiModel, new PatientDetails());
return "patientdetailses/create";
}
#RequestMapping(method = RequestMethod.POST, produces = "text/html")
public String create(#Valid PatientDetails patientDetails,
BindingResult bindingResult, Model uiModel,
HttpServletRequest httpServletRequest) {
if (bindingResult.hasErrors()) {
populateEditForm(uiModel, patientDetails);
return "patientdetailses/create";
}
uiModel.asMap().clear();
patientDetailsService
.savePatientDetails(setCurrentUser(patientDetails));
return "redirect:/patientdetailses/"
+ encodeUrlPathSegment(patientDetails.getId().toString(),
httpServletRequest);
}
void populateEditForm(Model uiModel, PatientDetails patientDetails) {
uiModel.addAttribute("patientDetails", patientDetails);
addDateTimeFormatPatterns(uiModel);
uiModel.addAttribute("sexes", Arrays.asList(Sex.values()));
uiModel.addAttribute("typeOfPatients",
typeOfPatientService.findAllTypeOfPatients());
}
my domain:
public class PatientDetails {
#NotNull
#NotBlank
#NotEmpty
#Size(max = 40)
private String firstName;
#NotNull
#NotBlank
#NotEmpty
#Size(max = 40)
private String lastName;
#Size(max = 40)
private String middleName;
#Size(max = 200)
#NotNull
#NotBlank
#NotEmpty
private String address;
#NotNull
#NotBlank
#NotEmpty
private String city;
#NotNull
private String province;
#NotNull
#Size(max = 5)
private String postalCode;
#NotNull
#Email
#Size(max = 100)
private String email;
#Size(max = 12)
private String homePhone;
#Size(max = 12)
private String workPhone;
#NotNull
private Sex sex;
#Past
#Temporal(TemporalType.TIMESTAMP)
#DateTimeFormat(style = "M-")
#NotNull
private Date dateOfBirth;
#NotNull
#Size(max = 10)
private String socialSecurityName;
#NotNull
#Size(max = 100)
private String occupation;
#ManyToOne
private TypeOfPatient typeOfPatient;
#ManyToOne
private User users;
}
and the views :
<div xmlns:c="http://java.sun.com/jsp/jstl/core" xmlns:field="urn:jsptagdir:/WEB-INF/tags/form/fields" xmlns:form="urn:jsptagdir:/WEB-INF/tags/form" xmlns:jsp="http://java.sun.com/JSP/Page" xmlns:spring="http://www.springframework.org/tags" version="2.0">
<jsp:directive.page contentType="text/html;charset=UTF-8"/>
<jsp:output omit-xml-declaration="yes"/>
<form:create id="fc_com_simplemed_npc_domain_PatientDetails" modelAttribute="patientDetails" path="/patientdetailses" render="${empty dependencies}" z="8/olU0ivxZlcCzNCDYriOP+hE2U=">
<field:input field="firstName" id="c_com_simplemed_npc_domain_PatientDetails_firstName" required="true" z="user-managed"/>
<field:input field="lastName" id="c_com_simplemed_npc_domain_PatientDetails_lastName" required="true" z="user-managed"/>
<field:input field="middleName" id="c_com_simplemed_npc_domain_PatientDetails_middleName" z="user-managed"/>
<field:textarea field="address" id="c_com_simplemed_npc_domain_PatientDetails_address" required="true" z="0CYYBU4YKijB7hQ3Npq7QXHb2ys="/>
<field:input field="city" id="c_com_simplemed_npc_domain_PatientDetails_city" required="true" z="pQoSTWOVKlwKWZV5OlKvsCwQt6M="/>
<field:input field="province" id="c_com_simplemed_npc_domain_PatientDetails_province" required="true" z="7hzMJ6GrQfV6YMHTSNpUIw2z508="/>
<field:input field="postalCode" id="c_com_simplemed_npc_domain_PatientDetails_postalCode" max="5" required="true" z="QttQ/Av8Y2LXLPjpc88NRqtu7kI="/>
<field:input field="email" id="c_com_simplemed_npc_domain_PatientDetails_email" required="true" validationMessageCode="field_invalid_email" z="user-managed"/>
<field:input field="homePhone" id="c_com_simplemed_npc_domain_PatientDetails_homePhone" max="12" z="pBKxDLFxHZKsvHUjMqozutbbkug="/>
<field:input field="workPhone" id="c_com_simplemed_npc_domain_PatientDetails_workPhone" max="12" z="LViJ3WNDosJPBWk6AGJmcZrnjfw="/>
<field:select field="sex" id="c_com_simplemed_npc_domain_PatientDetails_sex" items="${sexes}" path="sexes" required="true" z="OjuzCMOizRZlHrPGgWVrV6wnR0k="/>
<field:datetime dateTimePattern="${patientDetails_dateofbirth_date_format}" field="dateOfBirth" id="c_com_simplemed_npc_domain_PatientDetails_dateOfBirth" past="true" required="true" z="tthi2TXacQkSlyRj+QX9HsbzaIs="/>
<field:input field="socialSecurityName" id="c_com_simplemed_npc_domain_PatientDetails_socialSecurityName" max="10" required="true" z="lKuMt6y/W4VI1dJEiW3gk5ZvK3c="/>
<field:textarea field="occupation" id="c_com_simplemed_npc_domain_PatientDetails_occupation" required="true" z="WfCTmH7Nkt3bMfkJ1HNpkqe+aa8="/>
<field:select field="typeOfPatient" id="c_com_simplemed_npc_domain_PatientDetails_typeOfPatient" itemValue="id" itemLabel="patientTypeName" required="true" items="${typeOfPatients}" path="/typeofpatients" z="Uj2xfoaPX5/gkwXb9WBxdzAfN/4="/>
</form:create>
<form:dependency dependencies="${dependencies}" id="d_com_simplemed_npc_domain_PatientDetails" render="${not empty dependencies}" z="OEZW6AYtVJ5mEmMbn24lHjWtPp4="/>
I'm getting errors while submitting forms
Can anyone please help me on this...
Thanks in Advance.
Edit:
TypeOfPatient Class:
public class TypeOfPatient {
#NotNull
private String patientTypeName;
#NotNull
#Size(max=1024)
private String decriptions;
#Override
public String toString() {
return patientTypeName;
}
}
My Conversion Code :
#Autowired
TypeOfPatientService typeOfPatientService;
public Converter<String, TypeOfPatient> getStringToTypeOfPatientConverter() {
return new Converter<String, TypeOfPatient>() {
#Override
public TypeOfPatient convert(String id) {
return typeOfPatientService.findTypeOfPatient(Long
.parseLong(id));
}
};
}
You basically have to provide a Converter.
EDIT:
According to your comments you use <mvc:annotation-driven conversion-service="applicationConversionService"/>. If that's something like this class, below code should work:
public class ApplicationConversionServiceFactoryBean
extends FormattingConversionServiceFactoryBean {
#Autowired
TypeOfPatientService typeOfPatientService;
#Override
protected void installFormatters(FormatterRegistry registry) {
registry.addConverter(getStringToTypeOfPatientConverter());
super.installFormatters(registry);
}
public Converter<String, TypeOfPatient> getStringToTypeOfPatientConverter() {
return new Converter<String, TypeOfPatient>() {
#Override
public TypeOfPatient convert(String id) {
return typeOfPatientService.findTypeOfPatient(Long.parseLong(id));
}
};
}
}
I'm trying to save Account object in the hibernate .please find the following code.
#RequestMapping(value = "/saveAccount", method = RequestMethod.POST)
public ModelAndView saveAccount(#ModelAttribute("account") Account account,
BindingResult result) {
Session session = sessionFactory.openSession();
System.out.println(account.getFirstName());
System.out.println(account.getLastName());
System.out.println(account.getSubject());
System.out.println(account.getCity().getCityName());
session.save(account);
return new ModelAndView("redirect:/form.html");
}
My jsp page have a form with First Name,Last Name ,city and subject fields.
I'm getting city dropdown fromatabase.
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib
prefix="c"
uri="http://java.sun.com/jsp/jstl/core"
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h3>Contact Form</h3>
<div class="container">
<form method="post" action="/sdnext/saveAccount.html">
<label for="fname">First Name</label>
<input type="text" id="fname" name="firstName" placeholder="Your name..">
<label for="lname">Last Name</label>
<input type="text" id="lname" name="lastName" placeholder="Your last name..">
<label for="country">City</label>
<select name="city" id="cityName" >
<c:forEach var="cityname" items="${lists}">
<option value="${cityname.cityName}">${cityname.cityName}</option>
</c:forEach>
</select>
<label for="subject">Subject</label>
<textarea id="subject" name="subject" placeholder="Write something.." style="height:200px"></textarea>
<input type="submit" value="Submit">
</form>
</div>
</body>
</html>
DataBase bean classes are here
package test.*;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.Table;
#Entity
#Table(name= "Account")
public class Account implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
public int getId() {
return id;
}
public void setId(int 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) {
LastName = lastName;
}
public City getCity() {
return city;
}
public void setCity(City city) {
this.city = city;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
private String firstName;
private String LastName;
#OneToOne
private City city;
private String subject;
}
package test.*;
#Entity
#Table(name= "City")
public class City implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
private String cityName;
public String getCityName() {
return cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
}
I have used one to one mapping to city object.But i'm not able to save city object in database,rest all firstNme,LastName and subjects are getting saved.its showing in network console,but data is not getting saved in database.Please help me fix this.Thanking you..
By creating the dto we can persists the values selected from the dropdown.and its working for me .
<option value="${cityname}">${cityname.cityName}</option>
The problem is you are sending cityname.cityName (String) which cannot be mapped to City object so,
send the complete city object as the value. Hibernate will take care of mapping.