How to insert the multiple value from select form into database? - java

My submission form:
<form method="post" action="${pageContext.request.contextPath }/">
<div>
<label>User:</label>
<select name="customer">
<option value="">Select Customer</option>
<c:forEach var="c" items="${ cList }">
<option value="${ c.id }">${ c.name }</option>
</c:forEach>
</select>
</div><br>
<div>
<label>Hobby:</label>
<select name="product" multiple size="8">
<!-- <option value="">Select Items</option> -->
<c:forEach var="p" items="${ pList }">
<option value = "${ p.id }">${ p.productName }</option>
</c:forEach>
</select>
</div>
<br><br>
<input type="submit" value="Send">
</form>
My Controller:
#RequestMapping(value = "/", method = RequestMethod.POST)
public String postHome(Model model, HttpServletRequest request, #ModelAttribute Transcation t){
transactionDao.addTransaction(t);
return "home";
}
In TransactionDaoImpl:
#Override
#Transactional
public void addTranscation(Transcation t) {
session = sessionFactory.openSession();
session.save(t);
session.close();
}
Based on your idea, what type of modifications do i have to make to perform insert operation.

Related

How to remove multiple rows via checkbox

I am new to spring and I need to be able to delete the selected rows by checkbox. How can I delete multiple rows from the database? I am using Thymeleaf as view.
Here is my code:
HTML
<div class="col-md-12">
<table class="table" id="tableImport">
<thead>
<tr>
<th scope="col">Remove</th>
<th scope="col">Debt Age Rule</th>
<th scope="col">Reminder</th>
<th scope="col">Frequency</th>
<th scope="col">Reorder</th>
</tr>
</thead>
<tbody>
<tr th:each="configCampaign:${listConfigCampaigns}">
<td>
<input type="checkbox" name="my-checkbox">
</td>
<td th:text="${configCampaign.debtagerule}"></td>
<td th:text="${configCampaign.remindebttype}"></td>
<td th:text="'Every '+${configCampaign.every} + ' ' + ${configCampaign.unit}"></td>
<td></td>
</tr>
</tbody>
</table>
<div class="col-md-12" style="text-align: center">
<input class="btn btn-primary" type="button" value="- Remove Selected Action(s)"/>
</div>
</div>
This table shows me data from an arrayList in memory, nothing with a database, I need to remove those selected objects from the array. At the moment I have my controller like this
Entity
private int configid;
private String debtagerule;
private String remindebttype;
private int every;
private String unit;
private boolean selected;
//getters and setters
In addition to the above, this is the controller with which I am currently working
Controller
#GetMapping("/deleteConfigureCampaign")
public String deleteConfig(#ModelAttribute ConfigCampaign configCampaign, Model model) {
listConfigCampaigns.remove(configCampaign);
return "redirect:/configureCampaign";
}
In Spring Boot, You have to use JpaRepository<> for delete data from database and need to understand structure of Spring Boot project.
Here is sturcture of Spring Boot project:
Entity -> Repository -> Service -> Controller -> View.
Here down is code:
Entity
#Table(name = "config_master")
public class ConfigCampaign {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer configid;
private String debtagerule;
private String remindebttype;
private Integer every;
private String unit;
private boolean selected;
// Constructor, Getter and Setter
}
Repository
Use of #Modifying annotation: It is used to enhance the #Query annotation so that we can execute not only SELECT queries, but also INSERT, UPDATE, DELETE, and even DDL queries
#Repository
public interface ConfigRepo extends JpaRepository<ConfigCampaign, Integer>{
#Modifying
#Transactional
#Query(nativeQuery = true, value = "DELETE FROM config_master WHERE configid IN(?1)")
void delConfig(List<Integer> configId);
}
Service
#Service
public class PojoServiceImpl{
#Autowired
private ConfigRepo configRepo;
#Override
public void delConfig(Integer[] configId) {
configRepo.delConfig(Arrays.asList(configId));
}
}
Controller
// Show table of Config Campaign
#RequestMapping(value = "/showconfig", method = RequestMethod.GET)
public String getConfig(Model mdl)
{
List<ConfigCampaign> getConfig = pojoService.getAllConfig();
mdl.addAttribute("config", getConfig);
return "showConfigCampaign";
}
// Delete item from Config Campaign
#RequestMapping(value = "/delcampaign", method = RequestMethod.GET)
public String deleteConfig(#RequestParam("cid") Integer[] configId)
{
pojoService.delConfig(configId);
return "redirect:/showconfig";
}
showConfigCampaign
You have to add configData.configid in checkbox.
<form th:action="#{/delcampaign}" th:object="${sconfig}">
<div class="container">
<div class="row">
<div class="col-sm-12">
<table class="table" style="text-align: center">
<thead>
<tr>
<th scope="col">Remove</th>
<th scope="col">Debt Age Rule</th>
<th scope="col">Reminder</th>
<th scope="col">Frequency</th>
</tr>
</thead>
<tbody>
<tr th:each="configData: ${config}">
<td><input type="checkbox" name="cid" th:value="${configData.configid}"/></td>
<td th:text="${configData.debtagerule}"></td>
<td th:text="${configData.remindebttype}"></td>
<td th:text="${configData.every}"></td>
</tr>
</tbody>
</table>
<input type="submit" value="Delete Users" />
</div>
</div>
</div>
</form>

Saving data of a html table in mysql table

In my system user will see a basic timetable view and he can add subjects by using a dropdown in each list.I need to store all the subjects in the timetable in a sql table. when a user selects a subject using a dropdown a new sql row should be created with start,end time,day and subject_code.Can someone please help
Add Time Table view
<!DOCTYPE html>
<html xmlns:th="https://www.thymeleaf.org">
<head>
<link rel="stylesheet" type="text/css" href="static/css/timeTableMapping.css" th:href="#{/css/timeTableMapping.css}">
<meta charset="UTF-8">
<title>Time Table</title>
</head>
<body>
</form>
<div class="container2">
<form action="#" th:action="#{/timeTableMapping/save}" th:object="${timeTableMapping}" method="post">
<table border="0" cell[adding="10">
<tr>
<td><h1>Time Table:</h1></td>
<td>
<select th:field="*{time_table_code}">
<option value="">Choose..</option>
<option th:each="timeTable: ${timeTables}" th:value="${timeTable.name}" th:text="${timeTable.name}"/>
</select>
</td>
</tr>
</table>
<table border="1" >
<thead>
<tr>
</tr>
<br>
<th></th>
<th:block th:each="day : ${days}">
<th th:text="${day.name}"></th>
</th:block>
</thead>
<tbody>
<th:block th:each="time : ${times}">
<tr>
<th th:text="${ time.start }+':00 - ' + ${ time.end }+':00'"></th>
<th:block th:each="day : ${days}">
<td>
<select th:field="*{subject_code}">
<option value=""></option>
<option th:each="subject: ${subjects}" th:value="${subject.subject_code}" th:text="${subject.name}"/>
</select>
</td>
</th:block>
</tr>
</th:block>
<tr>
<td colspan="2">
<button type="submit">Save</button>
</td>
</tr>
</tbody>
</table>
</form>
</div>
</body>
</html>
Controller
#Controller
public class TimeTableMappingController {
#Autowired
private TimeTableMappingDAO timeTableMappingDAO;
#Autowired
private TimeTableDAO timeTableDAO;
#Autowired
private SubjectDAO subjectDAO;
#Autowired
private StudentGroupDAO studentGroupDAO;
#Autowired
private DayDAO dayDAO;
#Autowired
private TimeDAO timeDAO;
#RequestMapping("/timeTableMapping")
public String viewHomePage(Model model){
List<TimeTableMapping> timeTableMappingDetails= timeTableMappingDAO.findAll();
model.addAttribute("timeTableMappingDetails",timeTableMappingDetails);
return "timeTableMapping";
}
#RequestMapping("/timeTableMapping/new")
public String addTimeTableMapping(Model model){
TimeTableMapping timeTableMapping =new TimeTableMapping();
model.addAttribute("timeTableMapping",timeTableMapping);
List<TimeTable> timeTableDetail = timeTableDAO.findAll();
model.addAttribute("timeTables", timeTableDetail);
List<Subject> subjectDetail = subjectDAO.findAll();
model.addAttribute("subjects", subjectDetail);
List<Day> dayDetails = dayDAO.findAll();
model.addAttribute("days",dayDetails);
List<Time> timeDetails = timeDAO.findAll();
model.addAttribute("times",timeDetails);
return "addTimeTableMapping";
}
#RequestMapping(value="/timeTableMapping/save",method= RequestMethod.POST)
public String saveTimeTable(#ModelAttribute("timeTableMapping") TimeTableMapping timeTableMapping){
timeTableMappingDAO.save(timeTableMapping);
return "redirect:/timeTableMapping";
}
#RequestMapping(value="/timeTableMapping/saveAll",method= RequestMethod.POST)
public String saveAll(#ModelAttribute("timeTable") TimeTable timeTable){
timeTableDAO.saveAll(timeTable);
return "redirect:/timeTable";
}
#RequestMapping("/timeTableMapping/edit/{id}")
public ModelAndView updateTimeTable(#PathVariable(name="id")Long id){
ModelAndView mav=new ModelAndView(("updateTimeTable"));
TimeTable timeTable = timeTableDAO.findById(id);
mav.addObject("timeTable",timeTable);
List<Subject> subjectDetails = subjectDAO.findAll();
mav.addObject("subjects", subjectDetails);
List<StudentGroup> studentGroupDetails = studentGroupDAO.findAll();
mav.addObject("studentGroups",studentGroupDetails);
List<Day> dayDetails = dayDAO.findAll();
mav.addObject("days",dayDetails);
List<Time> timeDetails = timeDAO.findAll();
mav.addObject("times",timeDetails);
return mav;
}
#RequestMapping("/timeTableMapping/delete/{id}")
public String deleteProduct(#PathVariable(name="id") Long id){
timeTableDAO.delete(id);
return "redirect:/timeTable";
}
}
I tried to do this but it seems what happens is trying to save all the data in the timeTable view in the same SQL record. And because of it, an error message occurs.
Exception:
There was an unexpected error (type=Internal Server Error, status=500).
could not execute batch; SQL [insert into timetablemappings (day, end, start, subject_code, time_table_code, id) values (?, ?, ?, ?, ?, ?)]; nested exception is org.hibernate.exception.DataException: could not execute batch
org.springframework.dao.DataIntegrityViolationException: could not execute batch; SQL [insert into timetablemappings (day, end, start, subject_code, time_table_code, id) values (?, ?, ?, ?, ?, ?)]; nested exception is org.hibernate.exception.DataException: could not execute batch
Caused by: com.mysql.cj.jdbc.exceptions.MysqlDataTruncation: Data truncation: Data too long for column 'subject_code' at row 1

populating thymeleaf dropdown with data of another table

i'm new to spring-boot. In my system there are two models named subject,course(two databases with the same names and connected by the foreign key course_id).I need to make it possible to select course name in a dropdown list in the addSubject thymeleaf form. Can someone please tell me how to do this
Subject.DAO file
#Service
public class SubjectDAO {
#Autowired
SubjectRepository subjectRepository;
//to save a subject
public Subject save(Subject subject){
return subjectRepository.save(subject);
}
//to search all subjects
public List<Subject> findAll(){
return subjectRepository.findAll();
}
//get a subject by id
public Subject findById(Long id){
return subjectRepository.findById(id).orElse(null);
}
//delete a subject
public void delete(Long id){
subjectRepository.deleteById(id);
}
}
Course.DAO file
#Service
public class CourseDAO {
#Autowired
CourseRepository courseRepository;
//to save a course
public Course save(Course course){
return courseRepository.save(course);
}
//to search all courses
public List<Course> findAll(){
return courseRepository.findAll();
}
//get a course by id
public Course findById(Long id){
return courseRepository.findById(id).orElse(null);
}
//delete a course
public void delete(Long id){
courseRepository.deleteById(id);
}
}
Subject Controller
#Controller
public class SubjectController {
#Autowired
private SubjectDAO subjectDAO;
#RequestMapping("/subject")
public String viewHomePage(Model model){
List<Subject> subjectDetails= subjectDAO.findAll();
model.addAttribute("subjectDetails",subjectDetails);
return "subject";
}
#RequestMapping("/subject/new")
public String addSubject(Model model){
Subject subject =new Subject();
model.addAttribute("subject",subject);
return "addSubject";
}
#RequestMapping(value="/subject/save",method= RequestMethod.POST)
public String saveCourse(#ModelAttribute("subject") Subject subject){
subjectDAO.save(subject);
return "redirect:/subject";
}
#RequestMapping("/subject/edit/{id}")
public ModelAndView updateSubjcet(#PathVariable(name="id")Long id){
ModelAndView mav=new ModelAndView(("updateSubject"));
Subject subject=subjectDAO.findById(id);
mav.addObject("subject",subject);
return mav;
}
#RequestMapping("/subject/delete/{id}")
public String deleteProduct(#PathVariable(name="id") Long id){
subjectDAO.delete(id);
return "redirect:/subject";
}
}
Subject html file
<!DOCTYPE html>
<html xmlns:th="https://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Adding a Subject</title>
</head>
<body>
<div align="center">
<h1>Add a new Subject</h1>
<br/>
<form action="#" th:action="#{/subject/save}" th:object="${subject}" method="post">
<table border="0" cell[adding="10">
<tr>
<td>Subject code:</td>
<td><input type="text" th:field="*{course_code}" /></td>
</tr>
<tr>
<td>Subject Name:</td>
<td><input type="text" th:field="*{name}" /></td>
</tr>
<tr>
<td>Course:</td>
<td>
<select>
<option value=""></option>
</select>
Z
</td>
</tr>
<tr>
<td colspan="2"><button type="submit">Save</button></td>
</tr>
</table>
</form>
</div>
</body>
</html>
So you want to load Course combo inside subject html
You need to modify subject controller
#RequestMapping("/subject")
public String viewHomePage(Model model){
List<Subject> subjectDetails= subjectDAO.findAll();
List<Course> courseDetail= courseDAO.findAll();
model.addAttribute("subjectDetails",subjectDetails);
model.addAttribute("courses",courseDetail);
return "subject";
}
In HTML
<tr>
<td>Course:</td>
<td>
<select th:field="*{course_code}">
<option value="">Choose..</option>
<option th:each="course: ${courses}" th:value="${course.id}" th:text="${course.name}" />
</select>
</td>
</tr>
<tr>
Edit 1:
I think you are loading addSubject.html
In that case you need to modify addSubject controller
#RequestMapping("/subject/new")
public String addSubject(Model model){
Subject subject =new Subject();
model.addAttribute("subject",subject);
List<Course> courseDetail= courseDAO.findAll();
model.addAttribute("courses",courseDetail);
return "addSubject";
}
Edit 2:
As per your code in Git I can see
#Autowired
private SubjectDAO subjectDAO;
private CourseDAO courseDAO;
It should be
#Autowired
private SubjectDAO subjectDAO;
#Autowired
private CourseDAO courseDAO;
First add all courses to the ModelMap
model.addAttribute("cources",courseDao.findAll());
Then use th:each attribute to populate select options
<select th:field="*{course}">
<option value="">Choose..</option>
<option th:each="c: ${cources}" th:value="${c.id}" th:text="${c.name}" />
</select>

Recover form in JAVA-Spring (with thymeleaf) from html page

I am new in development tool and i am trying to use spring with thymeleaf to create a form to register on a website. I am currently not able to recover information from the form to another page which only show the list of users.
I create a classic Spring boot security in Eclipse with model/service/dao/controller java files.
My Model java file --> Register.java
#Entity
public class Register {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String pseudo;
private String lastname;
private String firstname;
private String sex;
private String country;
private String phone;
private String spokenlanguages;
private String email;
private String password;
private String job;
private boolean premium;
public void updateRegister(String pseudo, String lastname, String firstname, String sex, String country, String phone,
String spokenlanguages, String email, String password, String job, boolean premium) {
this.pseudo = pseudo;
this.lastname = lastname;
this.firstname = firstname;
this.sex = sex;
this.country = country;
this.phone = phone;
this.spokenlanguages = spokenlanguages;
this.email = email;
this.password = password;
this.job = job;
this.premium = premium;
// with all the getters & setters
}
My Service java file --> RegisterService.java
public interface RegisterService {
public List<Register> list();
public Register getById(long id);
}
My Repository Java file --> RegisterRepository.java
#Repository
public interface RegisterRepository extends PagingAndSortingRepository<Register, Long> {}
My Controller Java file --> RegisterController.java
#Controller
public class RegisterController {
#Autowired
RegisterRepository registerRepository;
#RequestMapping(value="/register", method=RequestMethod.GET)
public String form (Model model) {
return "register/form";
}
#PostMapping("/register/add")
public String registerAdd(
#Valid Register register,
BindingResult result,
Model model) {
if (result.hasErrors()) {
return "redirect:/error";
}
else {
Register r = new Register();
r.updateRegister(register.getPseudo(),
register.getLastname(),
register.getFirstname(),
register.getSex(),
register.getCountry(),
register.getPhone(),
register.getSpokenlanguages(),
register.getEmail(),
register.getPassword(),
register.getJob(),
register.isPremium());
System.out.println(r);
registerRepository.save(r);
model.addAttribute("registerlist", registerRepository.findAll());
return "register/valid";
}
}
#RequestMapping(value="/register/valid", method=RequestMethod.GET)
public String list (Model model) {
return "redirect:/home";
}
}
My Form in HTML --> form.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org/">
<head>
<title>Formulaire d'inscription</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"
crossorigin="anonymous">
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"
integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
crossorigin="anonymous"></script>
</head>
<body>
<h1 class="register">Formulaire d'inscription</h1>
<form action="#" method="post" th:object="${register}" th:action="#{/register/add}">
<div class="form-group">
<label for="pseudo">Pseudo</label> <input type="text"
class="form-control" id="pseudo" placeholder="Pseudo"
th:field="*{pseudo}" required="required">
</div>
<div class="form-group">
<label for="lastname">Nom</label> <input type="text"
class="form-control" id="lastname" placeholder="Nom"
th:field="*{lastname}" required="required">
</div>
<div class="form-group">
<label for="firstname">Prénom</label> <input type="text"
class="form-control" id="firstname" placeholder="Prenom"
th:field="*{firstname}" required="required">
</div>
<div class="form-group radio">
<label for="sex">Sexe</label><br />
<label for="male">Homme<input
type="radio" class="form-control" id="sex" value="male"
th:field="*{sex}" required="required">
</label> <label for="female">Femme<input type="radio"
class="form-control" th:field="*{sex}" id="sex" value="female">
</label> <label for="other">Autre<input type="radio"
class="form-control" th:field="*{sex}" id="sex" value="other"></label>
</div>
<div class="form-group">
<label for="country">Pays</label> <br /> <select th:field="*{country}" required="required">
<option value="France" selected="selected">France</option>
....other countries...
</select>
</div>
<div class="form-group">
<label for="phone">Téléphone</label> <label
class="optional">(Facultatif)</label> <input type="text"
class="form-control" id="phone" placeholder="Téléphone" th:field="*{phone}">
</div>
<div class="form-group">
<label for="spokenlanguages">Langues parlées</label> <input
type="text" class="form-control" id="spokenlanguages"
placeholder="Langues" th:field="*{spokenlanguages}" required="required">
</div>
<div class="form-group">
<label for="email">Adresse Email</label> <input type="email"
class="form-control" id="email" aria-describedby="emailHelp"
placeholder="Email" th:field="*{email}" required="required">
</div>
<div class="form-group">
<label for="emailconf">Confirmez votre adresse Email</label> <input
type="email" class="form-control" id="emailconf"
aria-describedby="emailHelp" placeholder="" required="required">
</div>
<div class="form-group">
<label for="password">Mot de passe</label> <input type="password"
class="form-control" id="password" placeholder=""
th:field="*{password}" required="required">
</div>
<div class="form-group">
<label for="passwordconf">Confirmez votre mot de passe</label> <input
type="password" class="form-control" id="passwordconf"
placeholder="" required="required">
</div>
<div class="form-group">
<label for="job">Travail</label> <br /> <select id="job"
th:field="*{job}" required="required">
<option value="alexandre">Alexandre</option>
<option value="filmlover">Cinéphile</option>
<option value="scenarist">Scénariste</option>
<option value="productor">Producteur</option>
<option value="other">Autres</option>
</select>
</div>
<div class="form-group radio">
<label for="premium">Premium</label><br />
<label for="yes">Oui<input
type="radio" class="form-control" id="premium"
value="yes" th:field="*{premium}" required="required">
</label>
<label for="no">Non<input type="radio" class="form-control"
th:field="*{premium}" id="premium" value="no">
</label>
</div>
<input type="submit" class="btn btn-primary" id="valider" name="valider" value="Valider" />
</form>
<a href="../home" > <input class="btn btn-primary" type="reset" value="Annuler" /></a>
</body>
</html>
and my second HTML --> valid.html where i want to see at first now that the register was successful...but I got in this page this message --> org.thymeleaf.spring5.processor.SpringInputGeneralFieldTagProcessor and my trial sysout in the controller lead to an null values for everything except the id and the premium stuff (boolean)
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org/">
<head>
<title>Formulaire d'inscription</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"
crossorigin="anonymous">
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"
integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
crossorigin="anonymous"></script>
</head>
<body>
<h1 class="register">Confirmation de votre inscription</h1>
<!-- <h2 class ="register" th:text="${'Bienvenue ' + register.pseudo}"></h2> -->
<div class="container">
<div class="page-header" id="banner">
<div class="row">
<div class="col-lg-8 col-md-7 col-sm-6">
<h1>Utilisateurs</h1>
<table class="table table-striped table-hover">
<thead>
<tr>
<th>Id</th>
<th>Pseudo</th>
<th>Nom</th>
<th>Prénom</th>
<th>Sexe</th>
<th>Pays</th>
<th>Téléphone</th>
<th>Langues parlées</th>
<th>E-mail</th>
<th>Mot de passe</th>
<th>Travail</th>
<th>Premium</th>
</tr>
</thead>
<tbody>
<tr th:each="register : ${registerlist}">
<td th:text="${register.id}"></td>
<td th:text="${register.pseudo}"></td>
<td th:text="${register.lastname}"></td>
<td th:text="${register.firstname}"></td>
<td th:text="${register.sex}"></td>
<td th:text="${register.country}"></td>
<td th:text="${register.phone}"></td>
<td th:text="${register.spokenlanguages}"></td>
<td th:text="${register.email}"></td>
<td th:text="${register.password}"></td>
<td th:text="${register.job}"></td>
<td th:text="${register.premium}"></td>
<td th:text="${register.id}"></td>
</tr>
</tbody>
</table>
</div>
</div>
<a href="../home" > <input class="btn btn-primary" type="reset" value="Retour" /></a>
</body>
</html>
Thanks in advance for the help.
Feel free to ask me more in order to a better unterstanding...
Try to add #ModelAttribute("register") in your registerAdd method, so it should look like
#RequestMapping(value="/register/add", method=RequestMethod.POST)
public String registerAdd(#ModelAttribute("register") #Valid Register register, BindingResult result, Model model)
Let me know if it was the problem.
Edit1
Add this line to your GET mapping
model.addAttribute("register", new Register());
So it should look like:
#RequestMapping(value = "/register", method = RequestMethod.GET)
public String form(Model model) {
model.addAttribute("register", new Register());
return "register/form";
}
Hope it solves the problem :)

How to get data using an input form through a rest call?

I want to get the name and email address from a user through following form
<!-- Contatct Us-->
<section>
<div class="grey-bg">
<div class="container p-y-40">
<h1>Contact Us</h1>
<div class="row">
<div class="col-md-6">
<div class="form-horizontal contact-us" th:action="#{/contact-us}">
<div class="form-group">
<label for="FirstName" class="col-sm-3 control-label mandatory">Name</label>
<div class="col-sm-9">
<input type="text" class="form-control" th:value="${name}" placeholder=""/>
<input name="name" type="text" th:value="${name}" placeholder=""/>
<span th:text = "${name}"/>
</div>
</div>
<!-- -->
<div class="form-group">
<label for="Email" class="col-sm-3 control-label mandatory">Email</label>
<div class="col-sm-9">
<input type="email" class="form-control" th:value="${email}" placeholder=""/>
<input type="email" name="email" class="form-control" th:value="${email}" placeholder=""/>
</div>
</div>
<!-- -->
<div class="form-group">
<label for="Telephone" class="col-sm-3 control-label">Telephone</label>
<div class="col-sm-9">
<input type="text" class="form-control" th:value="${telephone}" placeholder=""/>
</div>
</div>
<!-- -->
<div class="form-group">
<label for="Message" class="col-sm-3 control-label ">Message</label>
<div class="col-sm-9">
<textarea class="form-control" rows="4" th:value="${message}"> </textarea>
</div>
</div>
<!-- -->
<div class="form-group">
<div class="col-sm-9 col-sm-offset-3 col-md-offset-3">
<input type="button" value="Send" class="btn btn-primary btn-flat w-min-120"
data-toggle="modal" data-target="#myModal" />
</div>
</div>
<!-- -->
</div>
</div>
<div class="col-md-6">
<iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d63371.792586563766!2d79.85603378454613!3d6.922006503004973!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x0%3A0x5f6f0f981a359f05!2sDialog+Axiata+PLC!5e0!3m2!1sen!2slk!4v1503969814382" width="100%" height="350" frameborder="0" style="border:0" allowfullscreen="true"></iframe>
</div>
</div>
</div>
</div>
</section>
I have used html and thymeleaf here. This is my controller. In the controller I want to pass parameters to the sendUserRegisterEmail method which I was taken from the user.
#Autowired
private EmailService emailService;
#ResponseBody
#RequestMapping(value = "/contact-us", method = RequestMethod.POST)
public String showContactForm(#RequestParam("name") String contactName, #RequestParam("email") String contactEmail) {
emailService.sendUserRegisterEmail(contactName, contactEmail);
return "index";
}
I wrote a DTO class as well.
public class ContactUsDto {
private String name;
private String email;
private String telephone;
private String message;
public ContactUsDto(String name, String email, String telephone, String message) {
this.name = name;
this.email = email;
this.telephone = telephone;
this.message = message;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
Currently I get no errors. But the email is not receiving. I have no any issues with the method which I used to send the email. Because I have used it in another instances. The only issue is passing form data to it. Please help me to resolve this
#RequestParam is used to pass the request parameters e.g.
http://example.com/path?name=myName&email=myEmail
Whereas #RequestBody is used to get the request's body, which in most cases for REST is a json (application/json) body. So your method will be
#ResponseBody
#RequestMapping(value = "/contact-us", method = RequestMethod.POST)
public String showContactForm(#RequestBody ContactUsDto contactUsDto ) {
emailService.sendUserRegisterEmail(contactUsDto.getContactName(), contactUsDto.getContactEmail());
return "index";
}
add to your input attibute name like this
<input type="email" name="email" class="form-control" th:value="${email}" placeholder=""/>
<input name="name" type="text" th:value="${name}" placeholder=""/>
and try again .

Categories