I have been now trying for many days to insert data into database using restful webservices but with no luck. I have a Service.java controller and three model classes (Candidate.java, Kysymykset.java, Vastaukset.java and VastauksetPK(the primary key class for vastaukset table)) "Candidate" and "Kysymykset" have a one to many relation with "Vastaukset".
In the controller I have one function that reads all the question from the Kysymykset table and print them for the user using a jsp form (candQues.jsp) and this function works fine. However, when I try to answer the question that are in the same form the "/addAnswer" function just doesn't add them to the database table "vastaukset".
keep in mind that I am trying to retrieve the "candidate_id" and "kysymykset_id" from the "candidate" table and the "kysymykset" table respectively.
I tried to use request. getParameter and also formparams.getFirst in different ways but apparently I have yet to understand the proper way to implement it. Any help and suggestion would be much appreciated.
Below I added the "addAnswer" function along with the jsp form and the vastaukset table class.
Below is the service.java:
..code
#POST
#Path("/addAnswer")
// #Produces(MediaType.TEXT_HTML)
#Consumes("application/x-www-form-urlencoded")
public void addAnswer(MultivaluedMap <String, String> formparams, #Context HttpServletRequest request, #Context HttpServletResponse response)
throws IOException, ServletException {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("electionMachine");
EntityManager em = emf.createEntityManager();
// int kysymykset = Integer.parseInt(request.getParameter("kysymykset_id"));
try {
int candidate_id = Integer.parseInt(formparams.getFirst("candidate_id"));
int kysymys_ID = Integer.parseInt(formparams.getFirst("kysymys_ID"));
int vastaus = Integer.parseInt(formparams.getFirst("kysymys"));
String kommentti = formparams.getFirst("kommentti");
// System.out.println(" "+kommentti+" "+vastaus+" "+candidate_id+" ");
Vastaukset vas = new Vastaukset();
vas = new Vastaukset(candidate_id, kysymys_ID, vastaus, kommentti);
Kysymykset k = new Kysymykset();
k.setKysymys_ID(kysymys_ID);
vas.setKysymykset(k);
em.getTransaction().begin();
em.persist(vas);
em.getTransaction().commit();
em.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
..code
Vastaukset.java:
..code
#NamedQuery(name="Vastaukset.findAll", query="SELECT v FROM Vastaukset v")
public class Vastaukset implements Serializable {
private static final long serialVersionUID = 1L;
#EmbeddedId
private VastauksetPK id;
private String kommentti;
private int vastaus;
//bi-directional many-to-one association to Candidate
#ManyToOne
#JoinColumn(name="candidate_id")
private Candidate candidate;
//bi-directional many-to-one association to Kysymykset
#ManyToOne
#JoinColumn(name="kysymys_ID")
private Kysymykset kysymykset;
public Vastaukset() {
}
public Vastaukset(int candidate_id, int kysymys_ID, int vastaus, String kommentti) {
// TODO Auto-generated constructor stub
try {
this.candidate.setCandidate_id(candidate_id);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
this.kysymykset.setKysymys_ID(kysymys_ID);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.vastaus=vastaus;
this.kommentti=kommentti;
}
public Vastaukset(int candidate_id, int vastaus, String kommentti) {
// TODO Auto-generated constructor stub
this.candidate.setCandidate_id(candidate_id);
this.vastaus=vastaus;
this.kommentti=kommentti;
}
//getters and setters..
candQues.jsp:
..code
<h1>Candidate Questions Form</h1>
<br>
<form action='/rest/service/addAnswer' method='post'>
<input type="text" name="candidate_id"
value="${sessionScope.LoggedUser.candidate_id}">
<table>
<tr>
<td>CandidateID</td>
<td>QuestionsID</td>
<td>Questions</td>
</tr>
<c:forEach var="Kysymys" items="${requestScope.Kysymyslista}">
<tr>
<td>${sessionScope.LoggedUser.candidate_id}</td>
<td>${Kysymys.kysymys_ID}</td>
<td>${Kysymys.kysymys}</td>
<td><input type="radio" id="q1${Kysymys.kysymys_ID}"
name="kysymys${Kysymys.kysymys_ID}" value="1"> <label
for="q1${Kysymys.kysymys_ID}">1</label><br></td>
<td><input type="radio" id="q2${Kysymys.kysymys_ID}"
name="kysymys${Kysymys.kysymys_ID}" value="2"> <label
for="q2${Kysymys.kysymys_ID}">2</label><br></td>
<td><input type="radio" id="q3${Kysymys.kysymys_ID}"
name="kysymys${Kysymys.kysymys_ID}" value="3"> <label
for="q3${Kysymys.kysymys_ID}">3</label><br></td>
<td><input type="radio" id="q4${Kysymys.kysymys_ID}"
name="kysymys${Kysymys.kysymys_ID}" value="4"> <label
for="q4${Kysymys.kysymys_ID}">4</label><br></td>
<td><input type="radio" id="q5${Kysymys.kysymys_ID}"
name="kysymys${Kysymys.kysymys_ID}" value="5"> <label
for="q5${Kysymys.kysymys_ID}">5</label><br></td>
<td><input type="text"
name="kommentti${Kysymys.kysymys_ID}"
value="Add an Explanation">
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</c:forEach>
</table>
<br>
<br>
<table>
<tr>
<td><input type='submit' name='ok' value='Answer'
style="font-size: 30px"></td>
..code
I noticed too that I am not getting the "Kysymys_ID" from any where and I don't know whether I should be getting it since it is part of the "vastaukset" table, and if so, I don't know how. I am a beginner in IT and I know that this code is very messy. I hope you can bare with me and I am sorry in advance if this is not clear enough but I would be happy to clarify more in the comment section if needed.
Related
i am creating a simple crud system in Java Servlet. I am beginner of Servlet.I filled the form and clicked submit button and got the error - HTTP Status 404 - Not Found. I have attached the screen shot image below along with the code.
folder structure
Form
<form method = post action = "employee/employee.java">
<table class="table table-borederd">
<tr>
<td>Enter Employee ID:</td>
<td ><input class="form-control" type = "text" name = "txtEmpId"/></br></td>
</tr>
<tr>
<td>Enter Employee FirstName:</td>
<td ><input class="form-control" type = "text" name = "txtFName"/></td>
</tr>
<tr>
<td>Enter Employee LastName:</td>
<td ><input class="form-control" type = "text" name = "txtLName"/></td>
</tr>
<td><input type = "submit" value = "submit"/></td>
</form>
employee.java
public class employee extends HttpServlet
{
Connection con;
int row;
public void doPost(HttpServletRequest req, HttpServletResponse rsp) throws IOException, ServletException
{
try
{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost/empp","root","");
System.out.println("Connection Established");
}
catch(Exception e)
{
System.out.println("Sorry...........");
}
rsp.setContentType("text/html");
PrintWriter out = rsp.getWriter();
String empId = req.getParameter("txtEmpId");
String empFName = req.getParameter("txtFName");
String empLName = req.getParameter("txtLName");
try
{
PreparedStatement stat = con.prepareStatement("insert into record (id,fname,lname) Values(?,?,?)");
stat.setString(1,empId);
stat.setString(2,empFName);
stat.setString(3,empLName);
row = stat.executeUpdate();
}
catch(Exception e)
{
}
out.println("<html>");
out.println("<font color = 'red'>Sucessfully registered!</font>");
out.println("</body>");
out.println("<h2>");
out.println(row);
out.println("</h2>");
out.println("</body>");
}
}
I am quite new to hibernate frameworks and I am working on a Hibernate framework project in the netbeans IDE. I have a javadb that is connected to the project and I need to get the task list for each employee and display it as a bullet list in a <td> against each employee name. The following is the table displaying the employees' names and roles that are being fetched using the getEmployeeDetails method in the EmployeeHelper class.
Issue - The task list is always empty though I call the resultTaskList parameter that is passed from the Controller. - I know that I have to do an if conditional check for task within the nested forloop that will list the tasks to group them based on the employee names. But am not sure how to do an if within a jsp page.
Any suggestions on how to display the task list of each employee within the same table will be highly appreciated.
In this table, I intend to have the tasks pertaining to each employee as a bulletlist within each corresponding <td>.
Employee.jsp
...
<div class="content">
<!--Display table of roles with an edit button against each role-->
<form method="get" action="<%= request.getContextPath() %>/RoleController">
<br>
<table border ="2">
<thead class="thead-inverse">
<tr>
<th></th>
<th>Employee Name</th>
<th>Role</th>
<th>Tasks</th>
<th>Edit</th>
</tr>
</thead>
<tbody>
<c:forEach items="${result}" var="res">
<tr>
<th scope="row">
</th>
<td>
<c:out value="${res[0]}"></c:out>
</td>
<td>
<c:out value="${res[1]}"></c:out>
</td>
<td>
<c:out value="${resultTaskList[1]}"></c:out>
</td>
<td>
<input type="button" class="btn btn-info" value="Edit Role">
</td>
</tr>
</c:forEach>
</table>
</form>
</div>
...
EmployeeController.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
EmployeeHelper helper = new EmployeeHelper();
List<Employee> resultTaskList = helper.getEmployeeTasks();
request.setAttribute("resultTaskList", resultTaskList);
List<Employee> result = helper.getEmployeeDetails();
request.setAttribute("result", result);
request.getRequestDispatcher("Employee.jsp").forward(request, response);
}
EmployeeHelper.java
public class EmployeeHelper {
Session session = null;
public EmployeeHelper(){
this.session = HibernateUtil.getSessionFactory().openSession();
}
public List getEmployeeDetails(){
Transaction tx = this.session.beginTransaction();
List<Employee> employeeList = null;
try{
Query query = session.createQuery("select e.name, r.title from Employee as e, Role as r where e.employeeid=r.employeeid");
employeeList = (List<Employee>)query.list();
tx.commit();
}
catch(HibernateException ex){
ex.printStackTrace();
tx.rollback();
}
return employeeList;
}
public List getEmployeeTasks(){
Transaction tx = this.session.beginTransaction();
List<Employee> employeeTaskList = null;
try{
Query query = session.createQuery("select e.name, t.description from Employee as e, Role as r, Task as t, EmployeeTask as et where e.employeeid=r.employeeid and t.taskid=et.taskid and e.employeeid=et.employeeid");
employeeTaskList = (List<Employee>)query.list();
tx.commit();
}
catch(HibernateException ex){
ex.printStackTrace();
tx.rollback();
}
return employeeTaskList;
}
}
SQL Query executed within the getEmployeeTasks() method
instead of List employeeTaskList use List and iterate loop and set values in employee list try following code .
public List getEmployeeTasks(){
Transaction tx = this.session.beginTransaction();
List<Employee> employeeTaskList = null;
try{
session.beginTransaction();
Query query = session.createQuery("select e.name, t.description from Employee as e, Role as r, Task as t, EmployeeTask as et where e.employeeid=r.employeeid and t.taskid=et.taskid and e.employeeid=et.employeeid");
List<Object[]> result = (List<Object[]>) query.list();
if (null != result && result.size() != 0) {
for (Object[] obj : result) {
//Set values over here
employeeTaskList.set.....
}
tx.commit();
}
}
catch(HibernateException ex){
ex.printStackTrace();
tx.rollback();
}
return employeeTaskList;
}
These two lists are non-related as suggested by JB Nizet. Still You can do something like this.
<c:forEach items="${result}" var="res">
<tr>
<th scope="row">
</th>
<td>
<c:out value="${res[0]}"></c:out>
</td>
<td>
<c:out value="${res[1]}"></c:out>
</td>
<td>
<c:forEach items="${resultTaskList}" var="resultTaskList">
<c:if test = "${res[0] == resultTaskList[0]}">
<c:out value="${resultTaskList[1]}"></c:out>
</c:if>
</c:forEach>
</td>
<td>
<input type="button" class="btn btn-info" value="Edit Role">
</td>
</tr>
</c:forEach>
Hope this helps.
Im using Spring mvc and facing the problem about inserting data into two tables, my target is inserting data into 2 tables from 1 jsp (1 form)
I have two 2 tables:
1.Cars
Id
Name
CityId(FK)
2.City
Id
Name
this is my controller:
#RequestMapping(value="/CreateCar", method = RequestMethod.GET)
public ModelAndView getCreateCarPage(ModelMap model) throws ServletException, IOException {
try {
Car myCar = new Car();
City city = new City();
myCar.setCity(city);
model.addAttribute("city", city);
model.addAttribute("createCar", myCar);
}
catch(Exception e) {
e.printStackTrace();
}
return new ModelAndView("testForm");
}
#RequestMapping(value="/CreateCar", method = RequestMethod.POST)
public ModelAndView setCreateCarPage(ModelMap model,
#ModelAttribute("createCar") Car createCar) throws SQLException, Exception {
try {
carService.createCar(createCar);
}
catch(Exception e) {
e.printStackTrace();
}
return new ModelAndView("successProcess");
}
}
JSP:
<form:form modelAttribute="createCar" method="POST" commandName="createCar" action="/CreateCar" enctype="multipart/form-data">
<fieldset style="width:300px">
<table cellspacing="0" cellpadding="0" align="center">
<tr>
<td>
<label>Name of car</label>
<form:input path="name" id="name"/>
</td>
<td>
<label>Name of city</label>
<form:input path="city.name" />
</td>
</tr>
<tr>
<td><input class="btn btn-danger" type="submit" value="Inser New" style="width:100px;" /></td>
</tr>
</table>
</fieldset>
With above source, it just insert name of car success but can not insert name of city
Log massages:
SqlExceptionHelper - Column 'city_id' cannot be null
How can I fix this problem ? thank so much !
In my program, I am generating dynamic form names based on the number of feedbacks I get. I am then taking the satisfaction, comment and feedbackId inputs. They are different for each iteration. This is giving me an IllegalStateException error.
My HTML form is:
<form action="#" th:action="#{/heart2heart/token/__${tokenId}__/}" method="post">
<div class="table-responsive">
<table class="table table-striped table-bordered table-hover table-condensed">
<tr>
<th style="display:none;"></th>
<th th:text="#{service.desc}">Service</th>
<th th:text="#{feedback.description}">Feedback</th>
<th th:text="#{visit.date}">Date of Visit</th>
<th th:text="#{repr.name}">FU Repr</th>
<th th:text="#{resolution.response}">Response</th>
<th th:text="#{resolution.satisfactionLevel}">Satisfaction</th>
<th th:text="#{resolution.comment}">Comment</th>
</tr>
<tr th:each="feedback, feedbackStat : *{feedbacks}">
<td style="display:none;"><input type="hidden" th:field="*{feedbacks[__${feedbackStat.index}__].feedbackId}" th:value="${feedback.id}" /></td>
<td th:text="${feedback.service.description}">Steel</td>
<td th:text="${feedback.description}">Problem</td>
<td th:text="${feedback.visits[0].date}">12/08/2015</td>
<td th:text="${feedback.visits[0].repr.fullName}">XYZ</td>
<td th:text="${feedback.receipt.resolutions[0].response}">response</td>
<td>
<div class="radio">
<label><input type="radio" th:field="*{feedbacks[__${feedbackStat.index}__].satisfaction}" th:text="#{global.yes}" value="SATISFIED">Yes</input></label>
</div>
<div class="radio">
<label><input type="radio" th:field="*{feedbacks[__${feedbackStat.index}__].satisfaction}" th:text="#{global.no}" value="NOT SATISFIED">No</input></label>
</div>
</td>
<td><textarea th:field="*{feedbacks[__${feedbackStat.index}__].comment}" class="form-control" rows="2"></textarea></td>
</tr>
</table>
<div class="form-group">
<button type="submit" name="addRow" th:text="#{button.submit}"
class="btn btn-primary btn-md">Submit</button>
</div>
</div>
</form>
My controller is:
#RequestMapping(value = "/{tokenId}/", method = RequestMethod.POST)
public String addSatisfaction(#PathVariable int tokenId, #Valid ReceiptForm receiptForm, BindingResult result, Model model) {
try {
for (SatisfactionForm satisfactionForm : receiptForm.getFeedbacks()) {
Feedback feedback = new Feedback();
feedback.setId(satisfactionForm.getFeedbackId());
Feedback feedback1 = heart2heartService.getFeedbackById(feedback);
Resolution resolution = new Resolution();
resolution.setId(feedback1.getReceipt().getResolutions().get(0).getId());
resolution.setSatisfactionLevel(satisfactionForm.getSatisfaction().name());
resolution.setComment(satisfactionForm.getComment());
heart2heartService.addSatisfaction(resolution);
model.addAttribute("success", "Satisfaction added for tokenId " + tokenId);
}
} catch (Exception e) {
logger.error("Exception :: ", e);
}
return "success2";
}
#RequestMapping(value = "/{tokenId}/", method = RequestMethod.GET)
public String getSatisfaction(#PathVariable int tokenId, Model model) {
Token token = new Token();
token.setId(tokenId);
try {
model.addAttribute("feedbacks", heart2heartService.getFeedbacksByToken(token));
} catch (Exception e) {
logger.error("Exception :: ", e);
}
return "heart2heart/closeFeedback";
}
My forms are:
public class ReceiptForm {
private List<SatisfactionForm> feedbacks = new ArrayList<SatisfactionForm>();
public List<SatisfactionForm> getFeedbacks() {
return feedbacks;
}
public void setFeedbacks(List<SatisfactionForm> feedbacks) {
this.feedbacks = feedbacks;
}
}
and
public class SatisfactionForm {
public static enum Satisfaction {
NOT_SATISFIED, SATISFIED
}
private String comment;
private int feedbackId;
private Satisfaction satisfaction;
public String getComment() {
return comment;
}
public int getFeedbackId() {
return feedbackId;
}
public Satisfaction getSatisfaction() {
return satisfaction;
}
public void setComment(String comment) {
this.comment = comment;
}
public void setFeedbackId(int feedbackId) {
this.feedbackId = feedbackId;
}
public void setSatisfaction(Satisfaction satisfaction) {
this.satisfaction = satisfaction;
}
}
I am getting the following error:
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'feedbacks[0]' available as request attribute
How do I fix this?
You did not specify the form-backing bean in your Thymeleaf template.
You are using the *{} operator to access fields of the bean, but Thymeleaf does not know
which bean you want to use. To resolve the error, add a th:object to your form.
Assuming that heart2heartService.getFeedbacksByToken(token) returns a ReceiptForm your form would look like this:
<form action="#" th:action="#{/heart2heart/token/__${tokenId}__/}" method="post" th:object="${feedbacks}">
This question already has answers here:
getOutputStream() has already been called for this response
(15 answers)
Servlets in java - both getWriter() and getOutputStream()
(3 answers)
getting error "getOutputStream() has already been called for this response"
(1 answer)
JSP : getOutputStream() has already been called for this response
(2 answers)
Closed 2 years ago.
I have a program which uses spring mvc. I wrote two controllers which first one is for importing data and second one is for generating reports. I have a problem with generating controller. When user clicks generate button I want to generate report, save report on server hard disk and send report to user. When I am trying to save report on hard disk I've got Illegal state exception: Cannot call getWriter(), getOutputStream() already called. I searched for solution but I cannot find matched answer. This is my generator controller code:
#RequestMapping(value = "/generate", method = RequestMethod.POST)
public String generateReport(
Model model,
#Valid #ModelAttribute("reportProperties") ReportProperties reportProperties,
BindingResult result, HttpServletResponse response) {
if (result.hasErrors()) {
model.addAttribute("logMessage",
"Generowanie Raportu nie powiodlo sie.");
return "import";
}
//Walidacja dat. Mozna przeniesc na validator
if(reportProperties.getEndDate().compareTo(reportProperties.getStartDate()) < 0){
model.addAttribute("logMessage", "Data końcowa jest wcześniejsza od poprzedniej");
return "import";
}
XSSFWorkbook report = null;
if (reportProperties.getReportType().equalsIgnoreCase("tv")) {
report = tvReportGenerator.generate(reportProperties);
} else if (reportProperties.getReportType().equalsIgnoreCase("prod")) {
report = prodReportGenerator.generate(reportProperties);
} else {
report = totalReportGenerator.generate(reportProperties);
}
if (report != null) {
saveReportOnHardDrive(report);
sendReportToUser(report, response);
} else {
model.addAttribute("logMessage",
"Generowanie Raportu nie powiodlo sie.");
}
return "import";
}
private void saveReportOnHardDrive(XSSFWorkbook report) {
try {
Resource resource = new ClassPathResource("/general.properties");
Properties props = PropertiesLoaderUtils.loadProperties(resource);
String path = props.getProperty("saveFilePath");
FileOutputStream out = new FileOutputStream(new File(path
+ new Date() + ".xlsx"));
report.write(out);
out.close();
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
private void sendReportToUser(XSSFWorkbook report,
HttpServletResponse response) {
try {
response.setContentType("application/xlsx");
response.setHeader("Content-Disposition",
"attachment; filename=generate.xlsx");
report.write(response.getOutputStream());
response.flushBuffer();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I tried some solution with closing and flushing response OutputStream but it did not work.
This is my import.jsp file:
<body>
<div id="Container">
<h1>Mediaplany GigaShopping instrukcja</h1>
<h2>Import Mediaplanu pobierz szablon</h2>
<form method="POST" enctype="multipart/form-data"
action="/GigaShopping/importMediaplan">
<input type="file" name="mediaplanFile"/>
<input type="submit" value="Prześlij plik"/>
</form>
<h2>Import cennika aktualny cennik</h2>
<form method="POST" enctype="multipart/form-data"
action="/GigaShopping/importPriceList">
<input type="file" name="pricelistFile">
<input type="submit" value="Prześlij plik">
</form>
<h2>Generowanie raportów</h2>
<form:form method="POST" action="/GigaShopping/generate" commandName="reportProperties">
<table>
<tr>
<td>Typ raportu:</td>
<td>
<label><form:radiobutton path="reportType" value="tv"/> M/S TV</label>
<label><form:radiobutton path="reportType" value="prod"/> M/S PROD</label>
<label><form:radiobutton path="reportType" value="total"/> M/S TOTAL</label>
</td>
</tr>
<tr>
<td>Stacja</td>
<td>
<form:select path="tvName">
<form:options items="${televisionsList}"/>
</form:select>
</td>
</tr>
<tr>
<td>Od</td>
<td><form:input type="date" path="startDate" id="startDatePicker"/></td>
</tr>
<tr>
<td>Do</td>
<td><form:input type="date" path="endDate" id="endDatePicker"/></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Generuj"></td>
</tr>
</table>
</form:form>
<form:form method="POST" action="/GigaShopping/requestDBContent" commandName="requestProperties">
<form:input type="date" id="requestDatePicker" path="date"/>
<form:select path="tvName">
<form:option value="wszystkie">--wszystkie--</form:option>
<form:options items="${televisionsList}"/>
</form:select>
<input value="zobacz mediaplan" type="submit" name="requestMediaplanButton" />
<input value="zobacz zamówienia" type="submit" name="requestOrdersButton"/>
</form:form>
<span class="logMessage">${logMessage}</span>
<footer>
CNS 2015
</footer>
</div>
Thanks for any help.
Regards,
Sebatian
As #M. Deinum said
you have to return null instead of the name of page your are trying to forward..