I'm creating a simple web application with a register form, and I have used Hibernate. But i have this kind of error:
this is the code:
AddUser.java
import java.io.IOException;
import javax.imageio.spi.ServiceRegistry;
import javax.security.auth.login.Configuration;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
#WebServlet("/CreateUser.do")
public class AddUser extends HttpServlet {
private static final long serialVersionUID = 1L;
public AddUser() {
super();
// TODO Auto-generated constructor stub
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Configuration config = new Configuration().configure("hibernate.cfg.xml");
ServiceRegistry servReg = new StandardServiceRegistryBuilder().applySettings(config.getProperties()).build();
SessionFactory factory = config.buildSessionFactory(servReg);
Session session = factory.openSession();
session.beginTransaction();
User u = new User(request.getParameter("firstname"), request.getParameter("lastname"), request.getParameter("login"), request.getParameter("password"));
session.save(u);
session.getTransaction().commit();
session.close();
RequestDispatcher view = request.getRequestDispatcher("useradd.jsp");
view.forward(request, response);
}
}
This is the error: ERROR
How can I do to solve this problem? Thanks you!
#LuisMuñoz
I add also the error if someone want to see it directly.
HTTP Status 500 – Internal Server Error
Type Exception Report
Message Servlet execution threw an exception
Description The server encountered an unexpected condition that prevented it from fulfilling the request.
Exception
javax.servlet.ServletException: Servlet execution threw an exception
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
Root Cause
java.lang.Error: Unresolved compilation problems:
Cannot instantiate the type Configuration
The method configure() is undefined for the type Configuration
The method getProperties() is undefined for the type Configuration
The method buildSessionFactory(ServiceRegistry) is undefined for the type Configuration
AddUser.doPost(AddUser.java:32)
javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
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 Eclipse Page:
ECLIPSE
From the error it looks like there is no method configure for Configuration object. Check the javadocs https://docs.oracle.com/javase/9/docs/api/index.html?javax/security/auth/login/Configuration.html
Related
//Eclipse java code:
package openbrowser;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class OpenChrome {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.setProperty("webdriver.chrome.driver", "d://chromedriver.exe");
WebDriver driver=new ChromeDriver();
}
}
eclipse error
Error occurred during initialization of boot layer
java.lang.module.FindException: Unable to derive module descriptor for C:\Users\Om Murugaa\Downloads\Testing\selenium-server-standalone-3.141.59.jar
Caused by: java.lang.module.InvalidModuleDescriptorException: Provider class org.eclipse.jetty.http.Http1FieldPreEncoder not in module
Adding maven into eclipse resolved this error.
I tried using TinyLog for a sample application to make sure understanding how it works, so that i can use it for my work application.
But, while using i get an exception to type cast the Writer (Compile time error). If i typecast it, it throws runtime error as below.
Code :
import java.io.FileWriter;
import java.io.IOException;
import org.pmw.tinylog.Configurator;
import org.pmw.tinylog.Logger;
import org.pmw.tinylog.writers.ConsoleWriter;
import org.pmw.tinylog.writers.Writer;
public class TestClass {
public static void main(String[] args) throws IOException {
Configurator.defaultConfig().writer(new ConsoleWriter()).addWriter((Writer) new FileWriter("data.txt")).activate();
Logger.info("welcome to tinylog logger.....");
}
}
Error :-
Exception in thread "main" java.lang.ClassCastException: java.io.FileWriter cannot be cast to org.pmw.tinylog.writers.Writer
at TestClass.main(TestClass.java:12)
Please help us :).
You can fix it easily. Just import org.pmw.tinylog.writers.FileWriter instead of java.io.FileWriter. The class java.io.FileWriter is the file writer of the JVM, but you need tinylog's file writer.
Afterwards you can remove the class cast "(Writer)" as org.pmw.tinylog.writers.FileWriter is an implementation of the interface org.pmw.tinylog.writers.Writer. However the class java.io.FileWriter does not implement the interface org.pmw.tinylog.writers.Writer. Therefor the reported ClassCastException has been thrown.
import org.pmw.tinylog.Configurator;
import org.pmw.tinylog.Logger;
import org.pmw.tinylog.writers.ConsoleWriter;
import org.pmw.tinylog.writers.FileWriter;
public class TestClass {
public static void main(String[] args) {
Configurator.defaultConfig().writer(new ConsoleWriter()).addWriter(new FileWriter("data.txt")).activate();
Logger.info("welcome to tinylog logger.....");
}
}
import java.util.List;
import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.Style;
import org.soapwebservice.model.Product;
#WebService
#SOAPBinding(style = Style.RPC)
public interface ProductCatalog {
#WebMethod(action="fetch_Categories",operationName="fetchCategories")
List<String> getProductCategories();
#WebMethod
List<String> getProducts(String category);
#WebMethod
boolean addProduct(String category, String product);
#WebMethod
List<Product> getProductsV2(String category);
}
This is the code it is failing only when I try to include the following line
#SOAPBinding(style = Style.RPC)
and also the the wsdl doesn't change when I try to bind with RPC style.
deploy is failing=Error occurred during deployment: Exception while loading the app : java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: java.lang.RuntimeException: Servlet web service endpoint '' failure. Please see server.log for more details.
Good Morning, please i don't know how to resolve that exception, i'm using ApcheTomcat 7 under eclipse and that exception is thrown everytime i run my servlet, here's my servlet for more clarity:
package servlets;
import java.util.*;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import dao.*;
#WebServlet("/AdminServlt")
public class AdminServlt extends HttpServlet {
private static final long serialVersionUID = 1L;
CarHome carDao;
public void init(ServletConfig config) throws ServletException{
carDao = new CarHome();
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
populateAdminView(request, response);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
}
public void populateAdminView(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{
ArrayList productsList = (ArrayList) carDao.extractAdminAttributes();
HttpSession session = request.getSession(true);
session.setAttribute("product_list",productsList);
RequestDispatcher rd = request.getRequestDispatcher("Admin.jsp");
rd.forward(request, response);
}
}
and here's CarHome.java
package dao;
import java.util.ArrayList;
import java.util.List;
import javax.naming.InitialContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.LockMode;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.*;
import entity.*;
public class CarHome {
private static final Log log = LogFactory.getLog(CarHome.class);
private final SessionFactory sessionFactory = getSessionFactory();
public List extractAdminAttributes() {
log.debug("Extracting car attributes for administrator view");
try {
ArrayList results = (ArrayList) sessionFactory
.getCurrentSession()
.createCriteria("pojo.Car")
.setProjection(
Projections.projectionList()
.add(Projections.property("carDesc"))
.add(Projections.property("price"))
.add(Projections.property("quantity")));
return results;
} catch (RuntimeException re) {
log.error("find by admin view failed");
throw re;
}
}
}
here's the stacktrace of the exception
java.lang.ClassNotFoundException: org.hibernate.criterion.Projection
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1676)
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1521)
servlets.AdminServlt.init(AdminServlt.java:31)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:462)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:562)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:395)
org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:250)
org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:188)
org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:166)
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:302)
java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
java.lang.Thread.run(Unknown Source)
i have solved my problem it was very simple, the main reason is that the hibernate.cor.jar file wasn't in the lib folder under the web-content of the application when i put it there it works fine
I was facing the same issue but in my case i re-ordered the hibernate-cor.jar on the top using eclipse
chose the project --> right click -->build path -->order tab -->chose the hibernate-cor.jar click top
**loginServlet.java**
package com.anil.apps;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out=response.getWriter();
String uid=request.getParameter("userid");
String password=request.getParameter("pwd");
if(uid.equals("Anil")&&password.equals("missinlx")){
//out.println("welcome "+uid);
response.sendRedirect("welcomeUser?userid="+uid);
}
else{
out.println("invalid username or password");
}
}
}
**WelcomeUserServlet.java**
package com.anil.apps;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class WelcomeUserServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out=response.getWriter();
out.println("<html><body><h1>Welcome " +uid+ "</h1></body></html>");
}
}
what is wrong with my code?? I want to redirect the page to welcomeUser.java page using response.sendRedirect() method.
As I am new to servlet please help me out of it. please tell me the whole format for the page redirection in Servlets.
GET parameters are not turned in to variables automatically. You need to add this to the top of your doGet method in the WelcomeUserServlet:
String uid = request.getParameter("userId");
Making that class look like this:
public class WelcomeUserServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String uid = request.getParameter("userId");
PrintWriter out=response.getWriter();
out.println("<html><body><h1>Welcome " +uid+ "</h1></body></html>");
}
}
You are using the wrong argument for the sendRedirect method
You should use a complete path like
response.sendRedirect("some/path/here/to/"+welcomeUser?userid="+uid)
Or better
response.sendRedirect(response.encodeURL(response.getContextPath()+"welcomeUser?userid="+uid))
Or use a request dispatcher which knows the structure of your project and does not need a full path
request.getRequestDispatcher("welcomeUser?userid="+uid).forward(request,response)