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>
Related
--> when i am Updating it was not saving the entered details insted it was saving null. when deleting it throws error.
DataBase : restonetoone
application.properties
/*****************************/
crm.rest.url=http://localhost:8080/restonetoone/api/details
-->when i use to update it was taking null value insted of inserted data.
Details [id=25, city=null, mobileno=0, student=Student [id=25, name=null, clas=0]]
->when i was deleting it throws this error.
Mar 06, 2021 4:09:53 PM org.springframework.web.servlet.DispatcherServlet noHandlerFound
WARNING: No mapping for GET /restclient/student/delete
the Details.java class Onetoone with student.java class
Details.java
/******************/
package com.rest.entity;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
#Entity
#Table(name="details")
public class Details {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
private String city;
private long mobileno;
#OneToOne(cascade=CascadeType.ALL)
#JoinColumn(name="student_id")
private Student student;
public Details(){
}
public Details(int id, String city, long mobileno, Student student) {
super();
this.id = id;
this.city = city;
this.mobileno = mobileno;
this.student = student;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public long getMobileno() {
return mobileno;
}
public void setMobileno(long mobileno) {
this.mobileno = mobileno;
}
public Student getStudent() {
return student;
}
public void setStudent(Student student) {
this.student = student;
}
#Override
public String toString() {
return "Details [id=" + id + ", city=" + city + ", mobileno=" + mobileno + ", student=" + student + "]";
}
}
student.java class
Student.java
/******************/
package com.rest.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="student")
public class Student {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
private String name;
private int clas;
public Student() {
}
public Student(int id, String name, int clas) {
super();
this.id = id;
this.name = name;
this.clas = clas;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getClas() {
return clas;
}
public void setClas(int clas) {
this.clas = clas;
}
#Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", clas=" + clas + "]";
}
}
DetailsServImpl.java class(service layers)
DetailsServImpl.java
/******************/
package com.rest.service;
import java.util.List;
import java.util.logging.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import com.rest.entity.Details;
#Service
public class DetailsServImpl implements DetailsServ {
private RestTemplate restTemplate;
private String crmRestUrl;
private Logger logger = Logger.getLogger(getClass().getName());
#Autowired
public DetailsServImpl(RestTemplate theRestTemplate,
#Value("${crm.rest.url}") String theUrl) {
restTemplate = theRestTemplate;
crmRestUrl = theUrl;
logger.info("Loaded property: crm.rest.url=" + crmRestUrl);
}
#Override
public List<Details> getDetails() {
logger.info("in getDetails(): Calling REST API " + crmRestUrl);
// make REST call
ResponseEntity<List<Details>> responseEntity =
restTemplate.exchange(crmRestUrl, HttpMethod.GET, null,
new ParameterizedTypeReference<List<Details>>() {});
// get the list of customers from response
List<Details> theDetails = responseEntity.getBody();
logger.info("in getDetails(): details" + theDetails);
return theDetails;
}
#Override
public Details getDetails(int theId) {
logger.info("in getDetails(): Calling REST API " + crmRestUrl);
// make REST call
Details theDetails =
restTemplate.getForObject(crmRestUrl + "/" + theId,
Details.class);
logger.info("in saveDetails(): theDetails=" + theDetails);
return theDetails;
}
#Override
public void saveDetails(Details theDetails) {
logger.info("in saveSt(): Cudentalling REST API " + crmRestUrl);
int detailsId = theDetails.getId();
// make REST call
if (detailsId == 0) {
// add employee
restTemplate.postForEntity(crmRestUrl, theDetails, String.class);
} else {
// update employee
restTemplate.put(crmRestUrl, theDetails);
}
logger.info("in saveDetails(): success");
}
#Override
public void deleteDetails(int theId) {
logger.info("in deleteDetails(): Calling REST API " + crmRestUrl);
// make REST call
restTemplate.delete(crmRestUrl + "/" + theId);
logger.info("in deleteDetails(): deleted Details theId=" + theId);
}
}
StudentServImpl.java class
StudentServImpl.java
/******************/
package com.rest.service;
import java.util.List;
import java.util.logging.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import com.rest.entity.Details;
import com.rest.entity.Student;
#Service
public class StudentServImpl implements StudentServ {
private RestTemplate restTemplate;
private String crmRestUrl;
private Logger logger = Logger.getLogger(getClass().getName());
#Autowired
public StudentServImpl(RestTemplate theRestTemplate,#Value("${crm.rest.url}") String theUrl){
restTemplate = theRestTemplate;
crmRestUrl = theUrl;
logger.info("Loaded property: crm.rest.url=" + crmRestUrl);
}
#Override
public List<Student> getStudent() {
logger.info("in getCustomers(): Calling REST API " + crmRestUrl);
// make REST call
ResponseEntity<List<Student>> responseEntity =
restTemplate.exchange(crmRestUrl, HttpMethod.GET, null,
new ParameterizedTypeReference<List<Student>>() {});
// get the list of customers from response
List<Student> theStudent = responseEntity.getBody();
logger.info("in getCustomers(): customers" + theStudent);
return theStudent;
}
#Override
public void saveStudent(Student theStudent) {
logger.info("in saveSt(): Cudentalling REST API " + crmRestUrl);
int studentId = theStudent.getId();
// make REST call
if (studentId == 0) {
// add employee
restTemplate.postForEntity(crmRestUrl, theStudent, String.class);
} else {
// update employee
restTemplate.put(crmRestUrl, theStudent);
}
logger.info("in saveStudent(): success");
}
#Override
public Student getStudent(int theId) {
logger.info("in getCustomer(): Calling REST API " + crmRestUrl);
// make REST call
Student theStudent =
restTemplate.getForObject(crmRestUrl + "/" + theId,
Student.class);
logger.info("in saveCustomer(): theCustomer=" + theStudent);
return theStudent;
}
#Override
public void deleteStudent(int theId) {
logger.info("in deleteStudent(): Calling REST API " + crmRestUrl);
// make REST call
restTemplate.delete(crmRestUrl + "/" + theId);
logger.info("in deleteStudent(): deleted Student theId=" + theId);
}
}
Now the controller class(here i am using single controller for multiple entites).
ClientController.java
/******************/
package com.rest.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.rest.entity.Details;
import com.rest.entity.Student;
import com.rest.service.DetailsServ;
import com.rest.service.StudentServ;
#Controller
#RequestMapping("/cont")
public class ClientController {
#Autowired
private DetailsServ detailsServ;
#Autowired
private StudentServ studentServ;
#GetMapping("/showForm")
public String showForm(Model theModel){
Details theDetails = new Details();
Student theStudent = new Student();
theDetails.setStudent(theStudent);
theModel.addAttribute("for",theDetails);
return "the-for";
}
#PostMapping("/saveForm")
private String saveForm(#ModelAttribute("for") Details theDetails) {
detailsServ.saveDetails(theDetails);
return "redirect:/cont/list";
}
#GetMapping("/list")
public String showList(Model theModel) {
List<Details> theDetails = detailsServ.getDetails();
theModel.addAttribute("details", theDetails);
return "list-table";
}
#GetMapping("/update")
public String updateDetails(#RequestParam("detailsId") int theId, Model theModel) {
Details theDetails =detailsServ.getDetails(theId);
theModel.addAttribute("for",theDetails);
return "the-for";
}
#GetMapping("/delete")
public String deleteDetails(#RequestParam("detailsId") int theId) {
detailsServ.deleteDetails(theId);
return "redirect:/cont/list";
}
}
I use this form for both saving and updating.
the-for.jsp
/******************/
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%# page import="java.sql.*"%>
<!DOCTYPE html>
<html>
<head>
<title>Save Customer</title>
<link type="text/css"
rel="stylesheet"
href="${pageContext.request.contextPath}/resources/css/style.css">
<link type="text/css"
rel="stylesheet"
href="${pageContext.request.contextPath}/resources/css/add-customer-style.css">
</head>
<body>
<div id="wrapper">
<div id="header">
<h2>Form</h2>
</div>
</div>
<div id="container">
<h3>Save StudentDetails</h3>
<form:form action="saveForm" modelAttribute="for" method="POST">
<!-- need to associate this data with customer id -->
<form:hidden path="id" />
<table>
<tbody>
<tr>
<td><label>City name:</label></td>
<td><form:input path="city" /></td>
</tr>
<tr>
<td><label>mobileno:</label></td>
<td><form:input path="mobileno" /></td>
</tr>
<tr>
<td><label>name:</label></td>
<td><form:input path="student.name" /></td>
</tr>
<tr>
<td><label>class:</label></td>
<td><form:input path="student.clas" /></td>
</tr>
<tr>
<td><label></label></td>
<td><input type="submit" value="Save" class="save" /></td>
</tr>
</tbody>
</table>
</form:form>
<div style="clear; both;"></div>
<p>
Back to List
</p>
</div>
</body>
</html>
Now the table which shows the CRUD dynamically.
list-table.jsp
/******************/
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# page import = "java.sql.*" %>
<!DOCTYPE html>
<html>
<head>
<title>List</title>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap CSS -->
<link
href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1"
crossorigin="anonymous">
</head>
<body>
<div class="container">
<h2 class="pt-2">Student Manager</h2>
<!-- put new button: Add Student -->
<input type="button" value="Add Student"
onclick="window.location.href='showForm'; return false;"
class="btn btn-primary btn-sm mb-3" />
<!-- add our html table here -->
<table class="table table-bordered table-striped">
<thead class="table-dark">
<tr>
<th>city</th>
<th>mobileno</th>
<th>name</th>
<th>class</th>
<th>Action</th>
</tr>
</thead>
<!-- loop over and print our students -->
<tbody>
<c:forEach var="tempDetails" items="${details}">
<!-- construct an "update" link with student id -->
<c:url var="updateLink" value="/cont/update">
<c:param name="detailsId" value="${tempDetails.id}" />
</c:url>
<!-- construct an "delete" link with student id -->
<c:url var="deleteLink" value="/student/delete">
<c:param name="studentId" value="${tempStudent.id}" />
</c:url>
<tr>
<td>${tempDetails.city}</td>
<td>${tempDetails.mobileno}</td>
<td>${tempDetails.student.name}</td>
<td>${tempDetails.student.clas}</td>
<td>
<!-- display the update link -->
Update
|
<a href="${deleteLink}"
onclick="if (!(confirm('Are you sure you want to delete this student?'))) return false">Delete</a>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</body>
</html>
For more clearity sake i am shering the link of my project which include Both client side and backend code files with database.
LINK( https://drive.google.com/file/d/128pvCd6bYdCNhOiG6ERRXbPRUlnhZlTp/view?usp=sharing )
So here is my issue. I am working on a school project and I am basically hitting a wall. I cannot get my RegistrationServer to work at all. I can get it to run, and correctly display the Registration.jsp that it is built behind, but none of the information is entered into the database at all. In fact, I cannot even tell if that is where exactly I am failing. Here is the code for the Registration function:
Registration.jsp
<%# 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">
<style>
div.container {
//width: 100%;
// border: 1px solid gray;
// padding:5px;
}
table, th, td {
//border: 1px solid black;
}
.textright{float:right;padding:10px}
</style>
<title>Registration</title>
<script>
function validate()
{
var firstname = document.form.firstname.value;
var lastname = document.form.lastname.value;
var username = document.form.username.value;
var password = document.form.password.value;
var address = document.form.address.value;
var contact = document.form.contact.value;
if (firstname==null || firstname=="")
{
alert("First Name can't be blank");
return false;
}
else if (lastname==null || lastname=="")
{
alert("Last Name can't be blank");
return false;
}
else if (username==null || username=="")
{
alert("Username can't be blank");
return false;
}
else if (password==null || password=="")
{
alert("Password can't be blank");
return false;
}
else if(password.length<6)
{
alert("Password must be at least 6 characters long.");
return false;
}
else if (address==null || address=="")
{
alert("Address can't be blank");
return false;
}
else if (contact==null || contact=="")
{
alert("Contact can't be blank");
return false;
}
}
</script>
</head>
<body bgcolor="#D3D3D3">
<form name="form" action="RegistrationServlet" method="post"
onsubmit="return
validate()">
<td style="float:left"><image
src="file:///G:/College/Winter%202018/CSC%20363/Computer%20logo.png"
width="100px" height="100px"></image></td>
<p style="float:right"><b> ${members[3]} <br> CSC 363<br>Final Project</b>
</p>
<td style="clear:float"></td>
<p style="align-text"left">Team</p>
<p style="float:left">${members[0]} <br> ${members[1]} <br>
${members[2]} </p>
<td style="close:float"></td>
<table style="float:right">
<tr>
<td>First Name</td>
<td><input type="text" name="firstName" /></td>
</tr>
<tr>
<td>Last Name</td>
<td><input type="text" name="lastName" /></td>
</tr>
<tr>
<td>User Name</td>
<td><input type="text" name="userName" /></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="password" /></td>
</tr>
<tr>
<td>Address</td>
<td><input type="text" name="address" /></td>
</tr>
<tr>
<td>Contact</td>
<td><input type="text" name="contact" /></td>
</tr>
<tr>
<td><%=(request.getAttribute("errMessage") == null) ? ""
: request.getAttribute("errMessage")%></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Submit"></input>
</tr>
</table>
</form>
</body>
</html>
RegistrationServlet
package com.mvc.RegistrationServlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.mvc.Bean.RegistrationBean;
import com.mvc.Dao.RegistrationDao;
public class RegistrationServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public RegistrationServlet() {
}
protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
// TODO Auto-generated method stub
String[] members = new String[4];
members[0] = "Jamie W.";
members[1] = "Evan D.";
members[2] = "Tim D.";
members[3] = "Hardware Plus";
request.setAttribute("members", members);
request.getRequestDispatcher("/Registration.jsp").forward(request,
response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
String firstName = request.getParameter("firstname");
String lastName = request.getParameter("lastname");
String userName = request.getParameter("username");
String password = request.getParameter("password");
String address = request.getParameter("address");
String contact = request.getParameter("contact");
RegistrationBean registrationBean = new RegistrationBean();
registrationBean.setFirstName(firstName);
registrationBean.setLastName(lastName);
registrationBean.setUserName(userName);
registrationBean.setPassword(password);
registrationBean.setAddress(address);
registrationBean.setContact(contact);
RegistrationDao registrationDao = new RegistrationDao();
String userRegistered = registrationDao.registrationUser(registrationBean);
if(userRegistered.equals("SUCCESS"))
{
request.getRequestDispatcher("/ProductSalesPage.jsp").forward(request,
response);
}
else
{
request.setAttribute("errMessage", userRegistered);
request.getRequestDispatcher("/RegistrationServlet.jsp").forward(request,
response);
}
}
}
RegistrationDao
package com.mvc.Dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import com.mvc.Bean.RegistrationBean;
import com.mvc.RegistrationDB.RegistrationDB;
public class RegistrationDao {
public String registrationUser(RegistrationBean registrationBean)
{
String firstName = registrationBean.getFirstName();
String lastName = registrationBean.getLastName();
String userName = registrationBean.getUserName();
String password = registrationBean.getPassword();
String address = registrationBean.getAddress();
String contact = registrationBean.getContact();
Connection con = null;
PreparedStatement preparedStatement = null;
try
{
con = RegistrationDB.createConnection();
String query = "insert into
users(SlNo,firstName,lastName,userName,password,address,contact) values
(NULL,?,?,?,?,?,?)";
preparedStatement = con.prepareStatement(query);
preparedStatement.setString(1, firstName);
preparedStatement.setString(2, lastName);
preparedStatement.setString(3, userName);
preparedStatement.setString(4, password);
preparedStatement.setString(5, address);
preparedStatement.setString(6, contact);
int i= preparedStatement.executeUpdate();
if (i!=0)
return "SUCCESS";
}
catch(SQLException e)
{
e.printStackTrace();
}
return "Oops.. Something went wrong there..!";
}
}
RegistrationDB
package com.mvc.RegistrationDB;
import java.sql.Connection;
import java.sql.DriverManager;
public class RegistrationDB {
public static Connection createConnection()
{
Connection con = null;
String url = "jdbc:mysql#localhost:3306/project/users";
String username = "root";
String password = "password";
try
{
try
{
Class.forName("com.mysql.jdbc.Driver");
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
con = DriverManager.getConnection(url, username, password);
System.out.println("Printing connection object "+con);
}
catch (Exception e)
{
e.printStackTrace();
}
return con;
}
}
RegistrationBean
package com.mvc.Bean;
public class RegistrationBean
{
private String firstName;
private String lastName;
private String userName;
private String password;
private String address;
private String contact;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getFirstName() {
return firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getLastName() {
return lastName;
}
public void setAddress(String address) {
this.address = address;
}
public String getAddress() {
return address;
}
public void setContact(String contact) {
this.contact = contact;
}
public String getContact() {
return contact;
}
}
Anything anyone can offer as far as why this servlet will not run would be gladly appreciated. The error messages that Eclipse throws are so generic, but the issue seems to be basically writing the registration information to the database. I can load the registration page and enter the information, and the if statements work because the page wont forward with blank text entry boxes or a password less than 6 characters. The problem is when you submit, and it throws HTTP Status 404 and says the requested resource is unavailable.
It might be because you're retrieving the incorrect parameter names in your RegistrationServlet.
For example: you are retrieving with request.getParameter("firstname") but your input have name="firstName". Note the upper case 'N' (java EE servers are case sensitive for URIs).
Try this in your RegistrationServlet:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String firstName = request.getParameter("firstName"); // upper case N
String lastName = request.getParameter("lastName"); // upper case N
String userName = request.getParameter("userName"); // upper case N
String password = request.getParameter("password");
String address = request.getParameter("address");
String contact = request.getParameter("contact");
//...
I made wrong HQL trying to access column from another table. Sorry.
This question is solved.
I have ArrayList of type Object. Fetched from session.
It exists. I check. But I cant print it it from jsp or java. even I create methods.
// with type List I cant even fetch information from session. A change it to ArrayList.
My goal is to print result. I select some sql columns and I just wanna output them. Of course it would be object.
I have no error and that is problem. Only existing arraylist object of my type prod.
ArrayList <prod> goodlist = (ArrayList <prod>) session.getAttribute("goodlist_s");
for (prod glst : goodlist) {
%>
<tr>
<td><%//=out.println(u.getname())%></td>
<td><%=glst.getcatid()%></td>}
I try convert it to String ArrayList .
ArrayList<String> jlistTitles = new ArrayList<String>((ArrayList<String>) session.getAttribute("goodlist_s")); //converted fine
for(int i = 0; i < goodlist.size(); i++) {
System.out.println(goodlist.get(i).getprice());
//print object type
}
**Shows nothing**
This is my function
#SuppressWarnings("unchecked")
public static ArrayList<prod> getListOfProds(String catname,String name,Integer pricel, Integer priceh){
ArrayList<prod> list = new ArrayList<prod>();
Session session = HibernateUtil.openSession();
Transaction tx = null;
try {
tx = session.getTransaction();
tx.begin();
Query query = session.createQuery("from prod where catname=?");
query.setString(0, catname);
//query.setInteger(1, pricel);
//query.setInteger(2, priceh);
list = (ArrayList<prod>) query.list();
tx.commit();
} catch (Exception e) {
if (tx != null) {
tx.rollback();
}
e.printStackTrace();
} finally {
session.close();
}
return list;
}
BTW i would sent all code
index.jsp
<%#page import="java.util.List"%>
<%#page import="service.IndexService"%>
<%#page import="java.util.Date"%>
<%#page import="goods.prod"%>
<%#page import="goods.cat"%>
<%#page import ="java.util.ArrayList"%>
<%#page import ="java.util.List"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charprods=UTF-8">
<link rel="stylesheet" type="text/css" href="css/style.css"/>
<title>Result Page</title>
</head>
</head>
<body>
<form action="IndexServlet" method="POST">
<table align="center" cellpadding = "10">
<tr>
<td>Category</td>
<td><input type="text" name="catname" maxlength="30"/>
(max 30 characters a-z and A-Z)
</td>
</tr>
<tr>
<td>Category id</td>
<td><input type="number" name="catid" maxlength="30"/>
(max 30 characters a-z and A-Z)
</td>
</tr>
<tr>
<td>Naimenovanie</td>
<td><input type="text" name="name" maxlength="30"/>
(max 30 characters a-z and A-Z)
</td>
</tr>
<tr>
<td>Price low</td>
<td><input type="number" name="pricel" maxlength="30"/>
(max 30 characters a-z and A-Z)
</td>
</tr>
<tr>
<td>Price high</td>
<td><input type="number" name="priceh" maxlength="100" /></td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" value="Submit">
<input type="reset" value="Reset">
</td>
</tr>
</table>
prodsAttribute
<%
prod prod = (prod) session.getAttribute("prod");
%>
<%
ArrayList <prod> goodlist = (ArrayList <prod>) session.getAttribute("goodlist_s");
%>
<b>You have<% if (null == prod) out.println("No text entered.");%></b>
<b>You have<% if (null == goodlist) out.println("goodlist does NOT exists.");%></b>
<b>You have<% if (null != goodlist) {
ArrayList<String> jlistTitles = new ArrayList<String>((ArrayList<String>) session.getAttribute("goodlist_s"));
if (null == jlistTitles) out.println("convertedStringlist does NOT exists.");
if (null != jlistTitles) out.println("convertedStringlist exists. How can I use it?");
for(int i = 0; i < goodlist.size(); i++) {
System.out.println(goodlist.get(i).getprice());
//print object type
}
out.println("goodlist exists. How can I use it?");}%></b>
<br>
<b><%if (null!=prod) out.println(prod.getid()+ " "+prod.getname()+ " "+prod.getprice());%></b>
<br/>
<%
if (null!=goodlist) {
for (prod glst : goodlist) {
%>
<tr>
<td><%//=out.println(u.getname())%></td>
<td><%=glst.getcatid()%></td>
<td><%=glst.getprice()%></td>
<td><%="hh"%></td>
</tr>
<%}}%>
</form>
</body>
</html>
Indexservlet.java
package servlet;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import goods.prod;
import service.IndexService;
public class IndexServlet extends HttpServlet {
private static final long serialVersionUID = -8670416133536111566L;
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charprods=UTF-8");
//Long id = Long.parseLong(request.getParameter("id"));
String name = request.getParameter("name");
String catname = request.getParameter("catname");
Integer pricel = Integer.parseInt(request.getParameter("pricel"));
Integer priceh = Integer.parseInt(request.getParameter("priceh"));
prod dot = IndexService.getprodbyparam(catname,name,pricel,priceh);
List<prod> goodlist = IndexService.getListOfProds(catname,name,pricel,priceh);
request.getSession().setAttribute("goodlist_s", goodlist);
request.getSession().setAttribute("prod", dot);
response.sendRedirect("index.jsp");
}
}
Indexservice with functions
package service;
import java.sql.DriverManager;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import HibernateUtil.HibernateUtil;
import goods.prod;
public class IndexService {
public static prod getprodbyparam(String catname,String name,Integer pricel, Integer priceh) {
Session session = HibernateUtil.openSession();
Transaction tx = null;
prod prod = null;
try {
tx = session.getTransaction();
tx.begin();
//Query query = session.createQuery("select prod.id from prod as prod inner join cat.id as id where name=?");
Query query = session.createQuery("from prod where name=? and price between ? and ?");
query.setString(0, name);
query.setInteger(1, pricel);
query.setInteger(2, priceh);
//query.prodsInteger(3, catid);
prod = (prod)query.uniqueResult();
tx.commit();
} catch (Exception e) {
if (tx != null) {
tx.rollback();
}
e.printStackTrace();
} finally {
session.close();
}
return prod;
}
#SuppressWarnings("unchecked")
public static ArrayList<prod> getListOfProds(String catname,String name,Integer pricel, Integer priceh){
ArrayList<prod> list = new ArrayList<prod>();
Session session = HibernateUtil.openSession();
Transaction tx = null;
try {
tx = session.getTransaction();
tx.begin();
Query query = session.createQuery("from prod where catname=?");
query.setString(0, catname);
//query.setInteger(1, pricel);
//query.setInteger(2, priceh);
list = (ArrayList<prod>) query.list();
tx.commit();
} catch (Exception e) {
if (tx != null) {
tx.rollback();
}
e.printStackTrace();
} finally {
session.close();
}
return list;
}
}
prod with getters
package goods;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinColumns;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import java.io.Serializable;
#Entity
#Table(name = "prod")
public class prod implements Serializable {
#Id #GeneratedValue
#Column(name = "id")
private Long id;
private Integer catid;
private String name;
private Integer price;
public prod() {
}
public prod(Long id, Integer catid, String name, Integer price) {
this.id = id;
this.catid = catid;
this.name = name ;
this.price = price;
}
public Long getid() {
return id;
}
public void setid(Long id) {
this.id = id;
}
public Integer getcatid() {
return catid;
}
public void setcatid(Integer catid) {
this.catid = catid;
}
public String getname() {
return name;
}
public void setname(String name) {
this.name = name;
}
public Integer getprice() {
return price;
}
public void setprice(Integer price) {
this.price = price;
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>Improve</display-name>
<servlet>
<servlet-name>IndexServlet</servlet-name>
<servlet-class>servlet.IndexServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>IndexServlet</servlet-name>
<url-pattern>/IndexServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
Can you please try the below code and see if it works
ArrayList<String> goodlist_s= (ArrayList<String>)session.getAttribute("goodlist_s");
<%
for(int i = 0; i < goodlist_s.size(); i++)
{
String myString = (String) goodlist_s.get(i);
}
%>
Hey guys I am trying to retrieve complete list of users in the table from database but unfortunately unable to do it. Here is the code
1.> Deleteuser.java
package roseindia.net;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
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;
/**
* Servlet implementation class Deleteuser
*/
#WebServlet("/Deleteuser")
public class Deleteuser extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public Deleteuser() {
super();
// TODO Auto-generated constructor stub
}
//String msg=" ";
String fname=" ";
String mname=" ";
String lname=" ";
String uname=" ";
String emailid=" ";
String mobno=" ";
String address=" ";
//String password1=" ";
//String password2=" ";
String usertype=" ";
String id=" ";
public void setFname(String fname) {
this.fname = fname;
}
public void setMname(String mname) {
this.mname = mname;
}
public void setLname(String lname) {
this.lname = lname;
}
public void setUname(String uname) {
this.uname = uname;
}
public void setEmailid(String emailid) {
this.emailid = emailid;
}
public void setMobno(String mobno) {
this.mobno = mobno;
}
public void setAddress(String address) {
this.address = address;
}
public void setUsertype(String usertype) {
this.usertype = usertype;
}
public void setId(String id) {
this.id = id;
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
public static List<Deleteuser> list() throws Exception {
Connection conn=null;
String url="jdbc:mysql://localhost:3306/";
String dbName="userlogindb";
String driver="com.mysql.jdbc.Driver";
String dbUserName="root";
String dbPassword="root";
//List<String> dataList = new ArrayList<String>();
List<Deleteuser> users = new ArrayList<Deleteuser>();
try{
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url+dbName,dbUserName,dbPassword);
String strQuery="select * from registerutable";
System.out.println("The sql is " +strQuery);
Statement st= conn.createStatement();
ResultSet rs= st.executeQuery(strQuery);
while(rs.next())
{
Deleteuser user = new Deleteuser();
user.setFname(rs.getString("fname"));
user.setMname(rs.getString("mname"));
user.setLname(rs.getString("lname"));
user.setUname(rs.getString("uname"));
user.setEmailid(rs.getString("emailid"));
user.setMobno(rs.getString("mobno"));
user.setAddress(rs.getString("address"));
user.setUsertype(rs.getString("usertype"));
user.setId(rs.getString("id"));
users.add(user);
}
rs.close();
st.close();
}
catch(Exception e)
{
e.printStackTrace();
}
return users;
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("We are in the doPost method of Deleteuser");
response.setContentType("text/html");
PrintWriter out=response.getWriter();
try{
List<Deleteuser> users = Deleteuser.list();
request.setAttribute("users",users);
}
catch(Exception e)
{
System.out.println(e);
}
//Disptching request
RequestDispatcher dispatcher = request.getRequestDispatcher("successful.jsp");
if (dispatcher != null){
dispatcher.forward(request, response);
}
//out.println("<font size='6' color=red>" + msg + "</font>");
}
}
2.> successful.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--<%#page language="java" import="java.util.*" %>-->
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login Successful</title>
</head>
<body>
<form name="deleteform" action="Deleteuser" method="post">
<p><b><i>List of user details:</i></b></p>
<table border="1">
<tr>
<th>First Name</th>
<th>Middle Name</th>
<th>Last Name</th>
<th>User Name</th>
<th>Email id</th>
<th>Mobile No</th>
<th>Address</th>
<th>Usertype</th>
<th>ID</th>
</tr>
<c:forEach items="${users}" var="user">
<tr>
<td><c:out value="${user.fname}" /></td>
<td><c:out value="${user.mname}" /></td>
<td><c:out value="${user.lname}" /></td>
<td><c:out value="${user.uname}" /></td>
<td><c:out value="${user.emailid}" /></td>
<td><c:out value="${user.mobno}" /></td>
<td><c:out value="${user.address}" /></td>
<td><c:out value="${user.usertype}" /></td>
<td><c:out value="${user.id}" /></td>
</tr>
</c:forEach>
</table>
</form>
</body>
</html>
Here, I m unable to display the list of user from the database table. I not getting any error also.
Serious apology I haven't use MVC because I first want do it using only single java program.
I have added all the necessary jar files.
Please let me know if I m missing anything or not following proper technique/standard.
To use EL syntax to get the value of object Pseudo Getter should be implemented.
So define getter for all element.
${user.fname} implicitly calls user.getFname()
You have not written any getter methods.
EL statement ${user.fname} is like calling user.getFname() and you don't have getter methods.
Define getter methods for all instance variables in Deleteuser.java.
public String getFname() {
return fname;
}
public void setFname(String fname) {
this.fname = fname;
}
public String getMname() {
return mname;
}
public void setMname(String mname) {
this.mname = mname;
}
public String getLname() {
return lname;
}
public void setLname(String lname) {
this.lname = lname;
}
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public String getEmailid() {
return emailid;
}
public void setEmailid(String emailid) {
this.emailid = emailid;
}
public String getMobno() {
return mobno;
}
public void setMobno(String mobno) {
this.mobno = mobno;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getUsertype() {
return usertype;
}
public void setUsertype(String usertype) {
this.usertype = usertype;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
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;
}
}