i've done a struts2 login action using mysql database which is as shown below.
for the initial login action i'm using LoginActionBean where i checks the username and password. After loging into the Main page there i need to get the team details again from the database. For that i used jsp scriplet tags. Can anyone tell me another way in which to access the team details from the database through javabeans (not through LoginActionBean) and without using the jsp scriplets.
login.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">
<head>
</head>
<body>
<s:form action="log">
<s:textfield label="USERNAME" name="uname"/>
<s:password label="PASSWORD" name="pass"/>
<s:submit label="SUBMIT"/>
</s:form>
</body>
</html>
Main.jsp
<%#page import="java.sql.ResultSet"%>
<%#page import="DbCon.DataConnection"%>
<%#page contentType="text/html" 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>JSP Page</title>
</head>
<body>
<h1>Welcome to Employee Home!</h1>
SELECT A TEAM:<select name="team">
<%
DataConnection db=new DataConnection();
ResultSet rs=db.exeQuery("select * from team");
while(rs.next())
{
%>
<option value="<%=rs.getString("teamname")%>" ><%=rs.getString("teamname")%></option>
<%
}
%>
</select>
</body>
</html>
struts.xml
<!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="default" extends="struts-default">
<action name="log" class="login.Action.LoginActionBean" >
<result name="success">/Main.jsp</result>
<result name="error">/login.jsp</result>
</action>
</package>
</struts>
DataConnection.java
package DbCon;
import java.io.FileInputStream;
import java.sql.*;
public class DataConnection
{
Connection con;
Statement stmt;
PreparedStatement pstmt;
ResultSet rs=null;
public DataConnection()
{
try
{
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost/test","root","");
stmt=con.createStatement();
con.setAutoCommit(false);
}catch(Exception e){
System.out.println("Err in constructor"+e);
}
}
public ResultSet exeQuery(String query)
{
try
{
// con.commit();
rs=stmt.executeQuery(query);
}catch(Exception e){System.out.println(e);}
return rs;
}
public int exeUpdate(String query)
{
int i = 0;
try
{
//con.commit();
i=stmt.executeUpdate(query);
con.commit();
}catch(Exception e){System.out.println(e);}
return i;
}
}
LoginActionBean.java
package login.Action;
import DbCon.DataConnection;
import com.opensymphony.xwork2.ActionSupport;
import java.sql.ResultSet;
import java.sql.SQLException;
public class LoginActionBean extends ActionSupport {
public String uname,pass;
public String getPass() {
return pass;
}
public void setPass(String pass) {
this.pass = pass;
}
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public String execute() throws SQLException
{
DataConnection db=new DataConnection();
ResultSet rs=db.exeQuery("select * from admin where name='"+uname+"' and pass='"+pass+"'");
if(rs.next())
return SUCCESS;
else
return ERROR;
}
}
Well you have already done most of the work, so you can do some simple things like in you action class
Create a bean say TeamDetails with properties you want to show in JSP
define this bean in your Action class and fill it using DB call
use OGN in your JSP to access data and show it using struts2 tag.
Action class:
public class TeamDetailAction extends ActionSupport{
List<TeamDetailData> teamDetails;
//getter and setter
public String execute() throws Exception{
teamDetails=fill it by retrieving from BD
}
}
TeamDetailData Java
public class TeamDetailData{
private teamMemberName;
// other properties
//getter and setters
}
on your JSP using OGNL iterator tag to show the data
JSP page
<s:iterator value="teamDetails">
<p>Name : <s:property value="teamMemberName"/></p>
</s:iterator>
Related
I am new to database and cannot find a way to handle this error. I am trying to make connection between my jsp file and sql server using eclipse. I copied my ms sql driver into WEB-INF/lib and configured "Build path" so it points to this driver but it gives error. What is my mistake, and how can I correct it ?
Here the Error Message:
Message java.lang.NullPointerException
Description The server encountered an unexpected condition that prevented it
from fulfilling the request.
Exception
org.apache.jasper.JasperException: java.lang.NullPointerException
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrap per.java:572)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:48
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:386)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:330)
javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
Root Cause
java.lang.NullPointerException
org.apache.jsp.Datab_jsp$Actor.getActors(Datab_jsp.java:54)
org.apache.jsp.Datab_jsp._jspService(Datab_jsp.java:193)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:44
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:386)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:330)
javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
Note The full stack trace of the root cause is available in the server logs.
My Code in jsp file:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# page import ="java.sql.*" %>
<%# page import=" javax.sql.DataSource" %>
<% Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); %>
<!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>
<%!
public class Actor {
String URL = "jdbc:sqlserver://localhost:1433/demo";
String username = "root";
String password = "7170256aziz";
Connection connection = null;
PreparedStatement selectActors = null;
ResultSet resultSet = null;
public Actor(){
try {
connection = DriverManager.getConnection(URL, username, password);
selectActors = connection.prepareStatement("SELECT name, id, address FROM demo");
} catch(SQLException e){
e.printStackTrace();
}
}
public ResultSet getActors(){
try{
resultSet = selectActors.executeQuery();
} catch (SQLException e){
e.printStackTrace();
}
return resultSet;
}
}
%>
<%
Actor actor = new Actor();
ResultSet actors = actor.getActors();
%>
Try to add Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); in Actor()
public Actor(){
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
connection = DriverManager.getConnection(URL, username, password);
selectActors = connection.prepareStatement("SELECT name, id, address FROM demo");
} catch(SQLException e){
e.printStackTrace();
}
}
I solved this. What I did was:
Changed the driver 6.4 to 4.0
Changed URL syntax to "jdbc:sqlserver://localhost;databaseName=demo;integratedSecurity=true;"
Changed "SELECT name, id, address FROM demo" to "SELECT name, id, address FROM people", where people is my table name
Copied sqljdbc_auth.dll to Windows/system32
Thereafter error messages gone.
I want to create a web client with Angularjs for a REST api using SpringBoot and #RestController
here is the entity Product:
package com.agTest.entities;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
public class Product implements Serializable{
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Long idProduct;
private String description;
private double prix;
public Product() {
super();
// TODO Auto-generated constructor stub
}
public Product(String description, double prix) {
super();
this.description = description;
this.prix = prix;
}
public Long getIdProduct() {
return idProduct;
}
public void setIdProduct(Long idProduct) {
this.idProduct = idProduct;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public double getPrix() {
return prix;
}
public void setPrix(double prix) {
this.prix = prix;
}
}
here is my ProductRepository interface using JpaRepository:
package com.agTest.Dao;
import org.springframework.data.jpa.repository.JpaRepository;
import com.agTest.entities.Product;
public interface ProductRepository extends JpaRepository<Product, Long>{
}
here is my ProductMetier interface:
package com.agTest.services;
import java.util.List;
import com.agTest.entities.Product;
public interface ProductMetier {
public Product saveProduct(Product p);
public List<Product> getProducts();
}
here is my ProductMetierImpl class:
package com.agTest.services;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.agTest.Dao.ProductRepository;
import com.agTest.entities.Product;
#Service
public class ProductMetierImpl implements ProductMetier{
#Autowired
private ProductRepository productRepository;
#Override
public Product saveProduct(Product p) {
productRepository.save(p);
return p;
}
#Override
public List<Product> getProducts() {
return productRepository.findAll();
}
}
here is my #RestController class:
package com.agTest.RestServices;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.agTest.entities.Product;
import com.agTest.services.ProductMetier;
#RestController
public class ProductRestService {
#Autowired
private ProductMetier productMetier;
#RequestMapping(value="/products", method=RequestMethod.POST)
public Product saveProduct(#RequestBody Product p){
return productMetier.saveProduct(p);
}
#RequestMapping(value="/products", method=RequestMethod.GET)
public List<Product> getProducts(){
return productMetier.getProducts();
}
}
here is my application.properties:
# Datasource settings:
spring.datasource.url = jdbc:mysql://localhost:3306/agence_test
spring.datasource.username = root
spring.datasource.password =
spring.datasource.driver-class-name = com.mysql.jdbc.Driver
spring.jpa.database = MYSQL
spring.jpa.show-sql = true
spring.jpa.hibernate.ddl-auto = update
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
I have tested my api with postman and everything is going well but when i tried to create the angularjs client, the http Post method return an exception:
here is my angularjs controller:
var app=angular.module("AVG",[]);
app.controller("AVGController",function($scope,$http){
$scope.products=[];
$scope.description=null;
$scope.prix=null;
$scope.getProducts= function(){
$http.get("/products")
.success(function(data){
$scope.products=data;
})
.error(function(data){
alert("error");
});
};
// headers :{'Content-Type':'application/json'}
$scope.saveMembre= function(){
$http({
method : 'POST',
url : "/products",
data : "description="+$scope.description+"prix="+$scope.prix,
headers :{'Content-Type':'application/json'}
})
.success(function(data){
alert("success");
})
.error(function(data){
alert("error");
});
};
});
here is my index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<link rel="stylesheet" type="text/css" href=""bootstrap-3.3.6-dist/css/bootstrap.min.css""/>
<title>Agence Test</title>
</head>
<body ng-app="AVG" ng-controller="AVGController">
<h1>AVE.com</h1>
<!-- Sauvegarde des Membres -->
<div>
<form>
<label>Description</label>
<input type="text" ng-model="description"/>
<label>Prix</label>
<input type="text" ng-model="prix"/>
<button ng-click="saveMembre()"> SAVE </button>
</form>
</div>
<!-- Affichage des Membres -->
<div >
<button type="button" ng-click="getProducts()">Get Products</button>
<table>
<tr>
<th>ID</th> <th>DESCRIPTION</th> <th>PRIX</th>
</tr>
<tr ng-repeat="item in products">
<td>{{item.idProduct}}</td>
<td>{{item.description}}</td>
<td>{{item.prix}}</td>
</tr>
</table>
<!-- <ul>
<li ng-repeat="item in membres"> {{item.idMembre}}</li>
<li ng-repeat="item in membres"> {{item.nomMembre}}</li>
</ul> -->
</div>
<script type="text/javascript" src="angular/angular.min.js"></script>
<script type="text/javascript" src="js/app.js"></script>
</body>
</html>
here is the exception returned when calling http post method:
Hibernate: select product0_.id_product as id_produ1_0_, product0_.description as descript2_0_, product0_.prix as prix3_0_ from product product0_
Hibernate: select product0_.id_product as id_produ1_0_, product0_.description as descript2_0_, product0_.prix as prix3_0_ from product product0_
Hibernate: select product0_.id_product as id_produ1_0_, product0_.description as descript2_0_, product0_.prix as prix3_0_ from product product0_
Hibernate: select product0_.id_product as id_produ1_0_, product0_.description as descript2_0_, product0_.prix as prix3_0_ from product product0_
Hibernate: select product0_.id_product as id_produ1_0_, product0_.description as descript2_0_, product0_.prix as prix3_0_ from product product0_
2016-05-10 18:03:33.978 WARN 5420 --- [nio-8080-exec-1] .w.s.m.s.DefaultHandlerExceptionResolver : Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: Could not read document: Unrecognized token 'description': was expecting ('true', 'false' or 'null')
at [Source: java.io.PushbackInputStream#22dbf53d; line: 1, column: 13]; nested exception is com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'description': was expecting ('true', 'false' or 'null')
at [Source: java.io.PushbackInputStream#22dbf53d; line: 1, column: 13]
the http get method works as expected
please any help I need it in my PEF and i spent a lot of time on it!!!!
The 'data' expected by $http post is an object, not a string.
Try:
data : {"description":$scope.description, "prix":$scope.prix}
There is no problem with your spring code. The only problem here is how your request is sending the values
In your ajax request ($http) you need to send the request in this form
data : {"property1":value1, "property2": value2, ....,"propertyN" : value"}
You can see the values that are going in the developer tools network tab.
Hope this be of some help.
Happy Learning :)
Hello I am developing an ADF Web application. In this I have test.jsf page and a showPrintablePage behaviour command button. When user click the button adf just shows a printable page in new window. But when the user clicks on the button it should directly show in print window of browser. For this I got the following code from ADF Code Corner.
public void beforePhaseMethod(PhaseEvent phaseEvent) {
if (phaseEvent.getPhaseId() == PhaseId.RENDER_RESPONSE) {
FacesContext fctx = FacesContext.getCurrentInstance();
AdfFacesContext adfFacesContext = AdfFacesContext.getCurrentInstance();
if (adfFacesContext.getOutputMode() == OutputMode.PRINTABLE) {
ExtendedRenderKitService erks = null;
erks = Service.getRenderKitService(fctx, ExtendedRenderKitService.class);
erks.addScript(fctx, "window.print();");
}
}
}
I have follwed the process specified in the document. And the follwoing is the test.jsf page code.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%# page contentType="text/html;charset=UTF-8"%>
<%# taglib uri="http://xmlns.oracle.com/adf/faces/rich" prefix="af"%>
<%# taglib uri="http://java.sun.com/jsf/core" prefix="f"%>
<f:view beforePhase="#{viewScope.PieBean.beforePhaseMethod}">
<af:document title="printTest" id="d1">
<af:form id="f1">
<af:commandButton text="commandButton 1" id="cb1">
<af:showPrintablePageBehavior/>
</af:commandButton>
<af:goButton text="goButton 1" id="gb1"/>
</af:form>
</af:document>
</f:view>
but it is showing in test.jsf property inspector beforePhaseMethod is an unknown property.
And the final out is as follows
Please help.
Thanks in advance.
Did you register the bean in adfc-config or if you are using the taskflow, then in taskflow configuration. Also from the screenshot, it seems you are getting the desired output.
I am following the code in http://www.codejava.net/coding/upload-files-to-database-servlet-jsp-mysql. I have modified some of the code, and it is now working. The problem I have now is, I've also added the "select * from contact" to see the value of the uploaded file, but the value stored in its field is in binary format (the datatype in the database is varbinary)
Is it possible to convert the binary data into String, so that when it is stored in the database, the value is already in String format? And that when I do the "select * from contact", the value for the field displayed will be in String format?
FileUploadDB.java
package com.process.web.controller;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
#WebServlet("/fileuploaddb.html")
#MultipartConfig(maxFileSize = 16177215)
public class FileUploadDB extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
private String dbURL = "jdbc:jtds:sqlserver://localhost:1433;DatabaseName=ATS;SelectMethod=cursor;";
private String dbUser = "sa";
private String dbPass = "benilde";
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// gets values of text fields
String firstName = request.getParameter("firstName");
String lastName = request.getParameter("lastName");
InputStream inputStream = null; // input stream of the upload file
// obtains the upload file part in this multipart request
Part filePart = request.getPart("photo");
if (filePart != null) {
// prints out some information for debugging
System.out.println(filePart.getName());
System.out.println(filePart.getSize());
System.out.println(filePart.getContentType());
// obtains input stream of the upload file
inputStream = filePart.getInputStream();
}
Connection conn = null; // connection to the database
String message = null; // message will be sent back to client
try {
// connects to the database
//DriverManager.registerDriver(new com.mysql.jdbc.Driver());
//DriverManager.getConnection(dbURL);
//com.microsoft.sqlserver.jdbc.Driver
Class.forName("net.sourceforge.jtds.jdbc.Driver").newInstance();
conn = DriverManager.getConnection(dbURL, dbUser, dbPass);
if(conn!=null) {
System.out.println("Connection Successful!");
} else {
System.out.println("Error in Connection");
}
// constructs SQL statement
String sql = "INSERT INTO contact (firstname, lastname, photo) values (?, ?, ?)";
PreparedStatement statement = conn.prepareStatement(sql);
statement.setString(1, firstName);
statement.setString(2, lastName);
if (inputStream != null) {
// fetches input stream of the upload file for the blob column
statement.setBinaryStream(3, filePart.getInputStream(), (int)(filePart.getSize()));
}
// sends the statement to the database server
int row = statement.executeUpdate();
if (row > 0) {
message = "File uploaded and saved into database";
}
} catch (SQLException ex) {
message = "ERROR: " + ex.getMessage();
ex.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (conn != null) {
// closes the database connection
try {
conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
// sets the message in request scope
request.setAttribute("Message", message);
// forwards to the message page
getServletContext().getRequestDispatcher("/Message.jsp").forward(request, response);
}
}
}
This is the upload.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>File Upload to Database Demo</title>
</head>
<body>
<center>
<h1>File Upload to Database Demo</h1>
<form method="post" action="fileuploaddb.html" enctype="multipart/form-data">
<table border="0">
<tr>
<td>First Name: </td>
<td><input type="text" name="firstName" size="50"/></td>
</tr>
<tr>
<td>Last Name: </td>
<td><input type="text" name="lastName" size="50"/></td>
</tr>
<tr>
<td>Portrait Photo: </td>
<td><input type="file" name="photo" size="50"/></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Save">
</td>
</tr>
</table>
</form>
</center>
</body>
</html>
**This is the Message.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>Message</title>
</head>
<body>
<center>
<h3><%=request.getAttribute("Message")%></h3>
</center>
</body>
</html>
AbstractMethodError means your JDBC driver's PreparedStatements don't implement
setBlob(int, InputStream).
Just saw the driver you are using and according to the documentation it doesnt take
`setBlob(int, InputStream)`
But instead it takes
setBlob(int parameterIndex, java.sql.Blob x)
Read this document http://jtds.sourceforge.net/doc/net/sourceforge/jtds/jdbc/JtdsPreparedStatement.html for further help or else I would suggest you to change the driver you are using.
Refer to this SO post
I am trying to build a simple app using google app engine, with java and JDO.
my application creates Sale objects and persists them to the datastore, once persisted i attempt to list using a query, ALL the Sales in the datastore.
however sometimes the list is missing one or two of the last persisted Sales, refreshing the browser a few times will eventually make all Sales listed.
even when i click the "add sale" button very slowly (once every 3 seconds or so) there is still no guarantee that ALL persisted Sales will be retrieved from the query.
there must be a way to ensure that a query returns ALL Sales, i have tried using transactions and no luck, however i may have used it wrong, any advice would be appreciated.
Here is my Sale object:
import java.util.Date;
import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;
import com.google.appengine.api.datastore.Key;
#PersistenceCapable(detachable="true")
public class Sale {
#PrimaryKey
#Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
private Key key;
#Persistent
private String title;
#Persistent
private Date valuationDate;
public Sale(){
}
//getters and setters
This is my utility class:
public class SaleUtil {
public static void addSale(){
PersistenceManager pm = PMF.get().getPersistenceManager();
Sale s = new Sale();
s.setTitle("new sale");
s.setValuationDate(new Date());
try{
pm.makePersistent(s);
} catch (Exception e){
System.out.println(e);
} finally {
pm.close();
}
}
public static List<Sale> getSales(){
List<Sale> sales = new ArrayList<Sale>();
PersistenceManager pm = PMF.get().getPersistenceManager();
Query query = pm.newQuery(Sale.class);
query.setOrdering("valuationDate desc");
try{
List<Sale> results = (List<Sale>)query.execute();
if(!results.isEmpty()){
for(Sale s: results){
Sale detached = pm.detachCopy(s);
sales.add(detached);
}
}
} catch (Exception e){
System.out.println(e);
} finally {
query.closeAll();
pm.close();
}
return sales;
}
}
This is my home page:
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%# page import="java.util.List" %>
<%# page import="javax.jdo.PersistenceManager" %>
<%# page import="javax.jdo.Query" %>
<%# page import="com.grc.tradesharx.*" %>
<!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>
<form action="/tradesharx" method="post">
<input type="submit" value="add sale"/>
</form>
<%
List<Sale> sales = SaleUtil.getSales();
out.println(sales.size()+"<br/>");
for(Sale s : sales){
out.println(s+"<br/>");
}
%>
</body>
</html>
and this is my servlet:
package com.grc.tradesharx;
import java.io.IOException;
import javax.servlet.http.*;
#SuppressWarnings("serial")
public class TradeSharxServlet extends HttpServlet {
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
SaleUtil.addSale();
resp.sendRedirect("index.jsp");
}
}
please help me, i know i am missing something.
If you are using the High Replication Datastore (HRD), queries outside of entity groups are eventual consistent. It means it can take some time before new objects are replicated and returned in a regular non-ancestor query.
The solution for you is to use entity groups/ancestor queries for the data you need to be consistent.
... in the High Replication datastore, queries across entity
groups (in other words, non-ancestor queries) may return stale
results. In order to return strongly consistent query results in the
High Replication environment, you need to query over a single entity
group. This type of query is called an ancestor query.
Ancestor queries work because entity groups are a unit of consistency:
all operations are applied to the entire group. Ancestor queries won't
return data until the entire entity group is up to date. Thus, the
data returned from ancestor queries on entity groups is strongly
consistent.
http://code.google.com/intl/sv-SE/appengine/docs/java/datastore/hr/overview.html