I'm fairly new to using hibernate and I'm trying to create a webapp with hibernate as the backend but I'm running into an error I can't seem to figure out how to solve given the current configuration of my code. Any help would be appreciated
I have added my hibernate.cfg.xml configuration into the hibernateutil java class but i can't seem to get my configuration to read data from my database and keep getting
org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
caused by another error: Caused by: org.hibernate.boot.registry.classloading.spi.ClassLoadingException: Unable to load class [com.mysql.jdbc.Driver] and a ClassNotFoundException again to the mysql driver
i thought i configured my class properly but i can't seem to get it to work, here is my code where the error starts
public class HibernateUtil {
private static SessionFactory sessionFactory;
public static SessionFactory getSessionFactory() {
if (sessionFactory == null) {
try {
Configuration configuration = new Configuration();
Properties settings = new Properties();
// Hibernate settings equivalent to hibernate.cfg.xml's properties
settings.put(Environment.DRIVER, "com.mysql.jdbc.Driver");
settings.put(Environment.URL, "jdbc:mysql://localhost:3308/demo");
settings.put(Environment.USER, "user");
settings.put(Environment.PASS, "password");
settings.put(Environment.DIALECT, "org.hibernate.dialect.MySQL5Dialect");
settings.put(Environment.SHOW_SQL, "true");
settings.put(Environment.CURRENT_SESSION_CONTEXT_CLASS, "thread");
settings.put(Environment.HBM2DDL_AUTO, "create-drop");
configuration.setProperties(settings);
configuration.addAnnotatedClass(Student.class);
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties()).build();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
} catch (Exception e) {
e.printStackTrace();
}
}
return sessionFactory;
}
}
here is my DAO class
public class StudentDAO {
public void saveStudent(Student student) {
Transaction transaction = null;
try {
Session session = HibernateUtil.getSessionFactory().openSession();
transaction = session.beginTransaction();
session.save(student);
transaction.commit();
} catch (Exception e) {
if (transaction != null) {
transaction.rollback();
}
}
}
public void updateStudent(Student student) {
Transaction transaction = null;
try {
Session session = HibernateUtil.getSessionFactory().openSession();
transaction = session.beginTransaction();
session.saveOrUpdate(student); //student object updated
transaction.commit();
} catch (Exception e) {
if (transaction != null) {
transaction.rollback();
}
}
}
public Student getStudent(int id) {
Transaction transaction = null;
Student student = null;
try {
Session session = HibernateUtil.getSessionFactory().openSession();
transaction = session.beginTransaction();
student = session.get(Student.class, id); //get student object by id
transaction.commit();
} catch (Exception e) {
if (transaction != null) {
transaction.rollback();
}
}
return student;
}
#SuppressWarnings("unchecked")
public List<Student> getAllStudents() {
Transaction transaction = null;
List<Student> students = null;
try {
Session session = HibernateUtil.getSessionFactory().openSession();
transaction = session.beginTransaction();
students = session.createQuery("from student").list(); //get all student objects
transaction.commit();
} catch (Exception e) {
if (transaction != null) {
transaction.rollback();
}
}
return students;
}
#SuppressWarnings("null")
public void deleteStudent(int id) {
Transaction transaction = null;
Student student = null;
try {
Session session = HibernateUtil.getSessionFactory().openSession();
student = session.get(Student.class, id);
if (student != null) {
session.delete(student);
System.out.println(student + "has been deleted");
}
transaction.commit();
} catch (Exception e) {
if (transaction != null) {
transaction.rollback();
}
}
}
}
and here is my servlet class
#WebServlet("/")
public class StudentServlet extends HttpServlet {
private static final long serialVersionUID = 2L;
private StudentDAO studentDao;
String home = "/Week05";
public StudentServlet() {
this.studentDao = new StudentDAO();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String sPath = request.getServletPath();
//switch statement to call appropriate method
switch (sPath) {
case "/new":
try {
showNewForm(request, response);
} catch (ServletException | IOException e) {
e.printStackTrace();
}
break;
case "/insert":
try {
insertStudent(request, response);
} catch (SQLException | IOException e) {
e.printStackTrace();
}
break;
case "/delete":
try {
deleteStudent(request, response);
} catch (SQLException | IOException e) {
e.printStackTrace();
}
break;
case "/update":
try {
updateStudent(request, response);
} catch (SQLException | IOException e) {
e.printStackTrace();
}
break;
case "/edit":
try {
editStudent(request, response);
} catch (ServletException | IOException e) {
e.printStackTrace();
}
break;
default:
try {
listAllStudents(request, response); //home page = .../week04/StudentServlet
} catch (ServletException | IOException | SQLException e) {
e.printStackTrace();
}
break;
}
}
// functions to fetch data from studentDao and display data on appropriate jsp
private void listAllStudents(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, SQLException {
List<Student> allStudents = studentDao.getAllStudents();
request.setAttribute("listStudents", allStudents);
RequestDispatcher dispatch = request.getRequestDispatcher("index.jsp"); //home page week04/StudentServlet | list all objects from table
dispatch.forward(request, response);
}
private void showNewForm(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
RequestDispatcher dispatch = request.getRequestDispatcher("student-form.jsp");
dispatch.forward(request, response);
}
private void insertStudent(HttpServletRequest request, HttpServletResponse response)
throws SQLException, IOException{
String firstname = request.getParameter("firstname");
String lastname = request.getParameter("lastname");
String email = request.getParameter("email");
Student newStudent = new Student(firstname, lastname, email);
studentDao.saveStudent(newStudent); //student object inserted to table
response.sendRedirect(home); //redirect to home page
}
private void deleteStudent(HttpServletRequest request, HttpServletResponse response)
throws SQLException, IOException {
int id = Integer.parseInt(request.getParameter("id"));
studentDao.deleteStudent(id); //student object deleted
response.sendRedirect(home);
}
private void updateStudent(HttpServletRequest request, HttpServletResponse response)
throws SQLException, IOException{
int id = Integer.parseInt(request.getParameter("id"));
String firstname = request.getParameter("firstname");
String lastname = request.getParameter("lastname");
String email = request.getParameter("email");
Student updateStudent = new Student(id, firstname, lastname, email);
studentDao.updateStudent(updateStudent); //student object updated
response.sendRedirect(home);
}
private void editStudent(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
int id = Integer.parseInt(request.getParameter("id"));
// String firstname = request.getParameter("firstname");
// String lastname = request.getParameter("lastname");
// String email = request.getParameter("email");
Student currentStudent = studentDao.getStudent(id);
RequestDispatcher dispatch = request.getRequestDispatcher("student-form.jsp"); //student form called with current student info loaded
request.setAttribute("student", currentStudent);
dispatch.forward(request, response);
}
}
Any help on where I'm going wrong would be appreciated as I truly can't figure what exactly to do, it might be a mapping error issue but i assumed all necessary mapping was covered on the servlet.
#Alpheus
Your project can't find out your driver's dependency, because you haven't put dependency on build path.
Related
We need to apply version control for our API, when the user send a request to our API endpoint i.e."http://mycompany/item?version=1", it will forwarded the request to itemServer_V1.java.
To achieve this goal, we have configured our web.xml as follows.
<servlet>
<servlet-name>item</servlet-name>
<servlet-class>com.mycompany.Servlet.ItemRequestHandler</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>item</servlet-name>
<url-pattern>/item</url-pattern>
</servlet-mapping>
We create a table in MySQL database.
database table
ItemRequestHandler is a class which extends HttpServlet, and it supposed to forward the request to ItemServiceV1 or ItemServiceV2 according to the version parameter in the request.
I have finish the ItemService class but I don't know how to forward the request from ItemRequestHandler to ItemService class. Could someone let me know how to do that please?
ItemRequestHandler class is as follows
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException , IOException
{
String version = req.getParameter("version");
String fcd = req.getParameter("fcd");
String client = req.getParameter("client");
//Find the targetClass from database using the above information.
targetClass.doGet(req, res);
}
I find out a solution.
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
System.out.println("LoginRequestHandler doPost");
String className = "";
String version = "";
String fcd = "login";
String compid = "";
RequestWrapper currentReq = new RequestWrapper(req);
version = currentReq.getParameter("Version");
compid = currentReq.getParameter("Compid ");
try {
className = findServletByVersion(compid, version, fcd);
Class<?> serviceClass = Class.forName(className);
Method method = serviceClass.getDeclaredMethod(MethodName.doPost.toString(), HttpServletRequest.class, HttpServletResponse.class);
method.invoke(serviceClass.newInstance(), currentReq, res);
return;
}catch(Exception e) {
System.out.println(e.toString());
} catch (DataNotFound e) {
System.out.println(e.toString());
}
}
}
Code of RequestWrapper
public class RequestWrapper extends HttpServletRequestWrapper {
private String _body;
public RequestWrapper(HttpServletRequest request) throws IOException {
super(request);
_body = "";
BufferedReader bufferedReader = request.getReader();
String line;
while ((line = bufferedReader.readLine()) != null){
_body += line;
}
}
#Override
public ServletInputStream getInputStream() throws IOException {
final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(_body.getBytes());
return new ServletInputStream() {
public int read() throws IOException {
return byteArrayInputStream.read();
}
};
}
#Override
public BufferedReader getReader() throws IOException {
return new BufferedReader(new InputStreamReader(this.getInputStream()));
}
}
Code of findServletByVersion
public String findServletByVersion(String compid, String version, String fcd) throws SQLException, ClassNotFoundException, DataNotFound {
String clsName = "";
Connection con = null;
Statement stmt = null;
User user = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://YourIpAddress:PortNum/"+schemaName,"account","password");
String query = "SELECT * FROM "+compid+".restfcd "
+ "WHERE 1=1 "
+ "AND compid = '"+compid+"'"
+ "AND version = '"+version+"'"
+ "AND fcd = '"+fcd+"'"
+ "ORDER BY compid desc";
System.out.println(query);
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
if(rs!=null) {
while (rs.next()) {
clsName = rs.getString("fcdcls");
}
}
if(Func.isEmpty(clsName)) {
throw new DataNotFound("findServletByVersion : no match result!");
}
return clsName;
} catch (SQLException e) {
throw new SQLException("findServletByVersion : SQLException!");
} catch (ClassNotFoundException e) {
throw new ClassNotFoundException("findServletByVersion : ClassNotFoundException!");
} finally {
try {
con.close();
stmt.close();
} catch (SQLException sqlee) {
throw new SQLException("Cannot close conection/statement!");
}
}
}
I have java class LoginValidation and Servlet Login ,am passing values from servlet to java class,but am not getting return values..from servlet to java class...
//normal java class LoginValidation
public class LoginValidation {
String userid="";
String password="";
String que="";
Connection dbConnection = null;
PreparedStatement pst=null;
ResultSet rs=null;
String userid1="";
String password1="";
int pan1=0;
public long valiDate(String userid ,String password){
long flag = 0l;
this.password=password;
this.userid=userid;
dbConnection = JDBCConnection.getDBConnection();
que="select * from shivu";
try {
pst = dbConnection.prepareStatement(que);
rs=pst.executeQuery();
while(rs.next()){
userid1=rs.getString(3);
password1=rs.getString(2);
pan1=rs.getInt(8);
if ((userid.equals(userid1)) && (password.equals(password1))){
flag = pan1;
}else{
flag = 0;
}
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return flag;
}
}
//Servlet Login
public class Login extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String userid=request.getParameter("userid");
String password=request.getParameter("password");
LoginValidation lv=new LoginValidation();
System.out.println("control flow");
long i=lv.valiDate(userid,password);
System.out.println(i);
if(i>=1){
System.out.println("control flow inside method call");
HttpSession session = request.getSession();
if (session != null)
session.setAttribute("pan", i);
response.sendRedirect("welcome.jsp");
}
else
{
System.out.println("Username or Password incorrect");
response.sendRedirect("login1.jsp");
}
}
}
you can print and see the values inside valiDate method.
while(rs.next()){
userid1=rs.getString(3);
password1=rs.getString(2);
pan1=rs.getInt(8);
// print userid, userid1, password, password1, pan1
if ((userid.equals(userid1)) && (password.equals(password1))){
flag = pan1;
}else{
flag = 0;
}
}
I have my servlet:
public class Authentification extends HttpServlet {
public int id1;
private static final long serialVersionUID = 1L;
public HttpSession session;
Authentification_link auth=new Authentification_link();
public Integer IdUser;
public Authentification() {
super();
}
public void init() {
Codb co= new Codb();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
int IdUser = Integer.valueOf(request.getParameter("id"));
session.setAttribute("ide", IdUser);
try {
if(auth.authen(IdUser)){
session.setAttribute("id", IdUser);
request.getRequestDispatcher("acceuil.jsp").forward(request, response);
System.out.println("found");}
else{
request.getRequestDispatcher("index.jsp").forward(request, response);
System.out.println("not found");
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public void doInteret (HttpServletRequest request, HttpServletResponse response) throws SQLException, ServletException, IOException {
IdUser = (Integer) session.getAttribute("IdUser");
Interets inte= new Interets (IdUser);
}
}
The user login to through an id, the authentification works fine, but now I want to get the same user's id so I can include it in this java classe when the user click on a link. For that I added the method doInteret in the servlet and the class Interet.java is like this:
public class Interets {
static Statement St ;
public ResultSet rs;
public Interets(Integer IdUser) throws SQLException, ServletException, IOException{
String res=" ";
try{
ResultSet result = St.executeQuery("SELECT description FROM interets, avoir, consomateur WHERE avoir.id_interet=interets.id_interets AND avoir.id_user=consomateur.code_bar AND consomateur.code_bar="+IdUser+"");
ResultSetMetaData resultMeta = (ResultSetMetaData) result.getMetaData();
while(result.next()){
String Newligne=System.getProperty("line.separator");
for(int i = 1; i <= resultMeta.getColumnCount(); i++){
res=res+Newligne+result.getObject(i).toString();
System.out.println(res);
}
}
}
catch (Exception e) {
System.out.println("Error in Select ");
}
}
}
but I am getting this error:
org.apache.jasper.JasperException: javax.servlet.ServletException: java.lang.NoSuchMethodError: pack1.Interets.AfficheInteret()Ljava/lang/String;
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:502)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:412)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
javax.servlet.http.HttpServlet.service(HttpServlet.java:723)
try changing your query and print it may be your query is not working
SELECT description FROM interets, avoir, consomateur WHERE avoir.id_interet=interets.id_interets AND avoir.id_user=consomateur.code_bar AND consomateur.code_bar='"+IdUser+"'");
Hi I'm writting java servlet which should get DVDs depends on which user is logged in. I have method
public List<Dvd> getDvdsByUserId(String user_id) throws SQLException {
List<Dvd> dvds = new ArrayList<Dvd>();
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
connection = getConnection();
preparedStatement = connection.prepareStatement("SELECT * FROM sedivyj_dvd where user_id = ?;");
preparedStatement.setString(1, user_id);
resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
Dvd dvd = new Dvd();
dvd.setId(resultSet.getInt("id"));
dvd.setUser_id(resultSet.getString("user_id"));
dvd.setName(resultSet.getString("name"));
dvd.setBorrower(resultSet.getString("borrower"));
dvd.setMail(resultSet.getString("mail"));
dvd.setBorrow_date(resultSet.getString("borrow_date"));
dvd.setBorrow_until(resultSet.getString("borrow_until"));
dvds.add(dvd);
}
} catch (SQLException e) {
throw e;
} finally {
cleanUp(connection, preparedStatement);
}
return dvds;
}
and I don't know how to set up logged user id in servlet's doGet method:
dvds = this.dvdDao.getDvdsByUserId();
loginServlet
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private UserDao userDao;
#Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
DbSettings dbSettings = new DbSettings();
dbSettings.setServer(config.getServletContext().getInitParameter("dbServer"));
dbSettings.setPort(Integer.valueOf(config.getServletContext().getInitParameter("dbPort")));
dbSettings.setUser(config.getServletContext().getInitParameter("dbUser"));
dbSettings.setPassword(config.getServletContext().getInitParameter("dbPassword"));
dbSettings.setDatabase(config.getServletContext().getInitParameter("dbDatabase"));
try {
this.userDao = new UserDao(dbSettings);
} catch (ClassNotFoundException e) {
throw new ServletException("Unable to initialize DB driver", e);
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
if (getLoggedUser(request, response) != null) {
response.sendRedirect("/list");
return;
}
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/WEB-INF/login.jsp");
dispatcher.forward(request, response);
} catch (Exception e) {
getServletContext().log("error", e);
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
if (getLoggedUser(request, response) != null) {
response.sendRedirect("/list");
return;
}
String nickname = request.getParameter("nickname");
String password = request.getParameter("password");
if (nickname != null && password != null) {
User user = userDao.getByLogin(nickname);
if (user != null && UserUtil.checkLogin(user, password)) {
HttpSession session = request.getSession(true);
Long userId = user.getId();
session.setAttribute("userId", userId);
session.setAttribute("loggedUser", user);
request.getSession().setAttribute("nickname", nickname);
response.sendRedirect("/list");
} else {
request.setAttribute("message", "Login se nepovedl.");
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/WEB-INF/login.jsp");
dispatcher.forward(request, response);
}
} else {
response.sendRedirect("/login");
}
} catch (Exception e) {
getServletContext().log("error", e);
}
}
public User getLoggedUser(HttpServletRequest request, HttpServletResponse response) {
HttpSession session = request.getSession(true);
User user = (User) session.getAttribute("loggedUser");
return user;
}
}
Does anybody have an idea please?
Get Logged User Id In Servlet Using Session.
HttpSession session=request.getSession(true);
session.setAttribute("user", userLoggedId);
Later You can retrieve Session Data :
HttpSession session=request.getSession(true);
String userId=(String)session.getAttribute("user");
According to my understand of your requirement first you validate whether username and password are matching then you pass the control to the servlet so on the request set the userid .Then you can acquire the userid in the doGet() method using the request.getParameter() method.
This can be done in many ways.
I think you are using form because in servlet you are calling doget().So while calling the servlet from the form pass the userid also and in servlet you can use userid=request.getParameter("user");
The other way is to keep the user in session
After the login if you are calling any servlet or jsp page then keep the user there in session like this way
session.setAttribute("username","username");
and in the servlet you can retrieve by using
session.getAttribute("username");
Does anyone know why I am getting a null pointer error when I call the getResultSet() method from MyServ2 class
here is my DBClass (imports etc omitted)
public DBClass(){
}
public Connection dbConnect(String db_connect_string,
String db_userid, String db_password)
{
try
{
DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
conn = DriverManager.getConnection(
db_connect_string, db_userid, db_password);
return conn;
}
catch (Exception e)
{
e.printStackTrace();
return null;
}
}
public ResultSet getResultSet(String query){
try{
stmt = conn.createStatement();
result = stmt.executeQuery(query);
} catch(Exception e){
e.printStackTrace();
return null;
}
return result;
}
}
and this is my MyServ2 class
public class MyServ2 extends HttpServlet {
private static final long serialVersionUID = 1L;
private DBClass db;
public MyServ2() {
super();
db = new DBClass();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ResultSet rs = db.getResultSet("Select * from ....ect");
try {
while(rs.next()){
System.out.println(rs.getString(1).toString());
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
You're not calling db.dbConnect(), so db.conn will be null.