How to forward result to another action in Struts2? - java

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>

Related

Custom debugging interceptor with JSP in Struts 2

I'm using Struts 2.
I want to create a custom interceptor debug class to display in interceptor debugging mode browser all attributes field value when user click save button.
ProduitDto:
public class ProduitDto {
private String reference;
private String designation;
private double prix;
private int quantite;
private boolean promo;
public ProduitDto(String reference, String designation, double prix, int quantite, boolean promo) {
this.reference = reference;
this.designation = designation;
this.prix = prix;
this.quantite = quantite;
this.promo = promo;
}
public ProduitDto() {
}
public String getReference() {
return reference;
}
public void setReference(String reference) {
this.reference = reference;
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
public double getPrix() {
return prix;
}
public void setPrix(double prix) {
this.prix = prix;
}
public int getQuantite() {
return quantite;
}
public void setQuantite(int quantite) {
this.quantite = quantite;
}
public boolean isPromo() {
return promo;
}
public void setPromo(boolean promo) {
this.promo = promo;
}
}
ProduitAction:
import com.id.dto.ProduitDto;
import com.id.entites.Produit;
import com.id.service.ICatalogueService;
import com.id.service.SingletonService;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
public class ProduitAction extends ActionSupport implements ModelDriven<Produit> {
private ProduitDto produitDto = new ProduitDto();
private Produit produit = new Produit();
private List<Produit> produits;
private String ref;
private boolean editMode = false;
private ICatalogueService service = SingletonService.getService();
public String index( ) {
produits = service.listProduit();
return SUCCESS;
}
public String save() {
if (!editMode)
service.ajouterProduit(produit);
else
service.miseAjourProduit(produit);
produits = service.listProduit();
return SUCCESS;
}
public String delete() {
service.supprimerProduit(ref);
produits = service.listProduit();
return SUCCESS;
}
public String edit() {
editMode = true;
produit = service.recupererProduit(ref);
service.miseAjourProduit(produit);
produits = service.listProduit();
return SUCCESS;
}
public Produit getProduit() {
return produit;
}
public String getRef() {
return ref;
}
public void setRef(String ref) {
this.ref = ref;
}
public void setProduit(Produit produit) {
this.produit = produit;
}
public List<Produit> getProduits() {
return produits;
}
public void setProduits(List<Produit> produits) {
this.produits = produits;
}
public ProduitDto getProduitDto() {
return produitDto;
}
public void setProduitDto(ProduitDto produitDto) {
this.produitDto = produitDto;
}
public boolean isEditMode() {
return editMode;
}
public void setEditMode(boolean editMode) {
this.editMode = editMode;
}
#Override
public Produit getModel() {
return produit;
}
}
JSP:
<%#taglib uri="/struts-tags" prefix="s" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Produits</title>
<link rel="stylesheet" type="text/css" href="css/style.css"/>
</head>
<body>
<div>
<s:form action="save" method="post">
<s:textfield label="REF" name="produit.reference"></s:textfield>
<s:textfield label="Designation" name="produit.designation"></s:textfield>
<s:textfield label="Prix" name="produit.prix"></s:textfield>
<s:textfield label="Quantite" name="produit.quantite"></s:textfield>
<s:checkbox label="Promo" name="produit.promo"></s:checkbox>
<!-- <s:textfield name="editMode"></s:textfield> permet de voir une valeur du model -->
<s:hidden name="editMode"></s:hidden>
<s:submit value="Save"></s:submit>
</s:form>
</div>
<div>
<table class="table1">
<tr>
<th>REF</th>
<th>DES</th>
<th>PRIX</th>
<th>QUANTITE</th>
<th>PROMO</th>
</tr>
<s:iterator value="produits">
<tr>
<td><s:property value="reference"/></td>
<td><s:property value="designation"/></td>
<td><s:property value="prix"/></td>
<td><s:property value="quantite"/></td>
<td><s:property value="promo"/></td>
<s:url namespace="/" action="delete" var="lien1">
<s:param name="ref">
<s:property value="reference"/>
</s:param>
</s:url>
<s:url namespace="/" action="edit" var="lien2">
<s:param name="ref">
<s:property value="reference"/>
</s:param>
</s:url>
<td><s:a href="%{lien1}">Suppr</s:a></td>
<td><s:a href="%{lien2}">Edit</s:a></td>
</tr>
</s:iterator>
</table>
</div>
</body>
</html>
struts.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
"http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
<package name="default" namespace="/" extends="struts-default">
<default-action-ref name="index"></default-action-ref>
<action name="index">
<result>views/index.jsp</result>
</action>
<action name="produits" class="com.id.web.ProduitAction" method="index">
<result name="success">views/Produits.jsp</result>
</action>
<action name="save" class="com.id.web.ProduitAction" method="save">
<result name="success">views/Produits.jsp</result>
<result name="input">views/Produits.jsp</result>
</action>
<action name="delete" class="com.id.web.ProduitAction" method="delete">
<result name="success">views/Produits.jsp</result>
</action>
<action name="edit" class="com.id.web.ProduitAction" method="edit">
<result name="success">views/Produits.jsp</result>
</action>
</package>
</struts>
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="struts_blank" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Struts Blank</display-name>
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
Interceptor product :
public class ProductCustomInterceptor implements Interceptor
{
private static final long serialVersionUID = 1L;
#Override
public String intercept(ActionInvocation invocation) throws Exception
{
System.out.println("ProductCustomInterceptor intercept() is called...");
System.out.println(invocation.getAction().getClass().getName());
return invocation.invoke();
}
}
How can I intercept all filed value of my class product when I click save button in my jsp page by using interceptor class with debugging mode browser?

404 page when running project through eclipse on Tomcat

Using Struts2 , I have set up a very simplistic webapp but when i run it in eclipese i got 404 error.. here is my all codes and jarfiles
URL : localhost:8985/firststruts/index.jsp
Jar files
commons-fileupload-1.3.1
commons-io-2.2
commons-lang-2.4
commons-logging-1.1.3
commons-logging-api-1.1
freemarker-2.3.19
javassist-3.11.0.GA
ognl-3.0.6
struts2-core-2.3.16.3
xwork-core-2.3.16.3
Struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts
Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<package name="default" extends="struts-default">
<action name="Product" class="com.javatpoint.Product">
<result name="success">welcome.jsp</result>
</action>
</package>
</struts>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<display-name>firstjsp</display-name>
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>*</url-pattern>
</filter-mapping>
</web-app>
product.java
public class Product {
private int id;
private String name;
private float price;
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 float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public String execute() {
return "success";
}
}
welcome.jsp
<%# taglib uri="/struts-tags" prefix="s" %>
Product Id:<s:property value="id"/><br/>
Product Name:<s:property value="name"/><br/>
Product Price:<s:property value="price"/><br/>
index.java
<%# taglib uri="/struts-tags" prefix="s" %>
<s:form action="product">
<s:textfield name="id" label="Product Id"></s:textfield>
<s:textfield name="name" label="Product Name"></s:textfield>
<s:textfield name="price" label="Product Price"></s:textfield>
<s:submit value="save"></s:submit>
</s:form>
im new to struts2 so please help me to solve this.

How to view data in struts2?

I am trying to view data from databases from jsp so now I come up with idea by without any scriplet or Java code in jsp .I have learned a modeldriven and some interceptors to use in struts.xml but I don't know how to implement it ?so could some one guide and help to go further am new to strut2 world
Beantest:
public String getId()
{
return id;
}
public void setId(String id)
{
this.id = id;
}
public String getBook()
{
return Book;
}
public void setBook(String book)
{
Book = book;
}
public String getAuthor()
{
return Author;
}
public void setAuthor(String author)
{
Author = author;
}
public String getAvailbleqty()
{
return Availbleqty;
}
public void setAvailbleqty(String availbleqty)
{
Availbleqty = availbleqty;
}
public String getCategory()
{
return Category;
}
public void setCategory(String category)
{
Category = category;
}
DataAction.java:
public List<Beantest> viewbook()
{
List<Beantest> al=new ArrayList<Beantest>();
Beantest bt = new Beantest();
try
{
String sql = "select * from Bookavaible";
Statement stmt;
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while (rs.next())
{
bt.setId(rs.getString("id"));
bt.setBook(rs.getString("Book"));
bt.setAuthor(rs.getString("Author"));
bt.setAvailbleqty(rs.getString("Availbleqty"));
bt.setCategory(rs.getString("Category"));
al.add(bt);
}
}
catch (SQLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return al;
}
Actiontest.java
public class ActionTest {
Beantest bt;
private List<Beantest> beans;
public String viewbookaction()
{
DataAction da = new DataAction();
beans = da.viewbook();
return ActionSupport.SUCCESS;
}
public List<Beantest> getBeans()
{
return beans;
}
Bookview.jsp:
<s:action name="VBA">
<td>id:</td>
<td>Book:</td>
<td>Author:</td>
<td>Availbleqty:</td>
<td>Category:</td>
</s:action>
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>BookView.jsp</welcome-file>
</welcome-file-list>
</web-app>
strut2.xml
<package name="a" namespace="/">
<action name="VBA" class="Action.ActionTest" method="viewbookaction">
<result name="success">/BookView.jsp</result>
</action>
</package>
Don't use s:action tag in JSP, until you know how and why to do that. To display values in JSP you are not needed it at all. You should use struts tags to access action bean properties. For example you can print values to the JSP out using s:property tag. For example
<s:iterator value="beans">
id: <s:property value="id"/><br>
Book: <s:property value="book"/><br>
Author: <s:property value="author"/><br>
Availbleqty: <s:property value="availbleqty"/><br>
Category: <s:property value="category"/><br>
<s:/iterator>
The FilterDispatcher is deprecated and you should replace it with StrutsPrepareAndExecuteFilter. See web.xml docs. Also see this answer for
Need suggestions regarding project implementation in Struts and Hibernate.
Change your web.xml and stuts.xml as below.
Struts.xml
<struts>
<constant name="struts.devMode" value="true" />
<package name="a" namespace="/" extends="struts-default">
<action name="" class="Action.ActionTest" method="viewbookaction">
<result name="success">/BookView.jsp</result>
</action>
</package>
web.xml
<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>
That's all. Simply run.

SelectOneMenu doesn't have any value to choose from

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

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