I am developing a simple webapp and I am getting the following error when I am registering my users.
HTTP Status 500 - Error instantiating servlet class com.marlabs.demo.XMLServlet
web.xml is as follows
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID" version="3.1">
<display-name>SimpleServletProject</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>XMLServlet</servlet-name>
<servlet-class>com.marlabs.demo.XMLServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>XMLServlet</servlet-name>
<url-pattern>/XMLServlet</url-pattern>
</servlet-mapping>
</web-app>
My servlet is as follows
package com.marlabs.demo;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletContext;
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 javax.servlet.http.HttpSession;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
#SuppressWarnings("serial")
#WebServlet(description = "A simple servlet", urlPatterns = { "/XMLServlet" })
public class XMLServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter pout = response.getWriter();
String emailID = request.getParameter("emailID");
String pass = request.getParameter("pass");
String fname = request.getParameter("fname");
String lname = request.getParameter("lname");
HttpSession sess = request.getSession();
ServletContext context = request.getServletContext();
if (emailID != "" && emailID != null) {
sess.setAttribute("savedEmail", emailID);
context.setAttribute("savedEmail", emailID);
}
pout.println("Hello " + fname + "<br/>");
UserDetails user = new UserDetails();
user.setEmailID(emailID);
user.setPass(pass);
user.setFname(fname);
user.setLname(lname);
#SuppressWarnings("deprecation")
SessionFactory sessionFactory = new Configuration().configure("hibernate.cfg.xml").buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save(user);
session.getTransaction().commit();
session.close();
pout.println("Your information is saved!");
}
}
Related
I am getting an error in web.xml file while adding context parameters to it.
Here is web.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
<context-param>
<pram-name>ADMIN_PATH</param-name>
<param-value>AdminChatServlet</param-value>
</context-param>
<context-param>
<param-name>ROOMLIST_PATH</param-name>
<param-value>/RoomListServlet</param-value>
</context-param>
<context-param>
<param-name>CHROOM_PATH</param-name>
<param-value>/ChRoomServlet</param-value>
</context-param>
<servlet>
<servlet-name>MainChatServlet</servlet-name>
<servlet-class>MainChatServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>AdminChatServlet</servlet-name>
<servlet-class>AdminChatServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>RoomListServlet</servlet-name>
<servlet-class>RoomListServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>ChRoomServlet</servlet-name>
<servlet-class>ChRoomServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MainChatServlet</servlet-name>
<url-pattern>/MainChatServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>AdminChatServlet</servlet-name>
<url-pattern>/AdminChatServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>RoomListServlet</servlet-name>
<url-pattern>/RoomListServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>ChRoomServlet</servlet-name>
<url-pattern>/ChRoomServlet</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>30</session-timeout>
</session-config>
</web-app>
and here is the servlet(MainChatServlet) using those context-parameters:
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;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import java.util.*;
import com.amir.*;
public class MainChatServlet extends HttpServlet {
String chRoomPath;//="ChRoomServlet.java";
String roomListPath;//="RoomListServlet.java";
String adminChatPath;//="AdminChatServlet.java";
public void init()
{
ServletContext context = getServletConfig().getServletContext();
context.setAttribute("chRoomPath",context.getInitParameter("CHROOM_PATH"));
context.setAttribute("roomListPath",context.getInitParameter("ROOMLIST_PATH"));
context.setAttribute("adminChatPath",context.getInitParameter("ADMINCHAT_PATH"));
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
HttpSession session = request.getSession();
chRoomPath = (String)getServletContext().getAttribute("chRoomPath");
roomListPath = (String)getServletContext().getAttribute("roomListpath");
adminChatPath = (String)getServletContext().getAttribute("adminChatPath");
session.setAttribute("chRoomPath",chRoomPath);
session.setAttribute("roomListPath", roomListPath);
session.setAttribute("adminChatPath",adminChatPath);
HashMap hashmap = null;
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/chat","root","mysql");
synchronized(getServletContext())
{
hashmap = (HashMap)getServletContext().getAttribute("chatList");
if(hashmap == null)
{
hashmap =new HashMap();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select * from chatrooms");
while(rs.next())
{
hashmap.put(rs.getString(1),new ChatRoom(rs.getString(1),rs.getString(2),4));
}
rs.close();
getServletContext().setAttribute("roomList", hashmap);
}
}
conn.close();
}
catch(ClassNotFoundException e)
{
System.out.print("Error(Class)");
e.printStackTrace();
}
catch(SQLException e)
{
System.out.print("Error(SQL)");
e.printStackTrace();
}
RequestDispatcher view = request.getRequestDispatcher("chat.jsp");
view.forward(request, response);
}
}
and here is the default-package in which all the .java files(servlets are kept)
Screenshot#1
Why am I getting the error in the web.xml file?
Screenshot#2
EDIT: OR Suggest me any alternate idea if possible.
I'm working with Spring Tool Suite and I want to be redirected to a jsp (rapports.jsp) from sevelet.But I can't do so .I get this error:
HTTP Status 404 - /rapports.jsp
type Status report
message: /rapports.jsp
description:The requested resource is not available.
This is my controller:
package com.mycompany.myapp;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.http.HttpStatus;
import javax.servlet.ServletConfig;
import java.io.*;
import java.util.*;
import javax.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import org.apache.tools.ant.util.Base64Converter;
import javax.servlet.ServletConfig;
#Controller
public class HomeController extends HttpServlet {
private static final long serialVersionUID = 1L;
#RequestMapping(value = "/", method = RequestMethod.GET)
public ModelAndView adminPage() {
ModelAndView model = new ModelAndView();
model.setViewName("authentification");
return model;}
#RequestMapping(method=RequestMethod.POST)
public void service(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException{
String Str1 = request.getParameter("smya");
String Str2 = request.getParameter("mdps");
System.out.println(Str1);
System.out.println(Str2);
try {
URL url = new URL("http://pc-demo-bi:8090/jasperserver-pro/rest/login?j_username="+Str1+"&j_password="+Str2);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
System.out.println("connected");
response.sendRedirect("/rapports.jsp");
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
as you see I have used: response.sendRedirect("/rapports.jsp") to do so.
and this is my Web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml</param-value>
</context-param>
<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Processes application requests -->
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
this is my rapport.jsp
<title>hahahah</title>
</head>
<body>
Welcome!!
</body>
</html>
thanks in advance if you have any suggestion.
Personally, I dont think you need to extend HttpServlet. Try something like what i've put below. Assuming you have a valid view resolver (Spring or otherwise, I prefer Apache Tiles), returning just the name of the JSP page "rapports" will redirect the user. You can also use the annotation #RequestAttribute to get Str1 and Str2 from the HttpServletRequest, rather than injecting it into the method.
#Controller
public class HomeController {
private static final long serialVersionUID = 1L;
#RequestMapping(value = "/", method = RequestMethod.GET)
public ModelAndView adminPage() {
ModelAndView model = new ModelAndView();
model.setViewName("authentification");
return model;
}
#RequestMapping(method=RequestMethod.POST)
public void service(#RequestAttribute("smya") Str1, #RequestAttribute("mdps") Str2){
System.out.println(Str1);
System.out.println(Str2);
try {
URL url = new URL("<code>http://pc-demo-bi:8090/jasperserver-pro/rest/login?j_username="+Str1+"&j_password="+Str2</code>);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
System.out.println("connected");
return("rapports");
conn.disconnect();
}
catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
Hopefully that makes sense!
I was testing a demo servlet file But, the servlet doesn't seem to respond. I'm not able to understand the problem.
When I click submit on the HTML form the URL is
localhost:8080/Beer-V1/SelectBeer.do
But, shouldn't it be /BeerSelect? Because of #WebServlet("/BeerSelect") ???
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web- app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" metadata-complete="false"
version="3.0">
<servlet>
<servlet-name>CH3 Beer</servlet-name>
<servlet-class>com.example.web.BeerSelect</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CH3 Beer</servlet-name>
<url-pattern>/SelectBeer.do</url-pattern>
</servlet-mapping>
</web-app>
BeerSelect.java
package com.example.web;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet("/BeerSelect")
public class BeerSelect extends HttpServlet {
private static final long serialVersionUID = 1L;
public BeerSelect() {
super();
}
#Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("Beer Selection Advice<br>");
String c = request.getParameter("color");
out.println("<br> Got Beer Color " + c);
}
}
When I click submit on the HTML form the URL is localhost:8080/Beer-V1/SelectBeer.do
But, shouldn't it be /BeerSelect? Because of #WebServlet("/BeerSelect") ???
web-container associates a "context-path" for each of the web-application deployed and in your case, I believe it is "Beer-V1".
You have overridden the mapping in web.xml as below and hence you are seeing *.do
<servlet-mapping>
<servlet-name>CH3 Beer</servlet-name>
<url-pattern>/SelectBeer.do</url-pattern>
</servlet-mapping>
The xml DD overrides the annotations.
I have modified my application to find out the number of users logged in a web application below is my piece of code..
the listener class
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
public class SessionCounter implements HttpSessionListener
{
private static int count;
public static int getActiveSessions() {
return count;
}
public SessionCounter()
{
}
//The "sessionCount" attribute which has been set in the servletContext should not be modified in any other part of the application.
//Since we are using serveltContext in both the methods to modify the same variable, we have synchronized it for consistency.
public void sessionCreated(HttpSessionEvent e)
{
count++;
ServletContext sContext = e.getSession().getServletContext();
synchronized (sContext)
{
sContext.setAttribute("sessionCount", new Integer(count));
}
}
public void sessionDestroyed(HttpSessionEvent e)
{
count--;
ServletContext sContext = e.getSession().getServletContext();
synchronized (sContext)
{
sContext.setAttribute("sessionCount", new Integer(count));
}
}
}
and the main servlet is ..
package com.saral;
import java.io.IOException;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class First
*/
//#WebServlet("/First")
public class MyServlet extends HttpServlet
{
private static final long serialVersionUID = 1L;
static final Logger logger = Logger.getLogger(MyServlet.class);
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PropertyConfigurator.configure("log4j.properties");
logger.info("before---->");
// TODO Auto-generated method stub
String name=request.getParameter("txtName");
response.setContentType("text/html");
PrintWriter out=response.getWriter();
out.println("Hello,"+name);
out.println("<br> this output is generated by a simple servlet.");
out.println("Total Number of users logged in--->"+SessionCounter.getActiveSessions());
out.close();
}
}
and the web.xml is ...
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>FirstDemo</display-name>
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>/WEB-INF/log4j.properties</param-value>
</context-param>
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>com.saral.MyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/helloServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>home.html</welcome-file>
</welcome-file-list>
<listener>
<listener-class>com.saral.SessionCounter</listener-class>
</listener>
</web-app>
but I am getting the total number of users logged in as 0 , which is not perfect, please advise where I am wrong and how can I overcome from this.
When a client request come to the Tomcat server and you don't call request.getSession(), then the Tomcat server stil creates a session automatically. After that, the method sessionCreated(...) in your SessionCounter class is called.
The method sessionDestroyed(...) will be called when a session is destroyed. That occurs when you call session.invalidate(). If you close a tab on browser or close a browser, the session is still alive on your tomcat server.
I think so. You can use some diffrent listeners to archive your goal: HttpSessionAttributeListener, HttpSessionBindingListener,...
I am trying a servlet that puts the data into the database:derbi (that comes packed with netbeans). When a user clicks to submit data,the request follows to the FormHandler servlet (given below) If any of the text-field was empty the request follows to another servlet ErrorServlet and if every thing was fine the request follows to the Registered servlet. But before the request follows to the Registered Servlet there is a small code that is written to insert the data into the database (After this code the the user views the success page,that he has been registered).
Now the problem : The user fills all the text fields in the form and clicks submit. When he clicks submit,he sees the success page displaying Registered Successfully . But when i query the databse, i see that the data wasn't submitted to the databse. The rows and columns are empty ! I don't understand the reason for this .
Code for FormHandler.java :
package FormHandler;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.LinkedList;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.sql.DataSource;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
public class FormHandler extends HttpServlet {
#Override
public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException {
}
#Override
public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException {
String name = request.getParameter("Name");
String email = request.getParameter("Email");
String password = request.getParameter("Password");
LinkedList list = new LinkedList();
if(name.compareTo("") == 0 || email.compareTo("") == 0 || email.compareTo("") == 0) {
list.add("One or more field's' left blank");
request.setAttribute("ErrorList", list);
RequestDispatcher rd = request.getRequestDispatcher("ErrorServlet.view");
rd.forward(request, response);
} else {
try {
Context context = new InitialContext();
DataSource ds = (DataSource)context.lookup("java:comp/env/jdbc/MyDatasource");
Connection connection = ds.getConnection();
String sqlStatement = "INSERT INTO INFORMATION VALUES('" + name + "'," + "'" + email + "'," + "'" + password + "')";
PreparedStatement statement = connection.prepareStatement(sqlStatement);
ResultSet result = statement.executeQuery();
}catch(Exception exc) {
System.out.println(exc);
}
request.setAttribute("Data", list);
RequestDispatcher rd = request.getRequestDispatcher("Registered.view");
rd.forward(request, response);
}
}
}
XML file:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<servlet>
<servlet-name>FormHandler</servlet-name>
<servlet-class>FormHandler.FormHandler</servlet-class>
</servlet>
<servlet>
<servlet-name>Registered</servlet-name>
<servlet-class>FormHandler.Registered</servlet-class>
</servlet>
<servlet>
<servlet-name>ErrorServlet</servlet-name>
<servlet-class>FormHandler.ErrorServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FormHandler</servlet-name>
<url-pattern>/FormHandler.do</url-pattern>
</servlet-mapping>
<resource-ref>
<res-ref-name>jdbc/MyDatasource</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
<res-sharing-scope>Shareable</res-sharing-scope>
</resource-ref>
<servlet-mapping>
<servlet-name>Registered</servlet-name>
<url-pattern>/Registered.view</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>ErrorServlet</servlet-name>
<url-pattern>/ErrorServlet.view</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
Html File :Code for html file
Note : I have already made a connection to database
I think you are getting somewhere a :
java.sql.SQLException: No ResultSet was produced
because executing your UPDATE query with executeQuery() actually returns no resultset
Use:
statement.executeUpdate();
try the following:
PreparedStatement ps2=null;
ps2 = connection.prepareStatement("INSERT INTO INFORMATION( colname1, colname2,colname3) VALUES(? ,? ,?)");
ps2.setString(1, name);
ps2.setString(2, email);
ps2.setString(3, password);
try {
rs=ps2.executeUpdate();
} catch (SQLException ex) {
// catch if any exception
}