This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I'm beginner with Java EE, when I try to transfer an object between a JSP and a Servlet I use a session.
For an homework, I have to create an e-commerce website.
I just have this in my jsp:
HttpSession sess = request.getSession();
Panier pan = new Panier();
sess.setAttribute("panier", pan);
sess.setAttribute("produit", produits.get(0));
produits is an arraylist of "produit" object.
In my Servlet:
HttpSession sess = request.getSession();
Panier pan = (Panier) sess.getAttribute("panier");
Produit p1 = (Produit) sess.getAttribute("prod");
When I'm here, all works cause I can display the good attributes of the object pan or p1. But, when I use my method "ajouterProduit" (addProduct in English), a savage null pointer exception appears.
My class "Produit":
public class Produit implements java.io.Serializable{
private String nom;
private int prix;
public Produit(String name, int price){
this.nom = name;
this.prix = price;
}
public void setNom(String n){
this.nom = n;
}
public void setPrix(int p){
this.prix = p;
}
public String getNom(){
return this.nom;
}
public int getPrix(){
return this.prix;
}
}
My class "Panier" (basket in english):
public class Panier implements Serializable{
private List<Produit> panier;
private static int montant = 0;
public Panier(){
panier = new ArrayList<>();
}
public void ajouterProduit(Produit p1){
panier.add(p1);
montant = montant + p1.getPrix();
}
public void ajouterProduit(Produit p1, Produit p2){
panier.add(p1);
montant = montant + p1.getPrix();
panier.add(p2);
montant = montant + p2.getPrix();
}
public void ajouterProduit(Produit p1, Produit p2,Produit p3){
panier.add(p1);
montant = montant + p1.getPrix();
panier.add(p2);
montant = montant + p2.getPrix();
panier.add(p3);
montant = montant + p3.getPrix();
}
public List<Produit> getPanier(){
return panier;
}
public int getMontantTotal(){
return montant;
}
}
Thanks in advance for help ! ;)
You add your "produit" like so:
sess.setAttribute("produit", produits.get(0));
But you retrieve it like so:
Produit p1 = (Produit) sess.getAttribute("prod");
"prod" and "produit" are 2 different session names. Your "produit" is not in "prod" session.
You store your product in the produit session, but you retrieve it from a prod session, which does not exist.
p1 is, therefore, null.
Related
This is the class and it's constructor that I made. No problems while compiling.
public class Usuario
{
private String usuario="a";
private String contrasena="a";
private String nombre="a";
private String apellido="a";
private int dni=0;
private int edad=0;
public Usuario (String usuario, String contrasena, String nombre, String apellido, int dni, int edad)
{
this.usuario=usuario;
this.contrasena=contrasena;
this.nombre=nombre;
this.apellido=apellido;
this.dni=dni;
this.edad=edad;
}
And this is my main code where I use the constructor.
public class userTest
{
public static void main (String args[])
{
Usuario philip;
philip=new Usuario (user987, pass123, Philip, Fry, 11000111, 21);
}
}
When compiling this part, the javac shows that error.
philip=new Usuario (user987, pass123, Philip, Fry, 11000111, 21);
The first 4 parameters are not defined.
If you are attempting to pass String values to the constructor, then the code should be:
philip= new Usuario ("user987", "pass123", "Philip", "Fry', 11000111, 21);
Here is the problem I am currently having. My DAO class returns data in index but I want to return the selected data to client in JSON format. How can I do it?
The controller class which returns data in json format.
MyController.java
#RequestMapping(value = "/ohlc",method = RequestMethod.POST)
public #ResponseBody List<OhlcResponse> getOhlc(#RequestBody OhlcRequest ohlcRequest) {
List<OhlcResponse> ohlc = ohlcService.getOhlc(ohlcRequest);
return ohlc;
}
Dao class returns 4 datas (minprice, maxprice, closingprice and previousclosingprice) by executing stored procedure.
OhlcDaoImpl.java
public List<OhlcResponse> getOhlc(OhlcRequest ohlcRequest) {
session = sessionFactory.openSession();
SQLQuery q = session.createSQLQuery("EXEC uspGetOhlc :StockCode, :fromDate, :toDate");
q.setString("StockCode",ohlcRequest.getStockSymbol());
q.setDate("fromDate",ohlcRequest.getFromDate());
q.setDate("toDate", ohlcRequest.getToDate());
List<OhlcResponse> l = q.list();
return l;
}
My stored procedure
USE WealthFeedSrv
GO
CREATE PROCEDURE uspGetOhlc
#StockCode varchar(50),
#fromDate date,
#toDate date
AS
BEGIN
SELECT spd.ClosingPrice, spd.PreviousClosingPrice, spd.MinPrice, spd.MaxPrice
FROM StockPriceDetl spd
inner join Stock stk on stk.Id = spd.StockId
inner join StockPriceMast spm on spm.Id = spd.MastId
WHERE stk.StockSymbol= #StockCode AND spm.TranDate Between #fromDate and #toDate
END
GO
The pojo class I want returned data to bind.
OhlcResponse.java
public class OhlcResponse {
private BigDecimal MaxPrice;
private BigDecimal MinPrice;
private BigDecimal PreviousClosingPrice;
private BigDecimal ClosingPrice;
public BigDecimal getMaxPrice() {
return MaxPrice;
}
public void setMaxPrice(BigDecimal maxPrice) {
MaxPrice = maxPrice;
}
public BigDecimal getMinPrice() {
return MinPrice;
}
public void setMinPrice(BigDecimal minPrice) {
MinPrice = minPrice;
}
public BigDecimal getPreviousClosingPrice() {
return PreviousClosingPrice;
}
public void setPreviousClosingPrice(BigDecimal previousClosingPrice) {
PreviousClosingPrice = previousClosingPrice;
}
public BigDecimal getClosingPrice() {
return ClosingPrice;
}
public void setClosingPrice(BigDecimal closingPrice) {
ClosingPrice = closingPrice;
}
public OhlcResponse(){
}
}
The result i want
"maxPrice":"200",
"minPrice":"300",
"ClosingPrice":"400",
"PreviousClosingPrice":"500"
The error says cannot cast to OhlcResponse. How can I bind the object returned by OhlcDao into OhlcResponse class and return JSON Format?
I have these codes:
public class CentroImpl implements Centro {
//Atributos
private String nombre;
private String direccion;
private Integer numeroPlantas;
private Integer numeroSotanos;
public Set<Espacio> espacio;
//Constructor
public CentroImpl(String nombre, String direccion, Integer numeroPlantas, Integer numeroSotanos){
checkPlantas(numeroPlantas);
checkSotanos(numeroSotanos);
this.nombre = nombre;
this.direccion = direccion;
this.numeroPlantas = numeroPlantas;
this.numeroSotanos = numeroSotanos;
this.espacio = new TreeSet<Espacio>();
}
#Override
public Set<Despacho> getDespachos() {
}
getDespacho is supposed to go through the list of 'Espacios' (places) in a building (centro) and tell me how many of them are Despachos (offices). As you can see in Espacio class there is a type defined.
public class EspacioImpl implements Espacio {
//Atributos
private TipoEspacio tipo;
private String nombre;
private Integer planta;
private Integer aforo;
//Constructores
public EspacioImpl(TipoEspacio tipo, String nombre, Integer planta, Integer aforo) {
checkerAforo(aforo);
this.nombre = nombre;
this.planta = planta;
this.aforo = aforo;
this.tipo = tipo;
}
But I have not learned yet how to access it, and I haven't been able to find anything understandable around. Thank you for your help.
Assuming Despacho extends Espacio and TipoEspacio is enum:
#Override
public Set<Despacho> getDespachos() {
Set<Despacho> despachos = new HashSet<Despacho>();
for (Espacio e : espacio) {
// Not sure, depends on the definition of TipoEspacio
if (e.getTipo() == TipoEspacio.DESPACHO && e instanceof Despacho) {
despachos.put((Despacho)e);
}
}
return despachos;
}
This answer assumes that you have a collection of EspacioImpls called espacios, and that the enum name for a Despacho is Despacho. You then have to do something with numDespachos (like return it). This also assumes that EspacioImpl has a method called getTipo. You need this because the tipo member is private, and so it cannot be accessed outside the class without having a getter.
int numDespachos = 0;
for(EspacioImpl e : espacios)
{
if(e.getTipo() == TipoEspacio.Despacho)
++numDespachos;
}
I have the object Usuario, I want to update it into the database, but it only save the changes in some attributtes.
#Entity
public class Usuario {
#Id
String nombre_Usuario;
String contrasena;
String estado;
#OneToOne(cascade = CascadeType.ALL, fetch=FetchType.EAGER)
#PrimaryKeyJoinColumn
Posicion miPosicion;
}
#Entity
public class Posicion {
#Id
int id;
float latitud;
float longitud;
float altura;
public Posicion() {
id = (int) Math.floor(Math.random()*1000);
latitud = longitud = altura = 0;
}
public Posicion(float alatitud, float alongitud, float aaltura) {
id = (int) Math.floor(Math.random()*1000);
latitud = alatitud;
longitud = alongitud;
altura = aaltura;
}
I'm working with a restfull service and when I want to change the object I do:
Usuario u = new Usuario();
u = todoService.obtenerUsuarioBusqueda("user_name"); //Here I get the object I want to change
u.setEstado("New Estado");
u.setmiPosicion(new Posicion(10,10,10));
todoService.saveUsuario(u);
public String saveUsuario(Usuario u){
try{
entityManager.merge(u);
}catch(Exception e){
return "false"+e.getMessage();
}
return "true";
}
I make this for update the object in the database. And when I make a find(u), the estado is "New Estado", but when I try to get the attribute miPosicion it is null.
Just after making u.setmiPosicion(), if I make u.getmiPosicion() it is correct, the Posicion I have set. But when I make it from the object from find(u) it is null.
I'm using Hibernate + HSQL on JBOSS server, I need to saveOrUpdate() an Object which has an ID represented by another class:
public class RideId implements java.io.Serializable {
private int beginPop;
private int endPop;
private String requestUser;
public RideId() {
}
public RideId(int beginPop, int endPop, String requestUser) {
this.beginPop = beginPop;
this.endPop = endPop;
this.requestUser = requestUser;
}
...
so, "RideID" is the ID of the entity "Ride"
public class Ride implements java.io.Serializable {
private RideId id;
private User userByRequestUser;
private User userByAcceptUser;
private Pop pop;
private Boolean rideStatus;
public Ride() {
}
public Ride(RideId id, User userByRequestUser, Pop pop) {
this.id = id;
this.userByRequestUser = userByRequestUser;
this.pop = pop;
}
public Ride(RideId id, User userByRequestUser, User userByAcceptUser,
Pop pop, Boolean rideStatus) {
this.id = id;
this.userByRequestUser = userByRequestUser;
this.userByAcceptUser = userByAcceptUser;
this.pop = pop;
this.rideStatus = rideStatus;
}
...
how can I saveOrUpdate() a new Object of type Ride?
Thanks everyone and sorry for my english!
It's simple. You need to create first a new RideId, assign it to a new Ride and call saveOrUpdate with the Ride.
RideId id = new RideId(1, 2, "someuser");
Ride ride = new Ride(id, ...);
session.saveOrUpdate(ride);