SelectOneMenu doesn't have any value to choose from - java

when I try to display employee.jsp page I am not able to select employee.
It looks like SelectOneMenu doesn't work. Am I missing something in that tag (line 20)?
I checked and the database has table employee with some employee data.
I have connection to database. I use mysql database. You can see connection to this database in persistance.xml file.
<%# page language="java" contentType="text/html;
charset=US-ASCII" pageEncoding="US-ASCII"%>
<%# taglib prefix="f" uri="http://java.sun.com/jsf/core"%>
<%# taglib prefix="h" uri="http://java.sun.com/jsf/html"%>
<!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>Employee Details</title>
</head>
<body>
<f:view>
<h2><center>Welcome to Employee Home Page</center></h2>
<br><br>
<h:form>
<h2>
Select an Employee Number from the drop down:
</h2>
<br><br>
<h:selectOneMenu id="selEmpNo"
valueChangeListener="#{employee.employeeReport}"
onchange="submit()">
<f:selectItem itemLabel="select" />
<f:selectItems value="#{employee.empNoList}" id="emp"/>
</h:selectOneMenu>
</h:form>
<br><br>
<h2>
<h:outputText value="Employee Name: "></h:outputText>
<h:outputText value="#{employee.empName}"/>
<br><br>
<h:outputText value="Employee Number: "/>
<h:outputText value="#{employee.empNo}"/>
<br><br>
<h:outputText value="Name of the IBU: "/>
<h:outputText value="#{employee.ibu}"/>
<br><br>
<h:outputText value="Designation: "/>
<h:outputText value="#{employee.designation}"/> </h2>
</f:view>
</body>
</html>
<%# page language="java" contentType="text/html;
charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%# taglib prefix="f" uri="http://java.sun.com/jsf/core"%>
<%# taglib prefix="h" uri="http://java.sun.com/jsf/html"%>
<!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=US-ASCII">
<title>Home</title>
</head>
<body>
<f:view>
<h2>
<center>
<h:outputLabel> Welcome!!!</h:outputLabel>
</center>
<h:outputLink value="employee.jsp">Employee Details</h:outputLink>
</h2>
</f:view>
</body>
</html>
</html>
package employee;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.faces.event.ValueChangeEvent;
import javax.faces.model.SelectItem;
public class EmployeeBean {
private String empName;
private String ibu;
private String designation;
private int empNo;
//This is used to dynamically populate the drop down with employee numbers
List<SelectItem> empNoList;
List<EmployeeEntity>empList;
public EmployeeBean(){
this.empNoList = new ArrayList<SelectItem>();
/*Populating Employee Number in the drop down - Dynamic */
empList = new EmployeeService().getEmployeeList();
Iterator<EmployeeEntity>iterator = empList.iterator();
while(iterator.hasNext()){
EmployeeEntity employee = iterator.next();
SelectItem item = new SelectItem(employee.getEmpNo());
empNoList.add(item);
}
System.out.println(empNoList);
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public String getIbu() {
return ibu;
}
public void setIbu(String ibu) {
this.ibu = ibu;
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
public int getEmpNo() {
return empNo;
}
public void setEmpNo(int empNo) {
this.empNo = empNo;
}
public List<SelectItem> getEmpNoList() {
return empNoList;
}
public void setEmpNoList(List<SelectItem> empNoList) {
this.empNoList = empNoList;
}
public List<EmployeeEntity> getEmpList() {
return empList;
}
public void setEmpList(List<EmployeeEntity> empList) {
this.empList = empList;
}
/*Eventlistener - for fetching an employee record based on the selection of employee
number from the drop down*/
public void employeeReport(ValueChangeEvent event){
int empNo = Integer.parseInt((String)event.getNewValue());
EmployeeEntity employee = new EmployeeService().getEmployee(empNo);
this.empNo = employee.getEmpNo();
this.empName = employee.getEmpName();
this.ibu = employee.getIbu();
this.designation = employee.getDesignation();
}
}
package employee;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="employee")
public class EmployeeEntity {
#Id
private int empNo;
private String empName;
private String ibu;
private String designation;
public int getEmpNo() {
return empNo;
}
public void setEmpNo(int empNo) {
this.empNo = empNo;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public String getIbu() {
return ibu;
}
public void setIbu(String ibu) {
this.ibu = ibu;
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
}
package employee;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import javax.persistence.Query;
public class EmployeeService {
public List<EmployeeEntity> getEmployeeList(){
List<EmployeeEntity> empList = new ArrayList<EmployeeEntity>();
EntityManager em = null;
try{
EntityManagerFactory emf =
Persistence.createEntityManagerFactory("Employee-
Details");
em = emf.createEntityManager();
EntityTransaction et = em.getTransaction();
et.begin();
Query query = em.createQuery("select empNo from employee ");
empList = query.getResultList();
}
catch(Exception e){
//log the exception
}
return empList;
}
public EmployeeEntity getEmployee(int empNo){
EmployeeEntity employee = new EmployeeEntity();
EntityManager em = null;
try{
EntityManagerFactory emf =
Persistence.createEntityManagerFactory("Employee-Details");
em = emf.createEntityManager();
EntityTransaction et = em.getTransaction();
employee = em.find(EmployeeEntity.class, empNo);
}
catch(Exception e){
//log the exception
}
finally{
if( em != null){
em.clear();
}
}
return employee;
}
}
<faces-config version="1.2"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-facesconfig_1_2.xsd">
<navigation-rule>
<display-name>Employee</display-name>
<from-view-id>/index.jsp</from-view-id>
</navigation-rule>
<managed-bean>
<managed-bean-name>employee</managed-bean-name>
<managed-bean-class>employee.EmployeeBean
</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
</managed-bean>
</faces-config>
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<display-name>Generating Employee Report</display-name>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>

you should add the value to the selectOneMenu, the valueChangeListener attribute accepts a method-binding expression representing a value change listener method to be notified when a new value has been set for this input component. A value change listener method must be a public method that takes a ValueChangeEvent parameter, with a return type of void. It's not the same as the value property.
Your page.
<h:selectOneMenu id="selEmpNo"
valueChangeListener="#{employee.employeeReport}"
onchange="submit()" value="#{employee.myvalue}">
<f:selectItem itemLabel="select" />
<f:selectItems value="#{employee.empNoList}" id="emp"/>
</h:selectOneMenu>
EmployeeBean
package employee;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.faces.event.ValueChangeEvent;
import javax.faces.model.SelectItem;
public class EmployeeBean {
private String myValue;
private String empName;
private String ibu;
private String designation;
public String getMyValue() {
return myValue;
}
public void setMyValue(String myValue) {
this.myValue = myValue;
}
Regards
Source here

Related

How to send a new product to Action in Struts 2

It looks like basical, but I am new with Struts2.
I want to send a new product created with name, price and category.
I work with struts2 version 2.5.26, Maven, tomcat 9.0, java jdk 1.8.0_241
It seams that the code I use to send the product is wrong, and Action defined in struts.xml can't get it.
My JSP file to send the product :
<%# page pageEncoding="UTF-8" %>
<%# taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Nouveau produit</title>
</head>
<body>
<h1>Ajouter un nouveau produit</h1><br><br>
<form action="newProduit.action" method="post">
<div >
<s:textfield name="produit.nom" label="Nom " />
</div><br>
<div>
<s:textfield name="produit.prix" class="formH len150" label="Prix " />
</div><br>
<div style="position:relative;">
<label for="cat" class="formH len150">Catégorie :</label>
<select id="cat" name="produit.categorie" class="formH len150">
<option value="">--Choisir--</option>
<s:iterator value="categories" var="c">
<option value=" ${c.id } " > ${c.nom } </option>
</s:iterator>
</select>
</div><br>
<div >
<s:submit class="btn btn-vert" value="Envoyer" />
</div><br>
<div >
<s:a href="listeProduits.action" class="btn" >Retour liste produits</s:a>
</div>
</form>
</body>
</html>
The struts.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.devMode" value="true" />
<package name="actionsDiverses" extends="struts-default,json-default" namespace="/actions" >
<!-- other actions -- >
<action name="newProduit" method="nvProduit" class="actions.ProduitsAction">
<result name="success" type="redirect">listeProduits</result>
</action>
</package>
</struts>
The ProduitsAction.java file :
package actions;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import entities.Produit;
import services.IMetiersBoutiqueFactory;
import services.MetiersBoutiqueFactory;
public class ProduitsAction extends ActionSupport implements ModelDriven{
private static final long serialVersionUID = 1L;
private IMetiersBoutiqueFactory services = new MetiersBoutiqueFactory();
private Produit produit;
public String nvProduit() {
try {
services.ajouterProduit(produit);
}catch (Exception e) {
e.getStackTrace();
}
return SUCCESS;
}
// other methods, properties, getters and setters
public Produit getProduit() {
return produit;
}
public void setProduit(Produit produit) {
this.produit = produit;
}
#Override
public Produit getModel() {
return produit;
}
}
The error sent is :
com.opensymphony.xwork2.config.ConfigurationException: No result defined for action actions.ProduitsAction and result input
I tried some other solutions but the best I get is a product with nom=null, prix=null, categorie=null.
I guess my problem is in these files.
I may send you the other files or methods
The entity Produit :
package entities;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
#Entity
#Table(name = "produit")
public class Produit {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String nom;
private Double prix;
#ManyToOne
#JoinColumn(name="id_categorie", nullable=true)
private Categorie categorie;
public Produit(Long id, String nom, Double prix, Categorie categorie) {
super();
this.id = id;
this.nom = nom;
this.prix = prix;
this.categorie = categorie;
}
public Produit() {}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public Double getPrix() {
return prix;
}
public void setPrix(Double prix) {
this.prix = prix;
}
public Categorie getCategorie() {
return categorie;
}
public void setCategorie(Categorie categorie) {
this.categorie = categorie;
}
}

How to retrieve an instance from the database and display it using struts2 and hibernate?

I want to display an instance of the company pojo from the database. All I am able to display is the CompanyId the rest of the details are not getting displayed.
viewCompany.jsp
`<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<s:form action="ViewCompany">
<s:textfield name="companyId" label="Enter Company ID">
<s:param name="companyId" value="company.companyId"></s:param>
</s:textfield>
<s:submit/>
</s:form>
</body>
</html>
`
I am trying to enter the companyId and the values corresponding to the id should be displayed to the display page.
CompanyBean:
`package com.buhin.POJO;
public class Company {
private int companyId;
public String companyName;
public String contactPerson;
public String mobileNumber;
public String officeNumber;
public String mail;
public String addressLine1;
public String addressLine2;
public String cityName;
public String stateName;
public String zipcode;
//public Address address;
public Company(){}
public Company(int companyId){
this.companyId = companyId;
}
public int getCompanyId() {
return companyId;
}
public void setCompanyId(int companyId) {
this.companyId = companyId;
}
public String getCompanyName() {
return companyName;
}
public String getContactPerson() {
return contactPerson;
}
public String getMobileNumber() {
return mobileNumber;
}
public String getOfficeNumber() {
return officeNumber;
}
public String getMail() {
return mail;
}
public String getAddressLine1() {
return addressLine1;
}
public String getAddressLine2() {
return addressLine2;
}
public String getCityName() {
return cityName;
}
public String getStateName() {
return stateName;
}
public String getZipcode() {
return zipcode;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public void setContactPerson(String contactPerson) {
this.contactPerson = contactPerson;
}
public void setMobileNumber(String mobileNumber) {
this.mobileNumber = mobileNumber;
}
public void setOfficeNumber(String officeNumber) {
this.officeNumber = officeNumber;
}
public void setMail(String mail) {
this.mail = mail;
}
public void setAddressLine1(String addressLine1) {
this.addressLine1 = addressLine1;
}
public void setAddressLine2(String addressLine2) {
this.addressLine2 = addressLine2;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
public void setStateName(String stateName) {
this.stateName = stateName;
}
public void setZipcode(String zipcode) {
this.zipcode = zipcode;
}
#Override
public String toString() {
return "Company [CompanyName=" + getCompanyName()
+ ", ContactPerson=" + getContactPerson()
+ ", MobileNumber=" + getMobileNumber()
+ ", OfficeNumber=" + getOfficeNumber() + ", Mail="
+ getMail() + ", AddressLine1=" + getAddressLine1()
+ ", AddressLine2()=" + getAddressLine2()
+ ", CityName()=" + getCityName() + ", StateName="
+ getStateName() + ", Zipcode=" + getZipcode()
+ "]";
}
}
ViewCompany.java(ActionClass)
`
package com.buhin.Action;
import com.buhin.POJO.*;
import com.buhin.DAO.*;
import com.opensymphony.xwork2.ActionSupport;
public class ViewCompany extends ActionSupport {
/**
*
*/
private static final long serialVersionUID = 1L;
private int companyId;
Company company;
public Company getCompany(){
return company;
}
public void setCompany(Company company){
this.company = company;
}
public int getCompanyId(){
return companyId;
}
public void setCompanyId(int companyId){
this.companyId = companyId;
}
public String execute(){
CompanyDAO cdao = new CompanyDAO();
company = cdao.viewCompany(companyId);
//System.out.println(company.toString());
return "success";
}
}
CompanyDAO:
`package com.buhin.DAO;
import com.buhin.POJO.*;
import com.buhin.hibernate.*;
import com.opensymphony.xwork2.ActionSupport;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.SessionFactory;
public class CompanyDAO extends ActionSupport{
public CompanyDAO(){
}
/**
*
*/
private static final long serialVersionUID = 1L;
Company vCompany;
public String addCompany(Company company){
SessionFactory sessionfactory = HibernateUtil.getSessionFactory();
Session session = sessionfactory.openSession();
Transaction transaction = session.beginTransaction();
session.save(company);
transaction.commit();
session.close();
return "success";
}
public Company viewCompany(int companyId){
SessionFactory sessionfactory = HibernateUtil.getSessionFactory();
Session session = sessionfactory.openSession();
vCompany = (Company) session.get(com.buhin.POJO.Company.class, companyId);
return vCompany;
}
}
`
companydetails.jsp:
`<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<s:property value="company.companyId"/>
<s:property value="company.companyName"/>
<s:property value="company.contactPerson"/>
<s:property value="company.mobileNumber"/>
<s:property value="company.officeNumber"/>
<s:property value="company.mail"/>
<s:property value="company.addressLine1"/>
<s:property value="company.addressLine2"/>
<s:property value="company.cityName"/>
<s:property value="company.stateName"/>
<s:property value="company.zipcode"/>
</body>
</html>`
`
Struts.xml:
`<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.devMode" value="true"></constant>
<package name="com.buhin.POJO" extends="struts-default">
<!-- <action name="AddCompany" class="com.buhin.Action.AddCompany" method="execute">
<result name="success">/success.jsp</result>
</action>
--> <action name="ViewCompany" class="com.buhin.Action.ViewCompany" method="execute">
<result name="success">/companydetails.jsp</result>
</action>
</package>
</struts>
`
First of all I agree with #Aleksandr M, this is a very bizarre structure. But nevertheless, there are a few things wrong with this code.
1) You are returning 'success' result from action methods, so your result should be <result name="success">/companydetails.jsp</result>
2) You are storing Company object in local variable(Company viewCompany). This will not be available in your JSP.
What you should do is make a object variable. Add setter-getters for that variable and use it in your JSP as follows.
<s:property value="viewCompany.zipcode"/>
Hope this helps.

How to forward result to another action in Struts2?

I have this action:
package com.test;
import com.opensymphony.xwork2.Action;
public class TestAction implements Action{
private String simpleParam;
public String getSimpleParam() {
return simpleParam;
}
public void setSimpleParam(String simpleParam) {
this.simpleParam = simpleParam;
}
#Override
public String execute() throws Exception {
return SUCCESS;
}
}
When it's executed I want to invoke another action inside struts(e.g. not redirect) and pass to it simpleParam. SecondAction is:
package com.test;
import com.opensymphony.xwork2.Action;
public class HelloAction implements Action {
private String id;
private String result;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getResult() {
return result;
}
#Override
public String execute() throws Exception {
result = "result" + getId();
return SUCCESS;
}
}
I saw working example when in struts.xml in result simply typed another action name and params and it worked. So I'm trying to do this:
<struts>
<package name="main" extends="struts-default">
<action name="test" class="com.test.TestAction">
<result name="success">hello.action?id=${simpleParam}</result>
</action>
<action name="hello" class="com.test.HelloAction">
<result>/hello.jsp</result>
</action>
</package>
</struts>
Idea totally sees this action but in browser I get 404 status. When I simply invoke hello.action from browser it works. Redirect also works. I also tried chain, but my param wasn't passed and it's not very convinient.
Am I doing it right? And if so what could be the cause of 404 status?
this could be helpful: http://struts.apache.org/docs/action-chaining.html
<struts>
<package name="main" extends="struts-default">
<action name="test" class="com.test.TestAction">
<result name="success" type="chain">hello</result>
</action>
<action name="hello" class="com.test.HelloAction">
<result>/hello.jsp</result>
</action>
</package>
</struts>
to pass a parameter from one action to another you could use the HttpServletRequest
(http://www.mkyong.com/struts2/how-to-get-the-httpservletrequest-in-struts-2):
TestAction.java:
package com.test;
import com.opensymphony.xwork2.Action;
public class TestAction implements Action{
private String simpleParam;
public String getSimpleParam() {
return simpleParam;
}
public void setSimpleParam(String simpleParam) {
this.simpleParam = simpleParam;
}
#Override
public String execute() throws Exception {
HttpServletRequest request = ServletActionContext.getRequest();
request.setAttribute("id", simpleParam);
return SUCCESS;
}
}
HelloAction.java:
package com.test;
import com.opensymphony.xwork2.Action;
public class HelloAction implements Action {
private String id;
private String result;
public String getId() {
return id;
}
public String getResult() {
return result;
}
#Override
public String execute() throws Exception {
HttpServletRequest request = ServletActionContext.getRequest();
id = (String)request.getAttribute("id");
result = "result" + getId();
return SUCCESS;
}
}
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/j2ee" xmlns:javaee="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/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" id="WebApp_9" version="2.4">
<display-name>Struts2 Application</display-name>
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.FilterDispatcher
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
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/j2ee" xmlns:javaee="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/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" id="WebApp_9" version="2.4">
<display-name>Struts2 Application</display-name>
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.FilterDispatcher
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
struts.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/j2ee" xmlns:javaee="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/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" id="WebApp_9" version="2.4">
<display-name>Struts2 Application</display-name>
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.FilterDispatcher
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
index.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">
<title>Insert title here</title>
</head>
<body>
View Records all
</body>
</html>
edit.jsp
<%# taglib uri="/struts-tags" prefix="s" %>
<b>id :</b> <s:property value="id"/> <br>
<b>name :</b> <s:property value="name"/> <br>
<b>salary :</b> <s:property value="salary"/> <br>
<s:textfield name="userid" label="phoneno" value="id"/>
UserAction.java
package com.action;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import com.model.User;
import com.userservice.UserService;
public class UserAction {
private int id;
private String name;
private int salary;
private int phoneno;
ArrayList<User> list=new ArrayList<User>();
public ArrayList<User> getList() {
return list;
}
public void setList(ArrayList<User> list) {
this.list = list;
}
public String execute(){
UserService service= new UserService();
list=service.getdetails();
return "success";
}
public String delete() {
System.out.println("----------");
return "success";
}
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 getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
public int getPhoneno() {
return phoneno;
}
public void setPhoneno(int phoneno) {
this.phoneno = phoneno;
}
}
UserService.java
package com.userservice;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import com.model.User;
public class UserService {
ArrayList<User> list=new ArrayList<User>();
public ArrayList<User> getdetails(){
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:#localhost:1521:xe","oracletest","oracle");
PreparedStatement ps=con.prepareStatement("select * from employee");
ResultSet rs=ps.executeQuery();
while(rs.next()){
User user=new User();
user.setId(rs.getInt(1));
user.setName(rs.getString(2));
user.setSalary(rs.getInt(3));
user.setPhoneno(rs.getInt(4));
list.add(user);
System.out.println(rs.getString(2));
}
con.close();
}catch(Exception e){e.printStackTrace();}
return list;
}
public ArrayList<User> getList() {
return list;
}
public void setList(ArrayList<User> list) {
this.list = list;
}
}
User.java
package com.model;
public class User {
private int id;
private String name;
private int salary;
private int phoneno;
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 getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
public int getPhoneno() {
return phoneno;
}
public void setPhoneno(int phoneno) {
this.phoneno = phoneno;
}
}
welcome.jsp
<%# page contentType="text/html; charset=UTF-8"%>
<%# taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>Struts2 Example</title>
</head>
<body>
<table>
<tr>
<th>id</th>
<th>Name</th>
<th>salary</th>
<th>phoneno</th>
</tr>
<s:iterator value="list" var="user">
<tr>
<td><s:property value="id"/> </td>
<td><s:property value="name"/></td>
<td><s:property value="salary"/></td>
<td><s:property value="phoneno"/></td>
<td>edit</td>
<td>edit1</td>
</tr>
</s:iterator>
</table>
</body>
</html>
</html>

insert update delete in Struts 2 but showing NullPointerException

Here I come up with problem with Operation like update,delete and view so now insert is working but other operation like update, delete, view showing error like. Could some one can guide to go right direction? This what I have tried up to now
Error:
HTTP Status 500 - java.lang.NullPointerException
type Exception report
message java.lang.NullPointerException
description The server encountered an internal error that prevented it from fulfilling this request.
exception
javax.servlet.ServletException: java.lang.NullPointerException
org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:515)
org.apache.struts2.dispatcher.FilterDispatcher.doFilter(FilterDispatcher.java:419)
root cause
java.lang.NullPointerException
Action.Testiue.view(Testiue.java:115)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:606)
com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:404)
com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:267)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:229)
com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:221)
com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:86)
com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:224)
com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:223)
com.opensymphony.xwork2.util.profiling.UtilTimerStack.profile(UtilTimerStack.java:455)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:221)
com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:150)
org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:48)
struts.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<include file="struts-default.xml" />
<package name="a" extends="struts-default">
<action name="adduser" class="Action.Testiue" method="add">
<result name="success">/insert.jsp</result>
<result name="success">/ssuccess.jsp</result>
</action>
<action name="viewuser" class="Action.Testiue" method="view">
<result name="success">/view.jsp</result>
<result name="error">/error.jsp</result>
</action>
<action name="updateuser" class="Action.Testiue" method="update">
<result name="success">/edit.jsp</result>
<result name="error">/error.jsp</result>
</action>
<action name="deleteuser" class="Action.Testiue" method="delete">
<result name="success">/dsuccess.jsp</result>
<result name="error">/error.jsp</result>
</action>
</package>
</struts>
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">
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
TestIUE.java
package Action;
import com.opensymphony.xwork2.ActionSupport;
import dao.UserDao;
import dbBean.UseBean;
public class Testiue
{
private String Name;
private String Password;
private String EmailID;
private String Phoneo;
private int ID;
public String getName()
{
return Name;
}
public void setName(String name)
{
Name = name;
}
public String getPassword()
{
return Password;
}
public void setPassword(String password)
{
Password = password;
}
public String getEmailID()
{
return EmailID;
}
public void setEmailID(String emailID)
{
EmailID = emailID;
}
public String getPhoneo()
{
return Phoneo;
}
public void setPhoneo(String phoneo)
{
Phoneo = phoneo;
}
public int getID()
{
return ID;
}
public void setID(int i)
{
ID = i;
}
#Override
public String toString()
{
return "UseBean [id=" + ID + ", Name=" + Name+ ", Password=" + Password + ", EmailID=" + EmailID + ", Phoneo="+ Phoneo + "]";
}
private UserDao dao;
private UseBean bean;
public String add()
{
dao=new UserDao();
bean=new UseBean();
System.out.println(getName()+""+getPassword()+""+getPhoneo()+""+getEmailID());
bean.setID(ID);
bean.setName(Name);
bean.setPassword(Password);
bean.setPhoneo(Phoneo);
bean.setEmailID(EmailID);
dao.addUser(bean);
return ActionSupport.SUCCESS;
}
public String update()
{
dao=new UserDao();
bean=new UseBean();
//System.out.println(getName()+""+getPassword()+""+getPhoneo()+""+getEmailID());
bean.setID(ID);
bean.setName(Name);
bean.setPassword(Password);
bean.setPhoneo(Phoneo);
bean.setEmailID(EmailID);
dao.updateUser(bean);
return ActionSupport.SUCCESS;
}
public String delete()
{
int userId =0;
dao.deleteUser(userId);
return ActionSupport.SUCCESS;
}
public String edit()
{
int userId =0;
bean = dao.getUserById(userId);
return ActionSupport.SUCCESS;
}
public String view()
{
dao.getAllUsers();
return ActionSupport.SUCCESS;
}
}
Index.jsp
<META HTTP-EQUIV="Refresh" CONTENT="0;URL=viewuser.action">
view.jsp;
<%# taglib prefix="s" uri="/struts-tags"%>
<%#page import="java.util.*,dbBean.*,Dbconnect.*,java.util.*"%>
Insert
<table border=1>
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>password</th>
<th>phoneno</th>
<th>emailid</th>
<th colspan=2>Action</th>
</tr>
</thead>
<jsp:useBean id="users" class="java.util.ArrayList" scope="request" />
<% for(int i = 0; i < users.size(); i+=1)
{
UseBean user = (UseBean)users.get(i);
%>
<tbody>
<tr>
<td><%= user.getID() %></td>
<td><%= user.getName() %></td>
<td><%= user.getPassword() %></td>
<td><%= user.getEmailID() %></td>
<td><%= user.getPhoneo() %></td>
<td>Update</td>
<td>Delete</td>
</tr>
<%
}
%>
</tbody>
</table>
edit.jsp:
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="updateuser">
id:<input type="text" name="ID" ><br/>
Name:<input type="text" name="Name" ><br/>
Password:<input type="text" name="password" ><br/>
phoneno:<input type="text" name="Phoneo" ><br/>
Emailid:<input type="text" name="Emailid" > <br/>
<input type="submit" value="Submit" />
</form>
</body>
</html>
UserDao.java
package dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import dbBean.UseBean;
import Dbconnect.*;
public class UserDao
{
private Connection conn;
public UserDao()
{
conn=Dbconnect.getConnection();
}
public void addUser(UseBean bean)
{
try
{
String sql="insert into senthil (name,pass,phoneno,emailid) values(?,?,?,?)";
PreparedStatement ps=conn.prepareStatement(sql);
ps.setString(1,bean.getName());
ps.setString(2,bean.getPassword());
ps.setString(3,bean.getPhoneo());
ps.setString(4,bean.getEmailID());
ps.executeUpdate();
}
catch (Exception e)
{
// TODO: handle exception
}
}
public void deleteUser(int userId)
{
try
{
PreparedStatement ps = conn.prepareStatement("delete from senthil where id=?");
// Parameters start with 1
ps.setInt(1, userId);
ps.executeUpdate();
} catch (SQLException e)
{
e.printStackTrace();
}
}
public void updateUser(UseBean bean)
{
try
{
PreparedStatement preparedStatement = conn.prepareStatement("update senthil set name=?, pass=?, phoneno=?, emailid=?"+ "where id=?");
// Parameters start with 1
preparedStatement.setString(1, bean.getName());
preparedStatement.setString(2, bean.getPassword());
preparedStatement.setString(3, bean.getPhoneo());
preparedStatement.setString(4, bean.getEmailID());
preparedStatement.setInt(5, bean.getID());
preparedStatement.executeUpdate();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public List<UseBean> getAllUsers()
{
List<UseBean> users = new ArrayList<UseBean>();
try
{
Statement statement = conn.createStatement();
ResultSet rs = statement.executeQuery("select * from senthil");
while (rs.next())
{
UseBean user = new UseBean();
user.setID(rs.getInt("id"));
user.setName(rs.getString("name"));
user.setPassword(rs.getString("pass"));
user.setPhoneo(rs.getString("phoneno"));
user.setEmailID(rs.getString("emailid"));
users.add(user);
}
}
catch (SQLException e)
{
e.printStackTrace();
}
return users;
}
public UseBean getUserById(int userId)
{
UseBean user = new UseBean();
try
{
PreparedStatement preparedStatement = conn.prepareStatement("select * from senthil where id=?");
preparedStatement.setInt(1, userId);
ResultSet rs = preparedStatement.executeQuery();
if (rs.next())
{
user.setID(rs.getInt("id"));
user.setName(rs.getString("name"));
user.setPassword(rs.getString("pass"));
user.setPhoneo(rs.getString("phoneno"));
user.setEmailID(rs.getString("emailid"));
}
} catch (SQLException e)
{
e.printStackTrace();
}
return user;
}
}
In the JSP the users should be available to the request scope.
public String view() {
UserDao userDao = new UserDao();
List<UseBean> users = userDao.getAllUsers();
ServletActionContext.getRequest().setAttribute("users", users);
return Action.SUCCESS;
}
public String update() {
UserDao dao = new UserDao();
UseBean bean=new UseBean();
HttpServletRequest request ServletActionContext.getRequest();
bean.setID(request.getParameter("ID");
bean.setName(request.getParameter("Name");
bean.setPassword(request.getParameter("Password");
bean.setPhoneo(request.getParameter("Phoneo");
bean.setEmailID(request.getParameter("EmailID");
//System.out.println(getName()+""+getPassword()+""+getPhoneo()+""+getEmailID());
dao.updateUser(bean);
return Action.SUCCESS;
}
public String delete() {
HttpServletRequest request ServletActionContext.getRequest();
int userId = request.getParameter("ID");
dao.deleteUser(userId);
return Action.SUCCESS;
}
for delete action
<s:param name='ID'><%=user.getID()%></s:param></s:url>">Delete
Inside view method you haven't initialized the dao object(i.e reference is null), add the following code :
In TestIUE.java add one more member variable :
List<UseBean> users = new ArrayList<UseBean>();
Also add Accessor method :
public List<UseBean> getUsers()
{
return users;
}
Now modify your view method as follows :
public String view()
{
dao = new UseDao();
users = dao.getAllUsers();
return ActionSupport.SUCCESS;
}

How to retrieve data from database using webservices (JAX - RS) in eclipse using Java

I have done inserting a record into database but I don't know how to retrieve it.
My code is:
Account.java:
package com.fetch;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Id;
public class Account implements Serializable
{
#Id
private long id;
#Column(name="NAME")
private String name;
public Account()
{
}
public Account(int id, String name)
{
this.id = id;
this.name = name;
}
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;
}
}
MyAccount.java:
package com.fetch;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Collection;
import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.persistence.Entity;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
#WebService()
#Entity
#Table(name = "CUSTOMER")
#Path("/user")
#NamedQuery(name="loginquery", query="select ID,NAME from CUSTOMER")
public class MyAccount
{
private Account ac;
public MyAccount()
{
// TODO Auto-generated constructor stub
ac = new Account();
}
#POST
#Path("/fetch")
#WebMethod(operationName = "insert")
public String insert(#FormParam("name") String name)
{
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/studentinfo", "root", "root");
String query = "insert into CUSTOMER"+"(NAME) VALUES"+"(?)";
PreparedStatement st = con.prepareStatement(query);
st.setString(1,name);
st.executeUpdate();
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
return"Record inserted successfully";
}
public Account getAc()
{
return ac;
}
public void setAc(Account ac)
{
this.ac = ac;
}
}
insert.html:
<!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=UTF-8">
<title>Insert</title>
</head>
<body>
<form action="rest/user/fetch" method="POST">
<p>
Name : <input id="name" name="name" />
</p>
<input type="submit" value="Add" />
<input type="submit" value="Retrive" />
</form>
</body>
</html>
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>FetchAndInsert</display-name>
<servlet>
<servlet-name>REST Servlet</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>com.fetch</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>REST Servlet</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
How to retrieve the data from the database when the user clicks on the retrieve button, and display all the records in another HTML form?
Please give suggestions on how to do it.
In my application, when the user clicks the retrieve button it is performing the insert operation.
But I want is, when the user clicks it should go to the another page and display the data in table from database.
Can anybody tell the mistake what I have done, and give suggestions for finding solution for it and how to display the dynamic table in other page when the user clicks the retrieve button?
Finally I have done it, Now I am able to perform both insertion and retriving of data from database using jersey(JAX - RS) webservices and able to display it in a html page.
Account.java:
package com.fetch;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Id;
public class Account implements Serializable
{
#Id
private long id;
#Column(name = "NAME")
private String name;
public Account(int id, String name)
{
this.id = id;
this.name = name;
}
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;
}
}
MyAccount.java:
package com.fetch;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.persistence.Entity;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
#WebService()
#Entity
#Path("/user")
public class MyAccount
{
#POST
#Path("/fetch")
#WebMethod(operationName = "insert")
public String insert(#FormParam("name") String name)
{
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/studentinfo", "root", "root");
String query = "insert into CUSTOMER"+"(NAME) VALUES"+"(?)";
PreparedStatement st = con.prepareStatement(query);
st.setString(1,name);
st.executeUpdate();
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
return"Record inserted successfully";
}
#GET
#Path("/retrive")
#Produces("text/html")
#WebMethod(operationName = "retrive")
public String retrive()
{
ResultSet rs = null;
String details = "";
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/studentinfo", "root", "root");
String query = "select ID,NAME from CUSTOMER";
PreparedStatement st = con.prepareStatement(query);
rs = st.executeQuery();
details = "<html><body>";
details = details + "<table border=1>";
details = details + "<tr><td><Strong>Id </Strong></td>" +
"<td><Strong>Name </Strong></td>" + "</tr>";
while (rs.next())
{
details = details + "<tr><td>" + rs.getInt("ID") + "</td>" +
"<td>" + rs.getString("NAME") + "</td></tr>";
}
details += "</table></body></html>";
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
return details;
}
}
insert.html:
<!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=UTF-8">
<title>Insert</title>
</head>
<body>
<form action="rest/user/fetch" method="POST">
<p>
Name : <input id="name" name="name" />
</p>
<input type="submit" value="Add" />
</form>
<form action="rest/user/retrive" method="GET">
<input type="submit" value="Retrive" />
</form>
</body>
</html>
my web.xml is:
<?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_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>FetchAndInsert</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>REST Servlet</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>com.fetch</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>REST Servlet</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
Jersey doesn't provide any sort of HTML templating. You need to forward your response to a jsp page or use Ajax to fetch the data and lay it out on the page.

Categories