How can I make Ajax and Struts2 together? - java

I am a newbie and this is my first post, I am doing a simple project that combine ajax and struts. My code as below, my question is : After I got correct value(department) from Action on jsp page, the correct result will be refresh because of "return query;" in QueryAction.java, however, if I have to use "return query;" to get value for query.jsp....How can I solve it ?
query.jsp
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%# taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<s:head />
<title>Query Page</title>
<h1 align="center" id="h1"></h1>
</head>
<body>
<p id="demo"></p>
<s:include value="/msg.jsp" />
<s:form action="query" id="form">
<s:textfield name="name" id="name" label="Search the Department" />
<s:submit value="Search" onclick="return myFunction()" id="submitRowAdd" />
</s:form>
<table border="1" id="depTable">
<tr>
<td>Department ID</td>
<td>Department Name</td>
<td>Manager ID</td>
<td>Repeal</td>
</tr>
</table>
<br>
<script type="text/javascript">
var btnAdd = document.getElementById("form");
btnAdd.onsubmit = function(){
var txtTd = document.createTextNode("<s:property value="did"/>");
var eleTd = document.createElement("td");
eleTd.appendChild(txtTd);
var txtTd1 = document.createTextNode("<s:property value="dname"/>");
var eleTd1 = document.createElement("td");
eleTd1.appendChild(txtTd1);
var txtTd2 = document.createTextNode("<s:property value="mid"/>");
var eleTd2 = document.createElement("td");
eleTd2.appendChild(txtTd2);
var txtTd3 = document.createTextNode("<s:property value="rep"/>");
var eleTd3 = document.createElement("td");
eleTd3.appendChild(txtTd3);
var eleTr = document.createElement("tr");
eleTr.appendChild(eleTd);
eleTr.appendChild(eleTd1);
eleTr.appendChild(eleTd2);
eleTr.appendChild(eleTd3);
var theTable = document.getElementById("depTable");
theTable.appendChild(eleTr);
}
</script>
QueryAction.java
package actions;
import com.Department;
import com.opensymphony.xwork2.ActionSupport;
import service.DepartmentService;
import net.sf.json.JSONObject;
public class QueryAction extends ActionSupport {
private String name;
DepartmentService ds;
long did;
String dname;
String mid;
char rep;
private String result;
public String execute() {
if(name != null && !"".equals(name)) {
Long lname = Long.valueOf(name.trim());
Department ppp = ds.findById(lname);
if(ppp==null) {
return "sss";
}
//did = ppp.getDepartmentId();
//dname = ppp.getDepartmentName();
//mid = ppp.getManagerId();
//rep = ppp.getRepeal();
JSONObject json=JSONObject.fromObject(ppp); //I run debug it fail on here !
result=json.toString();
System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" + result);
} //return "result";
return SUCCESS;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public DepartmentService getDs() {
return ds;
}
public void setDs(DepartmentService ds) {
this.ds = ds;
}
public long getDid() {
return did;
}
public void setDid(long did) {
this.did = did;
}
public String getDname() {
return dname;
}
public void setDname(String dname) {
this.dname = dname;
}
public String getMid() {
return mid;
}
public void setMid(String mid) {
this.mid = mid;
}
public char getRep() {
return rep;
}
public void setRep(char rep) {
this.rep = rep;
}
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
}

Related

Problems with Glassfish5 and servlet

I'm relatively new to Java. Tried my first web application with server Tomcat, which went rather well. However, with another server Glassfish, problems arouse. After application deployment jsp doesn't connect to servlet, therefore error 404 appears. I added project structure and several classes. Any help appreciated.
empBean:
package app.bean;
import app.entity.Emp;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import java.util.List;
#Stateless
public class EmpBean {
#PersistenceContext(unitName = "DEVMODE")
private EntityManager em;
public Emp add(Emp emp) {
return em.merge(emp);
}
public Emp get(Integer empno) {
return em.find(Emp.class, empno);
}
public void update(Emp emp) {
add(emp);
}
public void delete(long empno){
em.remove(get((int) empno));
}
public List<Emp> getAll(){
TypedQuery<Emp> namedQuery = em.createNamedQuery("Emp.getAll", Emp.class);
return namedQuery.getResultList();
}
}
Emp:
package app.entity;
import javax.persistence.*;
import java.sql.Date;
#Entity(name="emp")
#NamedQuery(name = "Emp.getAll", query = "SELECT e from emp e")
public class Emp {
#Id
#Column(name="empno")
private Integer empno ;
#Column(name="ename")
private String ename;
#Column(name="job")
private String job;
#Column(name="mgr")
private Integer mgr;
#Column(name="hiredate")
private Date hiredate;
#Column(name="sal")
private Integer sal;
#Column(name="comm")
private Integer comm;
#Column(name="deptno")
private Integer deptno;
public Emp(Integer empno, String ename, String job, Integer mgr, Date hiredate, Integer sal, Integer comm, Integer deptno, String id) {
this.empno = empno;
this.ename = ename;
this.job = job;
this.mgr = mgr;
this.hiredate = hiredate;
this.sal = sal;
this.comm = comm;
this.deptno = deptno;
}
public Emp() {
}
public Integer getEmpno() {
return empno;
}
public void setEmpno(Integer empno) {
this.empno = empno;
}
public String getEname() {
return ename;
}
public void setEname(String ename) {
this.ename = ename;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
public Integer getMgr() {
return mgr;
}
public void setMgr(Integer mgr) {
this.mgr = mgr;
}
public Date getHiredate() {
return hiredate;
}
public void setHiredate(Date hiredate) {
this.hiredate = hiredate;
}
public Integer getSal() {
return sal;
}
public void setSal(Integer sal) {
this.sal = sal;
}
public Integer getComm() {
return comm;
}
public void setComm(Integer comm) {
this.comm = comm;
}
public Integer getDeptno() {
return deptno;
}
public void setDeptno(Integer deptno) {
this.deptno = deptno;
}
}
Select1Servlet:
package app.servlets;
import app.bean.DeptBean;
import app.bean.EmpBean;
import app.bean.SalgradeBean;
import app.entity.Dept;
import app.entity.Emp;
import app.entity.Salgrade;
import javax.ejb.EJB;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.io.PrintWriter;
import java.sql.*;
import java.util.ArrayList;
#WebServlet("/search")
public class Select1Servlet extends HttpServlet {
#EJB
private EmpBean empBean;
private DeptBean deptBean;
private SalgradeBean salgradeBean;
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html");
req.setCharacterEncoding("UTF-8");
req.getRequestDispatcher("/searchview.jsp").forward(req, resp);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException {
// response.setContentType("text/html");
PrintWriter out = response.getWriter();
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/users";
String userName = "root";
String password = "7777";
Statement st;
try {
// Class.forName("com.mysql.jdbc.Driver");
// conn = DriverManager.getConnection(url , userName, password);
System.out.println("Connected!");
String numb = request.getParameter("numb");
ArrayList al = null;
ArrayList pid_list = new ArrayList();
// String query = "SELECT emp.ename, emp.job, emp.sal, dept.dname, salgrade.grade FROM dept,emp,salgrade WHERE (emp.empno = '" + numb + "' ) AND (emp.deptno = dept.deptno) and (emp.sal BETWEEN losal and hisal) ";
// System.out.println("query " + query);
st = conn.createStatement();
// ResultSet rs = st.executeQuery(query);
Emp emp = empBean.get(Integer.valueOf(numb));
String ename= emp.getEname();
String job = emp.getJob();
Integer sal = emp.getSal();
Integer deptnoEmp= emp.getDeptno();
Dept dept = deptBean.get(Integer.valueOf(deptnoEmp));
String dname = dept.getDname();
Salgrade salgrade = salgradeBean.get(sal);
Integer grade = salgrade.getGrade();
// while (rs.next()) {
al = new ArrayList();
// out.println(rs.getString(1));
// out.println(rs.getString(2));
// out.println(rs.getString(3));
// out.println(rs.getString(4));
al.add(ename);
al.add(job);
al.add(sal);
al.add(dname);
al.add(grade);
System.out.println("al :: " + al);
pid_list.add(al);
// }
request.setAttribute("piList", pid_list);
RequestDispatcher view = request.getRequestDispatcher("/searchview.jsp");
view.forward(request, response);
conn.close();
System.out.println("Disconnected!");
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Returns a short description of the servlet.
* #return a String containing servlet description
*/
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
select1.jsp:
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title> Enter the number </title>
<link rel="stylesheet" href="design/w3.css">
</head>
<body>
<br/><br/>
<form method="post" name="frm" action="search">
<table border="0" width="375" align="center" class = "w3-pink w3-text-white" >
<tr><td colspan=2 style="font-size:12pt;" align="center">
<h3>Search User</h3></td></tr>
<br/>
<tr><td ><b>User Number</b></td>
<td>: <input type="number" name="numb" id="numb">
</td></tr>
<tr><td colspan=2 align="center">
<br/>
<input type="submit" name="submit" value="Search" onclick="form.action='/search';"></td></tr>
</table>
</form>
</body>
</html>
searchview.jsp:
<%# page import="java.util.*" %>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%--<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>--%>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title> List of emp </title>
<link rel="stylesheet" href="design/w3.css">
</head>
<body>
<form method="get" name="frm" action="searchview">
<table width="700px"
class = "w3-text-pink">
<tr>
<td colspan=5 align="center"
class = "w3-black w3-text-pink">
<b>User Record</b></td>
</tr>
<tr class = "w3-black ">
<td><b>User Name</b></td>
<td><b>Job</b></td>
<td><b>Sal</b></td>
<td><b>Dname</b></td>
<td><b>Grade</b></td>
</tr>
<%
int count = 0;
String color = "#ffffff";
if (request.getAttribute("piList") != null) {
ArrayList al = (ArrayList) request.getAttribute("piList");
System.out.println(al);
Iterator itr = al.iterator();
while (itr.hasNext()) {
if ((count % 2) == 0) {
color = "#ffffff";
}
count++;
ArrayList pList = (ArrayList) itr.next();
%>
<tr style="background-color:<%=color%>;">
<td><%=pList.get(0)%></td>
<td><%=pList.get(1)%></td>
<td><%=pList.get(2)%></td>
<td><%=pList.get(3)%></td>
<td><%=pList.get(4)%></td>
</tr>
<%
}
}
if (count == 0) {
%>
<tr>
<td colspan=5 align="center"
style="background-color:#ffffff"><b>No Record Found..</b></td>
</tr>
<% }
%>
</table>
</form>
</body>
</html>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<servlet>
<servlet-name>Select1</servlet-name>
<servlet-class>app.servlets.Select1Servlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Select1</servlet-name>
<url-pattern>/search</url-pattern>
</servlet-mapping>

Wicket Modal dialog, form validation in AjaxBootstrapTabbedPanel

I've to create a modal dialog which contains a AjaxBootstrapTabbedPanel with two or more tabs. All tabs belong to the same form.
Each tab contains required input fields, select boxes or drop down choices. Until now,
I don't use own validators, but this is a future task.
I was able to trigger the validation when switching between the tabs.
When I use the dialog like variant A and B, I get proper feedback from validation.
Variant A
open the dialog
closing the dialog via submit button immediately results in feedback message "please enter a value in field..."
Variant B
open the dialog
switch to another tab without filling required fields on initial tab gives
also "please enter a value in ..."
Variant C - validation problem
But using the dialog in this way doesn't result in feedback messages:
open the dialog
enter all required values on the initial tab
don't enter values in required fields on another tab
use the submit button to close the diaolg: no feedback message!!, but there has to be one or more
In Variant C, no logging output from the method BootstrapAjaxButton#onError() is printed.
I'm using Wicket 7.6.0 and Wicket-Bootstrap 0.10.11
Class for modal dialog
public abstract class OwsDetailsDialog extends Modal<Ows>
{
private static final long serialVersionUID = -8110788978602397064L;
private BootstrapAjaxButton createOwsBtn;
private BootstrapForm<Ows> owsForm;
public OwsDetailsDialog(String id,
IModel<Ows> owsModel)
{
super(id, owsModel);
setOutputMarkupPlaceholderTag(true);
setDefaultModel(owsModel);
owsForm = new BootstrapForm<>("owsForm");
owsForm.setOutputMarkupId(true);
add(owsForm);
List<ITab> tabs = createTabs(owsModel);
MyAjaxTabbedPanel tabbedPanel = new MyAjaxTabbedPanel("tabbedPanel", tabs);
owsForm.add(tabbedPanel);
createOwsBtn = new BootstrapAjaxButton("submitOws",
Model.of("Create"), Buttons.Type.Default)
{
#Override
protected void onError(AjaxRequestTarget target, Form<?> form)
{
super.onError(target, form);
target.add(form, tabbedPanel);
System.out.println("onError() at form ID " + form.getId() + " target.getPage() "
+ target.getPage());
}
#Override
protected void onSubmit(AjaxRequestTarget target, Form<?> form)
{
super.onSubmit(target, form);
System.out.println("click on create");
createOws(target, owsModel);
}
};
owsForm.add(createOwsBtn);
BootstrapAjaxButton cancelBtn = new BootstrapAjaxButton("cancelOws",
Model.of("Cancel"), Buttons.Type.Default)
{
#Override
protected void onSubmit(AjaxRequestTarget target, Form<?> form)
{
super.onSubmit(target, form);
cancel(target);
}
};
cancelBtn.setDefaultFormProcessing(false);
owsForm.add(cancelBtn);
//FeedbackPanel feedbackOwsDialog = new FeedbackPanel("feedbackOwsDialog");
//add(feedbackOwsDialog);
}
private List<ITab> createTabs(IModel<Ows> owsModel)
{
List<ITab> tabs = new ArrayList<>();
tabs.add(new AbstractTab(Model.of("Data 1"))
{
private static final long serialVersionUID = -9107223557866453561L;
#Override
public WebMarkupContainer getPanel(String panelId)
{
return new OwsMainInfoContainer(panelId, owsModel);
}
});
tabs.add(new AbstractTab(Model.of("Data 2"))
{
private static final long serialVersionUID = -7323530522820254738L;
#Override
public WebMarkupContainer getPanel(String panelId)
{
return new OwsSecondaryInfoContainer(panelId, owsModel);
}
});
return tabs;
}
protected class OwsMainInfoContainer extends Panel
{
private static final long serialVersionUID = -2965824809083715016L;
public OwsMainInfoContainer(
String panelId, IModel<Ows> owsModel)
{
super(panelId, owsModel);
add(new RequiredTextField<>("title"));
add(new RequiredTextField<>("url"));
List<OwsType> types = Arrays.asList(OwsType.values());
DropDownChoice<OwsType> dropDownChoice = new DropDownChoice<>("category", types,
new ChoiceRenderer<OwsType>()
{
private static final long serialVersionUID = 8139757791037487164L;
#Override
public Object getDisplayValue(OwsType owsType)
{
return owsType.getName();
}
});
add(dropDownChoice.setRequired(true));
add(new FeedbackPanel("feedbackMain"));
}
}
protected class OwsSecondaryInfoContainer extends Panel
{
private static final long serialVersionUID = -7396160769731997541L;
public OwsSecondaryInfoContainer(
String panelId, IModel<Ows> owsModel)
{
super(panelId, owsModel);
add(new DateTextField("firstPublished"));
add(new TextField<>("provider").setRequired(true));
add(new TextField("price").setRequired(true));
add(new FeedbackPanel("feedbackSecondary"));
}
}
protected abstract void createOws(AjaxRequestTarget target
, IModel<Ows> owsWithUtilDateIModel);
protected abstract void cancel(AjaxRequestTarget target);
// http://www.volkomenjuist.nl/blog/2009/12/01/ajaxtabbedpanel-store-state-when-switching-tabs/
class MyAjaxTabbedPanel extends AjaxBootstrapTabbedPanel<ITab>
{
private static final long serialVersionUID = 1513951445901529991L;
public MyAjaxTabbedPanel(String id, List<ITab> tabs)
{
super(id, tabs);
}
#Override
protected WebMarkupContainer newLink(String linkId, final int index)
{
return new AjaxSubmitLink(linkId, owsForm)
{
private static final long serialVersionUID = 7049548660275591812L;
#Override
protected void onSubmit(AjaxRequestTarget target, Form<?> form)
{
setSelectedTab(index);
if (target != null)
{
target.add(form);
}
onAjaxUpdate(target);
System.out.println("onSubmit() on target.getPage(): " + target.getPage());
}
#Override
protected void onError(AjaxRequestTarget target, Form<?> form)
{
MyAjaxTabbedPanel component = MyAjaxTabbedPanel.this;
target.add(component);
System.out.println("in onError() , target.add() on " + component.getId());
}
};
}
}
}
Class extending WebPage
public class MyPage extends WebPage
{
private static final long serialVersionUID = 6826446949682313116L;
public MyPage()
{
Form<Void> form = new Form<Void>("buttonForm");
add(form);
form.setOutputMarkupId(true);
OwsDetailsDialog owsDialog = new OwsDetailsDialog("owsDialog"
, new CompoundPropertyModel<Ows>(new Ows()))
{
#Override
protected void createOws(AjaxRequestTarget target,
IModel<Ows> model)
{
Ows ows = model.getObject();
System.out.println("object: "+ ows);
close(target);
}
#Override
protected void cancel(AjaxRequestTarget target)
{
System.out.println("click auf abbrechen");
close(target);
}
};
add(owsDialog);
BootstrapAjaxButton createOwsButton = new BootstrapAjaxButton("createOwsButton",
Model.of("OWS neu"), Buttons.Type.Default)
{
#Override
protected void onSubmit(AjaxRequestTarget target, Form<?> form)
{
super.onSubmit(target, form);
owsDialog.setDefaultModelObject(new Ows());
target.add(owsDialog);
TabbedPanel tabbedPanel = (TabbedPanel) owsDialog.get("owsForm:tabbedPanel");
tabbedPanel.setSelectedTab(0);
owsDialog.show(target);
}
};
form.add(createOwsButton);
}
}
PoJo
package example.tryOut.ows;
import java.util.Date;
public class Ows
{
private Integer index=0;
private String title = "";
private String provider = "";
private String url = "";
private OwsType category;
private Date firstPublished =null;
private Double price=0.0;
public Integer getIndex()
{
return index;
}
public void setIndex(Integer index)
{
this.index = index;
}
public String getTitle()
{
return title;
}
public void setTitle(String title)
{
this.title = title;
}
public String getProvider()
{
return provider;
}
public void setProvider(String provider)
{
this.provider = provider;
}
public String getUrl()
{
return url;
}
public void setUrl(String url)
{
this.url = url;
}
public OwsType getCategory()
{
return category;
}
public void setCategory(OwsType category)
{
this.category = category;
}
public Date getFirstPublished()
{
return firstPublished;
}
public void setFirstPublished(Date firstPublished)
{
this.firstPublished = firstPublished;
}
public Double getPrice()
{
return price;
}
public void setPrice(Double price)
{
this.price = price;
}
#Override
public String toString()
{
return "Ows{" +
"index=" + index +
", title='" + title + '\'' +
", provider='" + provider + '\'' +
", url='" + url + '\'' +
", category=" + category +
", firstPublished=" + firstPublished +
", price=" + price +
'}';
}
}
Markup
Page
<!DOCTYPE html>
<html xmlns:wicket="http://wicket.apache.org">
<head>
<meta charset="UTF-8">
</head>
<body>
<form wicket:id="buttonForm">
<button wicket:id="createOwsButton"></button>
</form>
<div wicket:id="owsDialog"></div>
</body>
</html>
Dialog
<!DOCTYPE html>
<html xmlns:wicket="http://wicket.apache.org">
<head>
<meta charset="UTF-8">
</head>
<body>
<wicket:extend>
<form wicket:id="owsForm">
<div wicket:id="tabbedPanel" class="container" style="width: inherit"></div>
<button type="submit" wicket:id="submitOws" class="btn btn-main">Anlegen</button>
<button type="reset" wicket:id="cancelOws" class="btn btn-main">Abbrechen</button>
</form>
</wicket:extend>
</body>
</html>
<!DOCTYPE html>
<html lang="en" xmlns:wicket="http://wicket.apache.org">
<head>
<meta charset="UTF-8">
</head>
<body>
<wicket:panel>
<div class="form-group">
<label wicket:for="url">URL</label>
<div class="controls">
<input type="text" wicket:id="url" class="form-control"/>
</div>
</div>
<div class="form-group">
<label wicket:for="title">Title</label>
<div class="controls">
<input type="text" wicket:id="title" class="form-control"/>
</div>
</div>
<div class="form-group">
<label wicket:for="category">OWS Category</label>
<div class="controls">
<select wicket:id="category">
<option value="">dummy1</option>
<option value="">dummy2</option>
</select>
</div>
</div>
<div wicket:id="feedbackMain"></div>
</wicket:panel>
</body>
</html>
<!DOCTYPE html>
<html lang="en" xmlns:wicket="http://wicket.apache.org">
<head>
<meta charset="UTF-8">
</head>
<body>
<wicket:panel>
<div class="form-group">
<label wicket:for="price">Price</label>
<div class="controls">
<input type="text" wicket:id="price" class="form-control"/>
</div>
</div>
<div class="form-group">
<label wicket:for="provider">Provider</label>
<div class="controls">
<input type="text" wicket:id="provider" class="form-control"/>
</div>
</div>
<div class="form-group">
<label wicket:for="firstPublished">First published</label>
<div class="controls">
<input type="date" wicket:id="firstPublished" class="form-control"/>
</div>
</div>
<div wicket:id="feedbackSecondary"></div>
</wicket:panel>
</body>
</html>

Error populating dropdown list from database - spring mvc - hibernate

I am new to java and am trying to write an application using spring-mvc and hibernate.
I am getting the error
"Caused by: java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'command' available as request attribute"
in a JSP file when I try to populate a dropdown list with elements from a database
#Controller
public class MetalController {
#Autowired
MtMetalService mtMetalService;
#Autowired
MtFormulaService mtFormulaService;
#RequestMapping(value = "/", method = RequestMethod.GET)
public ModelAndView homePage() {
ModelAndView model =new ModelAndView("homepage");
return model;
}
#RequestMapping(value = "/inputmetal.html", method = RequestMethod.GET)
public ModelAndView metalInputForm() {
MtFormula mtFormula = new MtFormula();
List<MtFormula> formulalist = mtFormulaService.getAll(mtFormula);
ModelAndView model =new ModelAndView("metalinput");
model.addObject(formulalist);
for (MtFormula x: formulalist) {
System.out.println(x.getFormulaCode());
}
return model;
}
#RequestMapping(value = "/metalviewinput.html", method = RequestMethod.GET)
public ModelAndView metalViewForm() {
ModelAndView model =new ModelAndView("metalviewinput");
return model;
}
#RequestMapping(value="/createmetal.html", method = RequestMethod.POST)
public ModelAndView createMetal(#ModelAttribute("mtMetal") MtMetal mtMetal) {
mtMetalService.persist(mtMetal);
ModelAndView model =new ModelAndView("redirect:/inputmetal.html?success=true");
return model;
}
#RequestMapping(value="/viewmetal.html", method={ RequestMethod.GET, RequestMethod.POST})
public ModelAndView McMetalView(
#RequestParam("MetalCode") String metalCode) {
MtMetal mtMetal = new MtMetal();
mtMetal = mtMetalService.getOne(mtMetal, metalCode);
ModelAndView model =new ModelAndView("metalview");
model.addObject("msg", "Metal input form");
model.addObject(mtMetal);
return model;
}
#RequestMapping(value = "/metallist.html", method={ RequestMethod.GET})
public ModelAndView metalListView() {
MtMetal mtMetal = new MtMetal();
List<MtMetal> mtMetalList = mtMetalService.getAll(mtMetal);
ModelAndView model = new ModelAndView("metallistview");
model.addObject(mtMetalList);
return model;
}
}
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib prefix="form" uri="http://www.springframework.org ags/form"%>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<form:form method="post" action="/labcontrol/createmetal.html">
<c:if test="${param.success eq true}"></c:if> Metal save - Successful
<table border=1>
<tr><th>Metal details entry form</th></tr>
<tr><td>Metal Code1 </td><td> <input type=text
name="metalCode"/></td></tr>
<tr><td>Metal Description </td><td> <input type=text
name="metalDesc"/></td></tr>
<tr><td>Metal Unit of measure </td><td> <input type=text
name="metalUnit"/></td></tr>
<tr><td>Loss Formula </td><td><form:select
path="formulalist">
<form:option
value="-" label="--Please Select"/>
<form:options
items="${formulalist}" itemValue="formulaCode"
itemLabel="formula"/>
</form:select> </td></tr>
<tr><td>Treatment recovery </td><td> <input type=number
name="treatmentRecovery"/></td></tr>
<tr><td>Salable mass </td><td> <input type=number
name="saleableMass"/></td></tr>
<tr><td>Pricing unit </td><td> <input type=number
name="pricePerUnit"/></td></tr>
<tr><td>Gross value </td><td> <input type=number
name="grossValue"/></td></tr>
<tr><td><input type="submit" value="Save record"></td></tr>
</table>
</form:form>
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib prefix="form" uri="http://www.springframework.org ags/form"%>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<form:form method="post" action="/labcontrol/createmetal.html">
<c:if test="${param.success eq true}"></c:if> Metal save - Successful
<table border=1>
<tr><th>Metal details entry form</th></tr>
<tr><td>Metal Code1 </td><td> <input type=text
name="metalCode"/></td></tr>
<tr><td>Metal Description </td><td> <input type=text
name="metalDesc"/></td></tr>
<tr><td>Metal Unit of measure </td><td> <input type=text
name="metalUnit"/></td></tr>
<tr><td>Loss Formula </td><td><form:select
path="formulalist">
<form:option
value="-" label="--Please Select"/>
<form:options
items="${formulalist}" itemValue="formulaCode"
itemLabel="formula"/>
</form:select> </td></tr>
<tr><td>Treatment recovery </td><td> <input type=number
name="treatmentRecovery"/></td></tr>
<tr><td>Salable mass </td><td> <input type=number
name="saleableMass"/></td></tr>
<tr><td>Pricing unit </td><td> <input type=number
name="pricePerUnit"/></td></tr>
<tr><td>Gross value </td><td> <input type=number
name="grossValue"/></td></tr>
<tr><td><input type="submit" value="Save record"></td></tr>
</table>
</form:form>}
Set the modelAttribute property on your form to the correct value.
<form:form modelAttribute="" >...
In your case it should be "mtMetal".
Always name your model attributes when adding them to your model, so that you know what to set in your form.
#Entity
public class MtMetal {
#Id
#GeneratedValue
private int metalId;
private String metalCode;
private String metalDesc;
private String metalUnit;
private double treatmentRecovery;
private double saleableMass;
private double pricePerUnit;
private double grossValue;
#OneToOne
private MtFormula lossFormula;
public MtFormula getLossFormula() {
return lossFormula;
}
public void setLossFormula(MtFormula lossFormula) {
this.lossFormula = lossFormula;
}
public double getTreatmentRecovery() {
return treatmentRecovery;
}
public void setTreatmentRecovery(double treatmentRecovery) {
this.treatmentRecovery = treatmentRecovery;
}
public double getSaleableMass() {
return saleableMass;
}
public void setSaleableMass(double saleableMass) {
this.saleableMass = saleableMass;
}
public double getPricePerUnit() {
return pricePerUnit;
}
public void setPricePerUnit(double pricePerUnit) {
this.pricePerUnit = pricePerUnit;
}
public double getGrossValue() {
return grossValue;
}
public void setGrossValue(double grossValue) {
this.grossValue = grossValue;
}
public String getMetalUnit() {
return metalUnit;
}
public void setMetalUnit(String metalUnit) {
this.metalUnit = metalUnit;
}
public int getMetalId() {
return metalId;
}
public void setMetalId(int metalId) {
this.metalId = metalId;
}
public String getMetalCode() {
return metalCode;
}
public void setMetalCode(String metalCode) {
this.metalCode = metalCode;
}
public String getMetalDesc() {
return metalDesc;
}
public void setMetalDesc(String metalDesc) {
this.metalDesc = metalDesc;
}
}
#Entity
public class MtFormula {
#Id
#GeneratedValue
private int formulaId;
private String formulaCode;
private String formulaDesc;
private double formulaRate;
public int getFormulaId() {
return formulaId;
}
public void setFormulaId(int formulaId) {
this.formulaId = formulaId;
}
public String getFormulaCode() {
return formulaCode;
}
public void setFormulaCode(String formulaCode) {
this.formulaCode = formulaCode;
}
public String getFormulaDesc() {
return formulaDesc;
}
public void setFormulaDesc(String formulaDesc) {
this.formulaDesc = formulaDesc;
}
public double getFormulaRate() {
return formulaRate;
}
public void setFormulaRate(double formulaRate) {
this.formulaRate = formulaRate;
}
}

I want to add "Edit" functionality. When I click Edit, it adds a duplicate record instead of editing

This is my Operations.java, products.Java class and Products.jsp file:
In which I implemented the Add and Edit functionality. The add button is working fine but the edit button is adding a duplicate record instead of editing the record. Please tell me how do I implement edit function in my program ?
package metier;
import java.util.ArrayList;
public class Operation {
private ArrayList<Produit> produits = new ArrayList<Produit>();
public ArrayList<Produit> getProduits() {
return produits;
}
public void setProduits(ArrayList<Produit> produits) {
this.produits = produits;
}
public void add(Produit p){
produits.add(p);
}
public void remove(Long id){
for(Produit p:produits){
if(p.getId()==id){ //equals
produits.remove(p);
break;
}
}
}
public void edit(Long id){
for(Produit p:produits){
if(p.getId()==id){
p.getId();
p.getName();
p.getContactno();
p.getSPS();
produits.add(p);
break;
}
}
}
public ArrayList getAll(){
return produits;
}
}
package metier;
public class Produit {
private Long id;
private String name, address, contactNo, SparePartsService;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getContactno() {
return contactNo;
}
public void setContactno(String contactNo) {
this.contactNo = contactNo;
}
public String getSPS() {
return SparePartsService;
}
public void setSPS(String SparePartsService) {
this.SparePartsService = SparePartsService;
}
public Produit() {
super();
// TODO Auto-generated constructor stub
}
public Produit(String name, String address, String contactNo, String SparePartsService) {
super();
this.name = name;
this.address = address;
this.contactNo = contactNo;
this.SparePartsService = SparePartsService;
}
public Produit(Long id, String name, String address, String contactNo, String SparePartsService) {
super();
this.id = id;
this.name = name;
this.address = address;
this.contactNo = contactNo;
this.SparePartsService = SparePartsService;
}
#Override
public String toString() {
return id + " - " + name + " - " + address + " - " + contactNo + " - " + SparePartsService + " .";
}
public void Show(){
System.out.println(toString());
}
}
<%# page import="web.ProduitBeans"%>
<%# page import="metier.Produit"%>
<%# page import="java.util.Iterator"%>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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>Getiteasy.Net</title>
</head>
<body>
<%
ProduitBeans produits;
if(request.getAttribute("modele") != null){
produits = (ProduitBeans) request.getAttribute("modele");
}else{
produits = new ProduitBeans();
}
%>
<h3>Tutorial MVC(Model, View, Controller)</h3>
<h5>Ajouter un nouveau produit</h5>
<form action="prodserv" method="post">
<table border="1" width="45%">
<tr>
<td>Name</td>
<td><input type="text" name="name"></td>
</tr>
<tr>
<td>Address</td>
<td><input type="text" name="address"></td>
</tr>
<tr>
<td>Contact No.</td>
<td><input type="text" name="contactNo"></td>
</tr>
<tr>
<td>Spare Parts Service(Yes/No)</td>
<td><input type="text" name="SparePartsService"></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Valider"></td>
</tr>
</table>
</form>
<table border="1" width="60%">
<tr>
<th>ID</th>
<th>Name</th>
<th>Address</th>
<th>Contact No.</th>
<th>Spare Parts Service</th>
<th>Option</th>
</tr>
<%
Iterator<Produit> list = produits.getListe().iterator();
while(list.hasNext()){
Produit p = list.next();
%>
<tr>
<td><%=p.getId() %></td>
<td><%=p.getName() %></td>
<td><%=p.getAddress() %></td>
<td><%=p.getContactno() %></td>
<td><%=p.getSPS() %></td>
<td>
<form action="prodserv" method="post">
<input type="hidden" name="id" value="<%=p.getId() %>" >
<input type="hidden" name="action" value="supprimer" >
<input type="submit" value="supprimer"/>
</form>
<form action="prodserv" method="post">
<input type="hidden" name="id" value="<%=p.getId() %>" >
<input type="hidden" name="editaction" value="Edit" >
<input type="submit" value="Edit"/>
</form>
</td>
</tr>
<%
}
%>
</table>
What do you want your edit method to do? Look at your edit method. If you find a product with the ID you are just calling the getter methods and you are doing nothing with the data. After that you are just adding the same object again to your list. You need to define what data you want to edit and then overwrite the data with a setter method. And don't add the object again to your list.
Working with an ArrayList for this purpose is very unefficiant, you will be looping your list many many times which will take longer and longer as your list is growing. Better make use of a Map, it "maps" a key to a value so you can call that value directly by the predefined key and don't have to loop the whole list.
In your Operation class:
change the ArrayList<Produit> produits ... to Map<Long,Produit> = new HashMap<>()
(Also I would recommand you making it static, to ensure the you keep the same list across the board)
Add a private static Long idCounter=0L
Then when you Add a new Produit, do:
public void add(Produit p){
idCounter++;
p.setId(idCounter);
produits.put(idCounter,p);
}
Remove:
public void remove(Produit p){
produits.remove(p.getId());
}
Note.
No idcounter--; here because you don't know if it is the last one in your map, So baicly you will be skipping some id's if you removed alot of elements.
The id of the Produit that you want to remove has to be set on the p parameter.
Edit:
public void edit(Produit p){
produits.put(p.getId(),p);
}
Note.
The ID of the Produit that you want to remove has to be set on the p parameter.
getAll:
public Collection<Produit> getAll(){
produits.values();
}
In your JSP page:
You have to somehow tell your controller what action it has to do. You can do this by using an Action parameter.
You have done this for one case (Delete (=supprimer FR)).
<input type="hidden" name="action" value="supprimer" >
To edit you must do it again, so change:
<input type="hidden" name="editaction" value="Edit" >
to
<input type="hidden" name="action" value="Edit" >
Note. "name"-tag is the name of the parameter like number is the name of the variable Int number.
In your Controller (servlet):
your:
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
if (req.getParameter("action") != null) {
op.remove(Long.parseLong(req.getParameter("id")));
}
else { // Recuprer les information
String name = req.getParameter("name");
String address = req.getParameter("address");
String contactNo = req.getParameter("contactNo");
String SparePartsService = req.getParameter("SparePartsService");
op.add(new Produit(1L, name, address, contactNo,SparePartsService));
}
In the "else"-clause of you if-satement that checks if action-parameter is null, you only have the functionality to add a Produit.
you must add:
if(req.getParameter("action").equals("Add")){
String name = req.getParameter("name");
String address = req.getParameter("address");
String contactNo = req.getParameter("contactNo");
String SparePartsService = req.getParameter("SparePartsService");
op.add(new Produit(1L, name, address, contactNo,SparePartsService));
}else if (req.getParameter("action").equals("Edit")){
String name = req.getParameter("name");
String address = req.getParameter("address");
String contactNo = req.getParameter("contactNo");
String SparePartsService = req.getParameter("SparePartsService");
Long id = Long.ParseLong(req.getParameter("id"));
op.edit(new Produit(id, name, address, contactNo,SparePartsService));
}
Result:
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
if (req.getParameter("action") != null) {
op.remove(Long.parseLong(req.getParameter("id")));
}
// Recuprer les information
else if(req.getParameter("action").equals("Add")){
String name = req.getParameter("name");
String address = req.getParameter("address");
String contactNo = req.getParameter("contactNo");
String SparePartsService = req.getParameter("SparePartsService");
op.add(new Produit(1L, name, address, contactNo,SparePartsService));
}else if (req.getParameter("action").equals("Edit")){
String name = req.getParameter("name");
String address = req.getParameter("address");
String contactNo = req.getParameter("contactNo");
String SparePartsService = req.getParameter("SparePartsService");
Long id = Long.ParseLong(req.getParameter("id"));
op.edit(new Produit(id, name, address, contactNo,SparePartsService));
}
}
Note. You must add a new "else if"-clause for every possible action-parameter value that you want to implement.
I advise you to put the functionality that is within these if-clauses in a seperate private function, if not your doPost(...) function will get very long.
Or even better take a look at the Command-patern.

<h:selectOneMenu> doesn't fire the actionListener

I am new in topic JSF and develop a simple web dialog:
My currently problem is: that my selectOneMenu component doesn't fire the actionListener and doesn't reRender the other components.
Here is my JSF page:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<%#page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://java.sun.com/jsf/core" prefix="f"%>
<%# taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
<%# taglib uri="http://richfaces.org/rich" prefix="rich"%>
<%# taglib uri="http://richfaces.org/a4j" prefix="a4j"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<meta http-equiv="cache-control" content="no-cache, must-revalidate">
<link href='styles/kn.css' rel="styleSheet" type="text/css" />
</head>
<style>
.top {
vertical-align: top;
}
</style>
<body>
<f:view>
<f:loadBundle basename="messages" var="msg" />
<h:form id="navigation">
<%#include file="include/kn_header.jsp"%>
</h:form>
<h:form >
<rich:panel styleClass="mainPanel" header="#{msg.log_title}"
id="logviewer">
<h:selectOneMenu value="#{logviewer.machine} " onchange="submit()" immediate="true">
<f:selectItems value="#{logviewer.machineList}" />
<a4j:support event="onchange"
actionListener="#{logviewer.processValueChanged}"
ajaxSingle="true" immediate="true" reRender="progressPanel" />
</h:selectOneMenu>
<rich:spacer height="10px" />
<a4j:outputPanel id="progressPanel"
rendered="#{logviewer.isMachine}">
<rich:progressBar value="#{logviewer.currentValue}" interval="1000"
label="#{logviewer.currentValue} %" enabled="#{logviewer.enabled}"
minValue="-1" maxValue="100" reRenderAfterComplete="progressPanel">
<f:facet name="initial">
<br />
<a4j:commandButton action="#{logviewer.startProcess}"
value="Start Download" reRender="progressPanel"
rendered="#{logviewer.buttonRendered}"
style="margin: 9px 0px 5px;" />
</f:facet>
<f:facet name="complete">
<br />
<rich:spacer height="10px" />
<a4j:commandButton id="doDownload"
action="#{logviewer.doDownload}" value="button"
alt="#{msg.download}" title="#{msg.download}"
image="#{icon.download}">
<rich:toolTip value="#{msg.download}"
style="background-color:#{richSkin.generalBackgroundColor}; border-color:#{richSkin.headerBackgroundColor}">
</rich:toolTip>
</a4j:commandButton>
<div class="TextArea">
<rich:panel styleClass="mainPanel">
<h:inputTextarea id="logView" value="#{logviewer.log}"
rows="35" style="font-size:10pt; width:100%" readonly="true" />
</rich:panel>
</div>
</f:facet>
</rich:progressBar>
</a4j:outputPanel>
</rich:panel>
</h:form>
</f:view>
</body>
</html>
and hier is my Bean:
package com.kn.documentserver.jsf;
import java.util.ArrayList;
import java.util.List;
import javax.faces.event.ValueChangeEvent;
import javax.faces.model.SelectItem;
import com.kn.commons.util.BeanLocator;
import com.kn.dcs.distribution.DownloadFile;
import com.kn.documentserver.entity.Machine;
import com.kn.documentserver.interfaces.IMachine;
public class LogviewerBean extends AbstractBean {
// private final static Logger LOG =
// Logger.getLogger(AdministrationBean.class);
private List<SelectItem> machineList;
private Machine machine;
private int maxlength;
private String logfile= null;
private DownloadFile logFile;
private boolean buttonRendered = true;
private boolean enabled = false;
IMachine s = BeanLocator.lookup(IMachine.class,
"java:global/KN_DocumentServerFrontendJBoss/MachineBean");
public LogviewerBean() {
super();
machineList = new ArrayList<SelectItem>();
initMachineList(readMachineList());
}
private List<Machine> readMachineList() {
return s.findAll();
}
private void initMachineList(List<Machine> machines) {
for (Machine m : machines) {
if (m.getMachineName().contains("KN")
&& !m.getMachineName().equals("ASKNGHST")
&& !m.getMachineName().equals("ASKNITRA")) {
SelectItem item= new SelectItem(m.getMachineName(),m.getMachineName());
machineList.add(item);
}
}
}
public List<SelectItem> getMachineList() {
return machineList;
}
public void changeEvent() {
System.out.println("Works");
}
public void setMachineList(List<SelectItem> machineList) {
this.machineList = machineList;
}
public Machine getMachine() {
return machine;
}
public String getLog() {
return logfile;
}
// public GenericConverter getMachineConverter() {
//
// return new GenericConverter(machineList.values());
// }
public void setMachine(Machine machine) {
this.machine = machine;
}
public String processValueChanged(ValueChangeEvent vce) {
String temp = (String) vce.getNewValue();
this.machine=s.findByName(temp);
return null;
}
public void doshowLog() {
setMachine(this.machine);
}
public int getMaxlength() {
return maxlength;
}
public void setMaxlength(int maxlength) {
this.maxlength = maxlength;
}
public boolean getIsMachine() {
return (this.machine == null) ? false : true;
}
public String getLogfile() {
return logfile;
}
public String startProcess() {
setEnabled(true);
setButtonRendered(false);
logFile = new DownloadFile(machine);
System.out.println(getTotalValue());
logFile.start();
return null;
}
public void setLogfile() {
byte[] bytes = logFile.getLogfileAsbyte();
if (bytes != null) {
this.logfile = new String(bytes);
}
}
public boolean getIsLogfileDownloaded() {
return (this.logfile == null) ? false : true;
}
public long getTotalValue() {
return logFile.getFilelength();
}
public Long getCurrentValue() {
if (isEnabled()) {
Long current = new Long(logFile.getCurrfilelength());
current = (current * 100) / getTotalValue();
if (current >= 100) {
setButtonRendered(true);
setLogfile();
return Long.valueOf(101);
} else {
return current;
}
} else {
return Long.valueOf(-1);
}
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public boolean isButtonRendered() {
return buttonRendered;
}
public void setButtonRendered(boolean buttonRendered) {
this.buttonRendered = buttonRendered;
}
}
Could you please help me to investigate, what exactly going wrong.
Kind regards
Alex
If you are using JSF 1.2 or higher, please add prependId="false" to your second form (containing your selectOneMenu). Else (using JSF prior to 1.2), you set an id for your form and add it your the reRender (reRender="formId:progressPanel")

Categories

Resources