Data not sent to MySQL database while using Spring - java

I am new to Spring Framework and java. I was creating Registration Module for my Web App. I created DAO, DTO, Dispatcher Servlet, controller and all. When I submit the form it redirects me to where I want to go but no data are added to the Database..
My userDTO.java
package com.lagan.dto;
public class userDto{
public String userId;
public String firstName;
public String lastName;
public String birthDate;
public int gender;
public String email;
public String password;
public String getUserId() {
return userId;
}
public String getUserId(String userId) {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getBirthDate() {
return birthDate;
}
public void setBirthDate(String birthDate) {
this.birthDate = birthDate;
}
public int getGender() {
return gender;
}
public void setGender(int gender) {
this.gender = gender;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password){
this.password = password;
}
}
userDao.java
package com.lagan.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import com.lagan.dbconnector.dbconnect;
import com.lagan.dto.userDto;
public class userDao {
public void create (userDto user) {
dbconnect db=new dbconnect();
Connection con=null;
try{
con=db.getConnections();
String sql="insert into tbluser values(?,?,?,?,?,?,?)";
PreparedStatement pre=con.prepareStatement(sql);
pre.setString(1,user.getUserId());
pre.setString(2,user.getFirstName());
pre.setString(3,user.getLastName());
pre.setString(4,user.getBirthDate());
pre.setInt(5,user.getGender());
pre.setString(6,user.getEmail());
pre.setString(7,user.getPassword());
pre.executeUpdate();
pre.close();
}catch (Exception e) {
e.printStackTrace();
}finally {
db.closeConnection(con);
}
}
}
userController.java
package com.lagan.controller;
import java.util.List;
import com.lagan.dao.userDao;
import com.lagan.dto.userDto;
public class userController {
public void create(userDto userDto){
userDao dao=new userDao();
dao.create(userDto);
}
}
Verification.jsp
<%# page import="com.lagan.controller.*,com.lagan.dto.*"%>
<%
String userId="aqwery";
String firstName=request.getParameter("firstName");
String lastName=request.getParameter("lastName");
String birthDate=request.getParameter("birthDate");
//int gender=request.getParameter("gender");
String email=request.getParameter("email");
String password=request.getParameter("password");
userDto dto=new userDto();
dto.getUserId(userId);
dto.setFirstName(firstName);
dto.setLastName(lastName);
dto.setBirthDate(birthDate);
//dto.setGender(gender);
dto.setEmail(email);
dto.setPassword(password);
userController uC=new userController();
uC.create(dto);
response.sendRedirect("home.html");
%>
dbconnect.java
package com.lagan.dbconnector;
import java.sql.*;
//import java.sql.Connection;
//import java.sql.DriverManager;
//import java.sql.SQLException;
public class dbconnect {
public dbconnect()
{
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public Connection getConnections() {
Connection conn=null;
try{
conn=DriverManager.getConnection("jdbc:mysql://localhost:80/project_lagan","root","");
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
public void closeConnection(Connection con){
if(null!=con) {
try{
con.close();
}catch(SQLException e){}
}
}
}
It redirects me to home.html but the datas are not added to the database. I don't know what i am doing wrong. Please Help.

Try changing the port number of connection string to either of these:
`jdbc:mysql://localhost:3306/project_lagan`
or
`jdbc:mysql://localhost/project_lagan`

I will suggest you connecting like that
String url = "jdbc:mysql://localhost:3306/project_lagan";
String user = "root";
String password = "";
Connection conn = null;
try(conn = DriverManager.getConnection(url, user, password);) {
// processing here
} catch(SQLException e) {
System.out.println(e.getMessage());
}
You can check this tutorial also.

Related

Hibernate does not insert the information into the database

I'm trying to sort of login with JPA and hibernate. The truth is that I'm new to working with hibernate and I don't know what I'm doing wrong.
I have two entity classes (User and Credential), and I have already mapped them in the persistence.xml file
<!-- Define Persistence Unit -->
<persistence-unit name="HibernateSchedule" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>ues.edu.sv.entity.User</class>
<class>ues.edu.sv.entity.Credential</class>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/diary?useSSL=false&useTimezone=true&serverTimezon=UTC&allowPublicKeyRetrieval=true"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.password" value="localhost"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
</properties>
</persistence-unit>
These are the entity classes:
package ues.edu.sv.entity;
import java.io.Serializable;
import javax.persistence.*;
#Entity
#NamedQueries({
#NamedQuery(name="User.listAllUsers", query="SELECT u FROM User u")
})
#Table(name = "\"user\"")
public class User implements Serializable{
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name = "id_user")
private int idUser;
private String name;
#Column(name = "lastname")
private String lastName;
private String email;
public User(){}
public User(int idUser){
this.idUser = idUser;
}
public User(String name, String lastName, String email){
this.name = name;
this.lastName = lastName;
this.email = email;
}
public User(int idUser, String name, String lastName, String email){
this.idUser = idUser;
this.name = name;
this.lastName = lastName;
this.email = email;
}
public int getIdUser() {
return idUser;
}
public void setIdUser(int idUser) {
this.idUser = idUser;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Override
public String toString() {
return "User{" + "idUser=" + idUser + ", name=" + name + ", lastName=" + lastName + ", email=" + email + '}';
}
}
This is the Credential class
package ues.edu.sv.entity;
import java.io.Serializable;
import javax.persistence.*;
#Entity
#NamedQueries({
#NamedQuery(name = "Credential.getAllCredentials", query = "SELECT c FROM Credential
c")
})
#Table(name = "credential")
public class Credential implements Serializable{
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name = "id_credential")
private int idCredential;
#Column(name = "username")
private String userName;
private String password;
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "id_user", referencedColumnName = "id_user")
private User user;
public Credential(){}
public Credential(int idCredential){
this.idCredential = idCredential;
}
public Credential(String userName, String password){
this.userName = userName;
this.password = password;
}
public Credential(String userName, String password, User user){
this.userName = userName;
this.password = password;
this.user = user;
}
public Credential(int idCredential,String userName, String password){
this.idCredential = idCredential;
this.userName = userName;
this.password = password;
}
public int getIdCredential() {
return idCredential;
}
public void setIdCredential(int idCredential) {
this.idCredential = idCredential;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
#Override
public String toString() {
return "Credential{" + "idCredential=" + idCredential + ", userName=" + userName + ", password=" + password + ", user=" + user + '}';
}
}
I am using a three layer pattern to retrieve the information, so I have a package "ues.edu.sv.dao" where I have two interfaces and two classes that implement them and are defined as ejb
package ues.edu.sv.dao;
import java.util.List;
import ues.edu.sv.entity.User;
public interface UserDao {
public List<User> listAllUsers();
public User getUserById(User user);
public void createNewUser(User user);
public void updateUser(User user);
public void deleteUser(User user);
}
package ues.edu.sv.dao;
import java.util.List;
import ues.edu.sv.entity.Credential;
public interface CredentialDao {
public List<Credential> getAllCredentials();
public Credential getCredentialById(Credential credential);
public Credential getCredentialByUserName(Credential credential);
public void createNewCredential(Credential credential);
public void updateCredential(Credential credential);
public void deleteCredential(Credential credential);
}
And here are the classes that implement their corresponding interface
package ues.edu.sv.dao;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.*;
import ues.edu.sv.entity.User;
#Stateless
public class UserDaoImpl implements UserDao {
EntityManagerFactory emf =
Persistence.createEntityManagerFactory("HibernateSchedule");
EntityManager em = emf.createEntityManager();
#Override
public List<User> listAllUsers() {
return em.createNamedQuery("User.listAllUsers").getResultList();
}
#Override
public User getUserById(User user) {
return em.find(User.class, user.getIdUser());
}
#Override
public void createNewUser(User user) {
em.persist(user);
}
#Override
public void updateUser(User user) {
em.merge(user);
}
#Override
public void deleteUser(User user) {
em.remove(em.merge(user));
}
}
package ues.edu.sv.dao;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import ues.edu.sv.entity.Credential;
#Stateless
public class CredentialDaoImpl implements CredentialDao {
EntityManagerFactory emf =
Persistence.createEntityManagerFactory("HibernateSchedule");
EntityManager em = emf.createEntityManager();
#Override
public List<Credential> getAllCredentials() {
return em.createNamedQuery("Credential.getAllCredentials").getResultList();
}
#Override
public Credential getCredentialById(Credential credential) {
return em.find(Credential.class, credential.getIdCredential());
}
#Override
public Credential getCredentialByUserName(Credential credential) {
return em.find(Credential.class, credential.getUserName());
}
#Override
public void createNewCredential(Credential credential) {
em.persist(credential);
}
#Override
public void updateCredential(Credential credential) {
em.merge(credential);
}
#Override
public void deleteCredential(Credential credential) {
em.remove(em.merge(credential));
}
}
My understanding is that since I am working in a java enterprise context, there is no need to open a transaction when persisting an object in the database. I am using glassfish by the way.
now to complete the three-layer pattern, I have another package called "ues.edu.sv.service" that injects the above interfaces via CDI
package ues.edu.sv.service;
import java.util.List;
import javax.ejb.Local;
import ues.edu.sv.entity.Credential;
#Local
public interface CredentialService {
public List<Credential> getAllCredentials();
public Credential getCredentialById(Credential credential);
public Credential getCredentialByUserName(Credential credential);
public void createNewCredential(Credential credential);
public void updateCredential(Credential credential);
public void deleteCredential(Credential credential);
}
package ues.edu.sv.service;
import java.util.List;
import javax.ejb.Local;
import ues.edu.sv.entity.User;
#Local
public interface UserService {
public List<User> listAllUsers();
public User getUserById(User user);
public void createNewUser(User user);
public void updateUser(User user);
public void deleteUser(User user);
}
and implementation classes
package ues.edu.sv.service;
import java.util.List;
import javax.annotation.Resource;
import javax.ejb.SessionContext;
import javax.ejb.Stateless;
import javax.inject.Inject;
import ues.edu.sv.dao.CredentialDao;
import ues.edu.sv.entity.Credential;
#Stateless
public class CredentialServiceImpl implements CredentialService{
#Inject
CredentialDao credentialDao;
#Resource
SessionContext context;
#Override
public List<Credential> getAllCredentials() {
return credentialDao.getAllCredentials();
}
#Override
public Credential getCredentialById(Credential credential) {
return credentialDao.getCredentialById(credential);
}
#Override
public Credential getCredentialByUserName(Credential credential) {
return credentialDao.getCredentialByUserName(credential);
}
#Override
public void createNewCredential(Credential credential) {
credentialDao.createNewCredential(credential);
}
#Override
public void updateCredential(Credential credential) {
try{
credentialDao.updateCredential(credential);
}catch(Exception ex){
ex.printStackTrace(System.out);
context.setRollbackOnly();
}
}
#Override
public void deleteCredential(Credential credential) {
credentialDao.deleteCredential(credential);
}
}
package ues.edu.sv.service;
import java.util.List;
import javax.annotation.Resource;
import javax.ejb.SessionContext;
import javax.ejb.Stateless;
import javax.inject.Inject;
import ues.edu.sv.dao.UserDao;
import ues.edu.sv.entity.User;
#Stateless
public class UserServiceImpl implements UserService{
#Inject
UserDao userDao;
#Resource
SessionContext context;
#Override
public List<User> listAllUsers() {
return userDao.listAllUsers();
}
#Override
public User getUserById(User user) {
return userDao.getUserById(user);
}
#Override
public void createNewUser(User user) {
userDao.createNewUser(user);
}
#Override
public void updateUser(User user) {
try{
userDao.updateUser(user);
}catch(Exception ex){
ex.printStackTrace(System.out);
context.setRollbackOnly();
}
}
#Override
public void deleteUser(User user) {
userDao.deleteUser(user);
}
}
And finally I have an ejb that connects to the jsf page called "Register.xhtml" and is responsible for retrieving the information that the user enters in the text fields to finally persist the information in the database, I have programmed the relationships so cascading user object can be persisted
package ues.edu.sv.beans;
import java.io.IOException;
import javax.enterprise.context.RequestScoped;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;
import ues.edu.sv.crypto.Cypher;
import ues.edu.sv.entity.Credential;
import ues.edu.sv.entity.User;
import ues.edu.sv.service.CredentialService;
import ues.edu.sv.service.UserService;
#Named
#RequestScoped
public class RegisterBean {
#Inject
CredentialService credentialService;
#Inject
UserService userService;
private String name;
private String lastName;
private String email;
private String userName;
private String password;
public RegisterBean() {
}
public void toRegister() {
User user = new User(name, lastName, email);
String encriptedPassword = Cypher.encryptPassword(password);
Credential credential = new Credential(userName, encriptedPassword, user);
credentialService.createNewCredential(credential);
try {
FacesContext.getCurrentInstance().getExternalContext().redirect("Login.xhtml");
} catch (IOException ex) {
ex.printStackTrace(System.out);
}
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
And apparently everything is fine, the console does not show me any error, but it does nothing in the database, it does not insert the content into the database :(
This is what appears in the console when everything has been executed...
]|#]
HHH000204: Processing PersistenceUnitInfo [name: HibernateSchedule]|#]
HHH000412: Hibernate Core {6.0.0.Alpha4}|#]
HCANN000001: Hibernate Commons Annotations {5.1.0.Final}|#]
HHH10001002: Using Hibernate built-in connection pool (not for production use!)|#]
HHH10001005: using driver [com.mysql.cj.jdbc.Driver] at URL
[jdbc:mysql://localhost:3306/diary?
useSSL=false&useTimezone=true&serverTimezon=UTC&allowPublicKeyRetrieval=true]|#]
HHH10001001: Connection properties: {user=root, password=****}|#]
HHH10001003: Autocommit mode: false|#]
HHH000115: Hibernate connection pool size: 20 (min=1)|#]
HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect|#]
HHH10005002: No explicit CDI BeanManager reference was passed to Hibernate, but CDI
is available on the Hibernate ClassLoader.|#]
HHH000490: Using JtaPlatform implementation:
[org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]|#]
That is all that appears. Someone who can help me please

Exception : Session Issue ids for this class must be manually assigned before calling save(): org.me.Testservices.TblUsers

I'm getting an exception
Session Issue ids for this class must be manually assigned before
calling save(): org.me.Testservices.TblUsers
package org.me.Testservices;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.UniqueConstraint;
/**
* TblUsers generated by hbm2java
*/
#Entity
#Table(name="tbl_users"
,catalog="ceotrp"
, uniqueConstraints = #UniqueConstraint(columnNames="Mobile_No")
)
public class TblUsers implements java.io.Serializable {
private String email;
private String username;
private String password;
private Date createTime;
private String mobileNo;
private String tblUsersType;
private String tblUserscol;
public TblUsers() {
}
public TblUsers(String email, String username, String password) {
this.email = email;
this.username = username;
this.password = password;
}
public TblUsers(String email, String username, String password, Date createTime, String mobileNo, String tblUsersType, String tblUserscol) {
this.email = email;
this.username = username;
this.password = password;
this.createTime = createTime;
this.mobileNo = mobileNo;
this.tblUsersType = tblUsersType;
this.tblUserscol = tblUserscol;
}
#Id
#Column(name="email", unique=true, nullable=false)
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
#Column(name="username", nullable=false, length=16)
public String getUsername() {
return this.username;
}
public void setUsername(String username) {
this.username = username;
}
#Column(name="password", nullable=false, length=32)
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
#Temporal(TemporalType.TIMESTAMP)
#Column(name="create_time", length=26)
public Date getCreateTime() {
return this.createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
#Column(name="Mobile_No", unique=true, length=14)
public String getMobileNo() {
return this.mobileNo;
}
public void setMobileNo(String mobileNo) {
this.mobileNo = mobileNo;
}
#Column(name="tbl_UsersType", length=1)
public String getTblUsersType() {
return this.tblUsersType;
}
public void setTblUsersType(String tblUsersType) {
this.tblUsersType = tblUsersType;
}
#Column(name="tbl_Userscol", length=45)
public String getTblUserscol() {
return this.tblUserscol;
}
public void setTblUserscol(String tblUserscol) {
this.tblUserscol = tblUserscol;
}
}`
>I AM NEW TO HIBERNATE in NETBEANS 8.2 . The Select Query is Working Fine ,but INSERT is Not Happening .
>>The Code Below Demonstrates how I am using hibernate and the Above Code for Inserting in MySQL 8.0 (Which is Of course not Happening)
public String registernewUser( String name , String email,String password,String MObileNo,String Utype)
{
TblUsers ins =new TblUsers();
ins.setUsername(name);
ins.setPassword(password);
ins.setMobileNo(MObileNo);
ins.setTblUsersType(Utype);
ins.setTblUserscol("D");
ins.setTblUsersType("C");
try{
/* session.beginTransaction();
session.save(ins);
session.getTransaction().commit();
session.close();*/
Transaction t= session.beginTransaction();
session.save(ins);
t.commit();
return "Operation executed";
}
catch(Throwable ex)
{
System.err.println("Session Issue " + ex.getMessage());
return ex.getMessage();
}
}
}
If you need other files I can provide them. I am trying to create a web service for an Android App and also I am fond of Hibernate Technologies. Please let me know the best way to optimize the above code . I am using Glassfish Server to test the web service.
TblUsers #Entity class has a String type for its #Id field, so it can't generate ids for you.The value of identifier has to be set by the application before save.
public String registernewUser( String name , String email,String password,String MObileNo,String Utype)
{
TblUsers ins =new TblUsers();
ins.setUsername(name);
ins.setEmail(email); // set email
ins.setPassword(password);
ins.setMobileNo(MObileNo);
ins.setTblUsersType(Utype);
ins.setTblUserscol("D");
ins.setTblUsersType("C");
try{
/* session.beginTransaction();
session.save(ins);
session.getTransaction().commit();
session.close();*/
Transaction t= session.beginTransaction();
session.save(ins);
t.commit();
return "Operation executed";
}
catch(Throwable ex)
{
System.err.println("Session Issue " + ex.getMessage());
return ex.getMessage();
}
}
}

Logging In With JSP Hibernate

I have a problem with Hibernate to make login process. All codes are perfectly correct in terms of syntax. NetBeans tell me that my code have no problem. However, when I run the web, and I test the login process, it doesn't reacting and the address is stucked on the doLogin.
All classes have been mapped correctly.
This is my problem: when I try to retrieve data, my code is stucked on a line.
on doLogin servlet (I use the template provided by NetBeans and just filling in my code on the try. Here's in brief:
Connect con = new Connect(); //my code is stucked on this line.
//I've done testing where's the cause of the stuck, and this line is the cause.
List logger = con.getLogin(username, password);
and to make it clear:
Connect.java
public class Connect {
Session sesi;
public Connect() {
sesi = HibernateUtil.getSessionFactory().openSession();
}
public List getLogin(String username, String password){
return sesi.createQuery("from MsUser WHERE username = '"+username+"' and password = '"+password+"'").list();
}
}
and since that query is HQL, here is the MsUser class:
public class MsUser {
public MsUser() {
}
private int userID;
private String username;
private String firstname;
private String lastname;
private String email;
private String password;
private String gender;
private String address;
private String phone;
private String photo;
public MsUser(int userID, String username, String firstname, String lastname, String email, String password, String gender, String address, String phone, String photo) {
this.userID = userID;
this.username = username;
this.firstname = firstname;
this.lastname = lastname;
this.email = email;
this.password = password;
this.gender = gender;
this.address = address;
this.phone = phone;
this.photo = photo;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getPhoto() {
return photo;
}
public void setPhoto(String photo) {
this.photo = photo;
}
public int getUserID() {
return userID;
}
public void setUserID(int userID) {
this.userID = userID;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
please help. But I suspect on Connect's constructor as the main cause. Anybody can suggest or fix or tell me what causing me this.
appendix:
HibernateUtil.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Controller;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.SessionFactory;
/**
* Hibernate Utility class with a convenient method to get Session Factory
* object.
*
* #author Ginanjar
*/
public class HibernateUtil {
private static final SessionFactory sessionFactory;
static {
try {
// Create the SessionFactory from standard (hibernate.cfg.xml)
// config file.
sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
} catch (Throwable ex) {
// Log the exception.
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
You can try following code in your hibernateUtil.java file:
SessionFactory factory = new Configuration().configure().buildSessionFactory();
session = factory.openSession();
String query = "select reg.username,reg.password from MsUser as reg where reg.username='" + username + "' and reg.password='" + password + "'";
Query DBquery = session.createQuery(query);
for (Iterator it = DBquery.iterate(); it.hasNext();) { it.next();
count++;
}
System.out.println("Total rows: " + count);
if (count == 1) {
return true;
} else {
return false;
}
}

h:outputLabel not showing anything

The problem that I am facing is that after I click on the h:commandLink button the h:outputLabel isn't showing anything. I have used selectedUser to store the value when the form is submitted but it seems selectedUser is not storing any value.
1)Here is the xhtml file.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui"
xmlns:c="http://java.sun.com/jsp/jstl/core">
<h:head></h:head>
<h:body class="thrColElsHdr">
<div class="friends">
<h4>Friends</h4>
<h:form>
<p:selectOneMenu value="#{chatBean.selectedUser}">
<f:selectItems value="#{chatBean.friendList}" var="users" itemLabel="#{users.firstName}" itemValue="#{users}"/>
</p:selectOneMenu>
<h:commandLink>Chat</h:commandLink>
</h:form>
<br>
</br>
<h:outputLabel value="#{chatBean.selectedUser.firstName}"/>
</div>
</h:body>
</html>
2)Here is the chatBean and it is session scoped using facesconfig.xml
package com.bean;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.faces.context.FacesContext;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.servlet.http.HttpSession;
import com.entity.Friend;
import com.entity.User;
public class ChatBean {
private EntityManager em;
private User selectedUser;
public User getSelectedUser() {
return selectedUser;
}
public void setSelectedUser(User selectedUser) {
this.selectedUser = selectedUser;
}
public ChatBean(){
selectedUser= new User();
EntityManagerFactory emf=Persistence.createEntityManagerFactory("FreeBird");
em =emf.createEntityManager();
}
public List<User> getFriendList(){
FacesContext context = FacesContext.getCurrentInstance();
HttpSession session = (HttpSession) context.getExternalContext().getSession(true);
User user=(User) session.getAttribute("userdet");
Query query = em.createQuery("SELECT f FROM Friend f WHERE f.email='"+user.getEmail()+"' AND f.status=1",Friend.class);
List<Friend> results =query.getResultList();
ArrayList<User> friends = new ArrayList<User>();
Iterator<Friend> it = results.iterator();
while(it.hasNext()){
System.out.println("in getFriendList...");
User friend =em.find(User.class,it.next().getFriendEmail());
friends.add(friend);
}
return friends;
}
}
3) Here is the user entity class
package com.entity;
import java.io.Serializable;
import javax.persistence.*;
/**
* The persistent class for the user database table.
*
*/
#Entity
public class User implements Serializable {
private static final long serialVersionUID = 1L;
#Id
private String email;
#Lob()
private String aboutMe;
private String birthDate;
private String city;
private String college;
private String confirmation;
private String contactNo;
private String country;
private String degree;
private String firstName;
private String gender;
private String highSchool;
private String image;
private String interest;
private String lastName;
private String password;
private int pincode;
#Lob()
private String quote;
private String relationship;
private String secondarySchool;
private String state;
private String street;
private String university;
private String userName;
public User() {
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAboutMe() {
return this.aboutMe;
}
public void setAboutMe(String aboutMe) {
this.aboutMe = aboutMe;
}
public String getBirthDate() {
return this.birthDate;
}
public void setBirthDate(String birthDate) {
this.birthDate = birthDate;
}
public String getCity() {
return this.city;
}
public void setCity(String city) {
this.city = city;
}
public String getCollege() {
return this.college;
}
public void setCollege(String college) {
this.college = college;
}
public String getConfirmation() {
return this.confirmation;
}
public void setConfirmation(String confirmation) {
this.confirmation = confirmation;
}
public String getContactNo() {
return this.contactNo;
}
public void setContactNo(String contactNo) {
this.contactNo = contactNo;
}
public String getCountry() {
return this.country;
}
public void setCountry(String country) {
this.country = country;
}
public String getDegree() {
return this.degree;
}
public void setDegree(String degree) {
this.degree = degree;
}
public String getFirstName() {
return this.firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getGender() {
return this.gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getHighSchool() {
return this.highSchool;
}
public void setHighSchool(String highSchool) {
this.highSchool = highSchool;
}
public String getImage() {
return this.image;
}
public void setImage(String image) {
this.image = image;
}
public String getInterest() {
return this.interest;
}
public void setInterest(String interest) {
this.interest = interest;
}
public String getLastName() {
return this.lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
public int getPincode() {
return this.pincode;
}
public void setPincode(int pincode) {
this.pincode = pincode;
}
public String getQuote() {
return this.quote;
}
public void setQuote(String quote) {
this.quote = quote;
}
public String getRelationship() {
return this.relationship;
}
public void setRelationship(String relationship) {
this.relationship = relationship;
}
public String getSecondarySchool() {
return this.secondarySchool;
}
public void setSecondarySchool(String secondarySchool) {
this.secondarySchool = secondarySchool;
}
public String getState() {
return this.state;
}
public void setState(String state) {
this.state = state;
}
public String getStreet() {
return this.street;
}
public void setStreet(String street) {
this.street = street;
}
public String getUniversity() {
return this.university;
}
public void setUniversity(String university) {
this.university = university;
}
public String getUserName() {
return this.userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
Your managed bean must have the corresponding annotations:
#ViewScoped
#ManagedBean
public class ChatBean {
//...
}
The example can be corrected using one of these tips:
Add an action to your <h:commandLink> and bind it to a method that returns the name of your page. In this way, the page will be refreshed and it will show the new value in #{chatBean.selectedUser.firstName}:
<h:commandLink action="#{chatBean.refresh}" value="Chat" />
In your class:
public String refresh() {
return "index";
}
Add ajax behavior to your <h:commandLink> in order to update the <h:outputLabel>. You should add an id attribute to your <h:outputLabel>:
<h:commandLink value="Chat">
<f:ajax render=":theLabel" />
</h:commandLink>
<!-- jsf code -->
<h:outputLabel id="theLabel" value="#{chatBean.selectedUser.firstName}"/>

Google App Engine User Registration System

I am creating a user registration system in google app engine, and so far I could develop the registration side of the app. But I can't log in and create a HttpSession.
Here what I did, I created login.jsp and two text boxes to input email and password.
And then I created Bean class and DAO class as following.
package com.myfirstguide.beans;
import javax.servlet.http.HttpSession;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
public class UserDAO {
public static UserBean login(UserBean bean){
String email = bean.getEmail();
String password = bean.getPassword();
try{
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
Query q = new Query("Account");
q.addFilter("email", Query.FilterOperator.EQUAL, email);
q.addFilter("password", Query.FilterOperator.EQUAL, password);
PreparedQuery pq = datastore.prepare(q);
Entity result = pq.asSingleEntity();
if(result != null){
bean.setValid(true);
}
//return bean;
}catch(Exception e){
}
return bean;
}
}
Here is the Bean class.
package com.myfirstguide.beans;
public class UserBean {
private String username;
private String password;
private String firstName;
private String lastName;
private String email;
public boolean valid;
public String getFirstName() {
return firstName;
}
public void setFirstName(String newFirstName) {
firstName = newFirstName;
}
public void setEmail(String semail){
email = semail;
}
public String getEmail(){
return email;
}
public String getLastName() {
return lastName;
}
public void setLastName(String newLastName) {
lastName = newLastName;
}
public String getPassword() {
return password;
}
public void setPassword(String newPassword) {
password = newPassword;
}
public String getUsername() {
return username;
}
public void setUserName(String newUsername) {
username = newUsername;
}
public boolean isValid() {
return valid;
}
public void setValid(boolean newValid) {
valid = newValid;
}
}
And here is the Servlet.
package com.myfirstguide.users;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.myfirstguide.beans.UserBean;
import com.myfirstguide.beans.UserDAO;
public class SignIn extends HttpServlet{
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String email = req.getParameter("email");
String password = req.getParameter("password");
try{
UserBean ubean = new UserBean();
ubean.setEmail(email);
ubean.setPassword(password);
ubean = UserDAO.login(ubean);
if(ubean.isValid()){
HttpSession session = req.getSession(true);
session.setAttribute("currentSessionUser",ubean);
resp.sendRedirect("index.jsp?session=" + ubean.getFirstName()); //logged-in page
}
}catch(Throwable e){
System.out.println(e);
}
}
}
And I don't know JPA. And if there is better way to do this, please tell me.
Thank you!
Have you enabled sessions?
https://developers.google.com/appengine/docs/java/config/appconfig#Enabling_Sessions

Categories

Resources