ClassNotFoundException of com.mysql.jdbc.Driver, when using servlets - servlets

this wierd problem is very interrupting me for a long time. I have a class name Connector inside dynamic web application in eclipse, with these code:
public class Connector {
private static final String dbURL = "jdbc:mysql://localhost:3306/";
private Connection con;
public Connector(String userName, String password) {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection(dbURL, userName, password);
} catch (SQLException e) {
e.printStackTrace();
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
catch (Exception e) {
System.err.print("Unidentified exception has acurred!");
e.printStackTrace();
}
}
when I'm using it from different Class in the same package, named portal, it works fine, but when I'm trying to use it from servlet in package servlets, named LoginHandle.java, I get ClassNotFoundException.
The Class is in the build path of all classes, and I checked it by trying to import it from the servlet, but when I create new instance, it is not being recognized. I tried to move the servlet to the package of the connector, and vise versa, and it didn't affect. Here is the servlet's code:
package servlets;
import java.io.IOException;
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 portal.Connector;
import portal.UserTableAnalyzer;
#WebServlet("/LoginHandle")
public class LoginHandle extends HttpServlet {
private static final long serialVersionUID = 1L;
public LoginHandle() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String referer = request.getHeader("Referer");
String pageName = referer.substring(referer.lastIndexOf('/') + 1);
if(pageName.equals("Login.jsp"))
{
HttpSession session = request.getSession(false);
Connector c = new Connector("root", "16180339887");
c.executeUpdate("USE Main");
String id = request.getParameter("id"), password = request.getParameter("password");
String query = "SELECT FROM Users WHERE id ='" + id + "' AND password = '" + password + "'";
String[][] result = c.executeQuery(query);
UserTableAnalyzer uta = new UserTableAnalyzer(result);
if(result.length > 0)
{
session.setAttribute("userID", uta.getID(0));
session.setAttribute("role", uta.getRole(0));
response.sendRedirect("Main.jsp");
}
else
{
request.setAttribute("wrongDetails", new Boolean(true));
response.sendRedirect("Login.jsp");
}
}
else
response.getWriter().print(pageName);
}
}
sorry if my english is bad, or if details are missing

Your driver is not in the server classpath, build path has nothing to do with that.
You didn't write which application server are you using. You also should use DataSource in servlets, rather than DriverManager. Here is sample configuration for Tomcat.
UPDATE
For Tomcat 7 you need to do the following:
Put mysql jar in the $CATALINA_HOME/lib
Configure Datasource in context
<Resource name="jdbc/TestDB" auth="Container" type="javax.sql.DataSource"
maxActive="100" maxIdle="30" maxWait="10000"
username="user" password="pass"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/databaseName"/>
Use Datasource in servlet (pseudo code)
#WebServlet("/LoginHandle")
public class LoginHandle extends HttpServlet {
private static final long serialVersionUID = 1L;
#Resource(lookup="jdbc/testDB")
private DataSource ds;
...
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Connection c = ds.getConnection();
...

Related

Struts send response from AsyncContext

I am trying to do long polling in a struts web application. I start an AsyncContext inside an ActionSupport action method, do some time-consuming work async, and then would like to send the SUCCESS response to struts.
I know that I can do PrintWriter pw = asyncContext.getResponse().getWriter(); and write a raw response, but I would like to somehow signal struts to proceed with the predefined result in struts.xml. Is this possible?
<action name="myAction" method="action1" class="myActionClass">
<result name="success" type="redirectAction">
/pages/myPage.jsp <!-- I want to run this from async --->
</result>
</action>
In non-async action I can simply return SUCCESS and struts takes care of everything, but I am having trouble with achieving a similar effect with async action. This is what I have so far:
public void action1() {
HttpServletRequest req = ServletActionContext.getRequest();
HttpServletResponse res = ServletActionContext.getResponse();
final AsyncContext asyncContext = req.startAsync(req, res);
asyncContext.start(new Runnable() {
public void run() {
// Some time-consuming polling task is done here
asyncContext.complete();
// Can I somehow proceed to predefined struts result from here?
}
});
}
Currently it seems cannot be done clearly. I am working if I can import this support to Struts but for now, I have a hack which works. I extended StrutsExecuteFilter as below:
package me.zamani.yasser.ww_convention.utils;
import org.apache.struts2.dispatcher.PrepareOperations;
import org.apache.struts2.dispatcher.filter.StrutsExecuteFilter;
import org.apache.struts2.dispatcher.filter.StrutsPrepareFilter;
import org.apache.struts2.dispatcher.mapper.ActionMapping;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
/**
* Created by user on 8/31/2017.
*/
public class MYStrutsAsyncExecuteFilter extends StrutsExecuteFilter {
public final int REQUEST_TIMEOUT = 240000;//set your desired timeout here
private ExecutorService exe;
#Override
public void init(FilterConfig filterConfig) throws ServletException {
int size = 41;//set your desired pool size here
exe = Executors.newFixedThreadPool(
size,
new ThreadFactory() {
public Thread newThread(Runnable r) {
return new Thread(r, "My Struts Async Processor");
}
}
);
super.init(filterConfig);
}
#Override
public void doFilter(final ServletRequest req, final ServletResponse res, final FilterChain chain) throws IOException, ServletException {
final HttpServletRequest request = (HttpServletRequest) req;
final HttpServletResponse response = (HttpServletResponse) res;
if (excludeUrl(request)) {
chain.doFilter(request, response);
return;
}
// This is necessary since we need the dispatcher instance, which was created by the prepare filter
if (execute == null) {
lazyInit();
}
final ActionMapping mapping = prepare.findActionMapping(request, response);
//if recursion counter is > 1, it means we are in a "forward", in that case a mapping will still be
//in the request, if we handle it, it will lead to an infinite loop, see WW-3077
final Integer recursionCounter = (Integer) request.getAttribute(PrepareOperations.CLEANUP_RECURSION_COUNTER);
if (mapping == null || recursionCounter > 1) {
boolean handled = execute.executeStaticResourceRequest(request, response);
if (!handled) {
chain.doFilter(request, response);
}
} else {
/* I ADDED THESE */
final AsyncContext context = req.startAsync();
context.setTimeout(REQUEST_TIMEOUT);
context.addListener(new AsyncListener() {
public void onComplete(AsyncEvent asyncEvent) throws IOException {
}
public void onTimeout(AsyncEvent asyncEvent) throws IOException {
context
.getResponse()
.getWriter().write("Request Timeout");
}
public void onError(AsyncEvent asyncEvent) throws IOException {
context
.getResponse()
.getWriter().write("Processing Error");
}
public void onStartAsync(AsyncEvent asyncEvent) throws IOException {
}
});
exe.execute(new ContextExecution(context, mapping));
}
}
private boolean excludeUrl(HttpServletRequest request) {
return request.getAttribute(StrutsPrepareFilter.class.getName() + ".REQUEST_EXCLUDED_FROM_ACTION_MAPPING") != null;
}
#Override
public void destroy() {
exe.shutdown();
super.destroy();
}
class ContextExecution implements Runnable {
final AsyncContext context;
ActionMapping mapping;
public ContextExecution(AsyncContext context, ActionMapping mapping) {
this.context = context;
this.mapping=mapping;
}
public void run() {
try {
execute.executeAction((HttpServletRequest) context.getRequest(),
(HttpServletResponse) context.getResponse(), mapping);
context.complete();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
then
<filter>
<filter-name>struts2asyncexecute</filter-name>
<filter-class>me.zamani.yasser.ww_convention.utils.MYStrutsAsyncExecuteFilter</filter-class>
<async-supported>true</async-supported>
</filter>
then put your desired async actions in a specific package and exclude them from Strut's original filter but map them to above filter in your web.xml.
I'm working to improve this to be more configurable and clear then import to Struts.
Could you please test in your app? and please feel free to let me know any idea.

#WebServlet on Tomcat 7 getting 404 Error

Tomcat 7 running on Windows 7, using servlet annotation, is giving me a 404 error when I try this URL:
http://localhost:8080/LoginExample/
Tomcat is using JRE 1.7, and the servlet class is contained within folder .../webapps/LoginExample. It was compiled using Java 1.7. I have no Web.xml. It deploys without error.
Here is the class:
package com.journaldev.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class LoginServlet
*/
#WebServlet(
description = "Login Servlet",
urlPatterns = { "/LoginServlet" },
initParams = {
#WebInitParam(name = "user", value = "Pankaj"),
#WebInitParam(name = "password", value = "journaldev")
})
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public void init() throws ServletException {
//we can create DB connection resource here and set it to Servlet context
if(getServletContext().getInitParameter("dbURL").equals("jdbc:mysql://localhost/mysql_db") &&
getServletContext().getInitParameter("dbUser").equals("mysql_user") &&
getServletContext().getInitParameter("dbUserPwd").equals("mysql_pwd"))
getServletContext().setAttribute("DB_Success", "True");
else throw new ServletException("DB Connection error");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//get request parameters for userID and password
String user = request.getParameter("user");
String pwd = request.getParameter("pwd");
//get servlet config init params
String userID = getServletConfig().getInitParameter("user");
String password = getServletConfig().getInitParameter("password");
//logging example
log("User="+user+"::password="+pwd);
if(userID.equals(user) && password.equals(pwd)){
response.sendRedirect("LoginSuccess.jsp");
}else{
RequestDispatcher rd = getServletContext().getRequestDispatcher("/login.html");
PrintWriter out= response.getWriter();
out.println("<font color=red>Either user name or password is wrong.</font>");
rd.include(request, response);
}
}
}
Your servlet class LoginServlet is designed to handle only '/LoginServlet' url and in http://localhost:8080/LoginExample/ you are using '/' as url.
You must use http://localhost:8080/LoginExample/LoginServlet
OR
<form action="LoginServlet" method="post">
....
....
</form>

Can't open PDF from Servlet

i trying to open a pdf right after i created.
I want to see the result in my browser, but i dosen't.
By the way, the programm runs on a server.
If i try to open the pdf there, no problem - all works fine.
Just the client can't see the pdf if he clicks, for example, on a button.
Here's my code:
#WebServlet("/GeneratePdfCustomer")
public class GeneratePdfCustomer extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
final int id = Integer.parseInt(request.getParameter("id"));
makePdf(request, response, "POST",id);
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void makePdf(HttpServletRequest request,
HttpServletResponse response, String methodGetPost, int id)
throws ServletException, IOException {
response.setContentType("application/pdf");
try {
Document document = new Document();
PdfWriter.getInstance(document, response.getOutputStream());
document.open();
document.add(new Paragraph("Test"));
document.close();
} catch (Exception e) {
System.out.println("Error" + e);
}
}
}
I using the iText library.
EDIT:
Now i have change my servlet code, but still not working for me.
I can't see the pdf in my browser. Firefox and IE both are show nothing.
package de.WorldCheckCustomer.model;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
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 com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;
#WebServlet("/GeneratePdfCustomer")
public class GeneratePdfCustomer extends HttpServlet {
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
makePdf(request, response);
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
makePdf(request, response);
}
public void makePdf(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Set content type to application / pdf
// browser will open the document only if this is set
response.setContentType("application/pdf");
// Get the output stream for writing PDF object
OutputStream out = response.getOutputStream();
try {
Document document = new Document();
/* Basic PDF Creation inside servlet */
PdfWriter.getInstance(document, out);
document.open();
document.add(new Paragraph("Tutorial to Generate PDF using Servlet"));
document.add(new Paragraph(
"PDF Created Using Servlet, iText Example Works"));
document.close();
} catch (DocumentException exc) {
throw new IOException(exc.getMessage());
} finally {
out.close();
}
}
private static final long serialVersionUID = 6067021675155015602L;
}

Unable to send the value of two attributes to JSP from servlet using requestdispatcher

Please help . Below is my code to redirect the request with two attributes to JSP but both of the below two attributes returns the value of passWord .
1)user_Name
2)Pass_word
for example , ABC is my username and XYZ is my password which is get from the "FORM" but my second value i.e the value of the passWord variable is appears in both of the attribute.
printing inside the jsp page :
user_Name: XYS (Should be ABC instead of XYZ)
pass_Word: XYZ
servlet :
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.RequestDispatcher;
import javax.servlet.Servlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
public class JndiConn extends HttpServlet implements Servlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
String userName=request.getParameter("Username");
String passWord=request.getParameter("password");
String user_Name="";
request.setAttribute(user_Name,userName);
String pass_Word="";
request.setAttribute(pass_Word,passWord);
RequestDispatcher rd=request.getRequestDispatcher ("GetParameter.jsp");
System.out.println(userName);
System.out.println(passWord);
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
Connection connection = getConnection();
if (connection != null) {
String sql = "SELECT count(1) FROM scott.login_user where login_id ='"+userName+"' and password='"+passWord+"'";
String sql1 = "select SYSDATE from dual";
System.out.println(sql);
try{
PreparedStatement statement = connection.prepareStatement(sql);
ResultSet rs = statement.executeQuery();
while (rs.next()) {
int number=rs.getInt("count(1)");
System.out.println("Result value is "+number);
if(number==1)
{
System.out.println("THE LOGIN SUCCESS FOR::"+userName);
String sql2 = "INSERT INTO SCOTT.LOGIN_USER VALUES(3,'VINOTH','vinoth55','SCOTT',to_date('08/06/13','DD/MM/RR'),105)";
PreparedStatement statement1 = connection.prepareStatement(sql2);
ResultSet rs1 = statement1.executeQuery();
rd.forward(request, response);
}
else{
System.out.println("THE LOGIN FAILURE FOR "+userName);
rd.forward(request, response);
}
}
connection.close();
}catch(Exception e){
System.out.println(e);
}
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
private Connection getConnection() {
Connection connection = null;
try {
InitialContext context = new InitialContext();
DataSource dataSource = (DataSource) context.lookup("vinothprd");
connection = dataSource.getConnection();
} catch (NamingException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
}
Below is my JSP to print the user_Name and pass_Word :
JSP:
String user_Name="";
String userName=(String)request.getAttribute(user_Name);
String pass_Word="";
String passWord=(String)request.getAttribute(pass_Word);
System.out.println("user_Name: "+userName);
System.out.println("pass_Word: "+passWord);
Thanks for your help in advance...
In Servlet you are setting, attributes using empty value.
String user_Name="";
request.setAttribute(user_Name,userName);
String pass_Word="";
request.setAttribute(pass_Word,passWord);
First of all, this is wrong and I don't know why you are doing this.
In JSP, When you access request.getAttribute(user_Name); // which is empty "",
you will get the value of password as username was overridden.
Solution:
You should set attribute like
EDIT Servlet
String userName=request.getParameter("Username");
String passWord=request.getParameter("password");
String user_Name="userName";
request.setAttribute(user_Name, userName);
String pass_Word="passWord";
request.setAttribute(pass_Word, passWord);
then in JSP
String user_Name="userName"
String userName=(String) request.getAttribute(user_Name);
String pass_Word="passWord";
String passWord=(String)request.getAttribute(pass_Word);
See: http://docs.oracle.com/javaee/6/api/javax/servlet/ServletRequest.html#setAttribute

java servlet session maintain

I have develop servlet for generate Captcha code & add session name code
Generate Capta-code
import javax.servlet.*;
import java.io.*;
import java.awt.*;
import java.util.Random;
import java.awt.image.*;
import javax.imageio.*;
import javax.servlet.http.*;
public class capta extends HttpServlet
{
final int LEN=10;
BufferedImage image;
Random rnd;
public void doGet(HttpServletRequest req,HttpServletResponse rep)
{
try
{
image = new BufferedImage(200, 80, BufferedImage.TYPE_INT_RGB);
rnd=new Random();
rep.setContentType("image/jpeg");
String random_String=getRandomNumbers();
HttpSession ses=req.getSession();
ses.setAttribute("code",random_String);
Graphics g = image.getGraphics();
g.setFont(new Font("Maiandra GD",1,30));
g.setColor(Color.blue);
g.drawString(random_String,3,50);
g.dispose();
/// it was here
ImageIO.write(image, "jpg", rep.getOutputStream());
}
catch(Exception e)
{
}
}
private String getRandomNumbers()
{
StringBuffer str=new StringBuffer();
for(int i=1;i<=9;i++)
{
str.append(new Integer(rnd.nextInt(9)).toString());
}
return str.toString();
}
public void doPost(HttpServletRequest req,HttpServletResponse rep)throws ServletException , IOException
{
doGet(req,rep);
}
}
Use Generate capta-image in other servlet
import javax.servlet.*;
import java.io.*;
import javax.servlet.http.*;
public class capta_test extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse rep)
{
PrintWriter out=null;
try
{
String input=req.getParameter("txt_capta");
out=rep.getWriter();
rep.setContentType("text/html");
out.println("<html><head><title>Capta Test</title></head>");
out.println("<body>");
out.println("<h1> Capta is Generated </h1>");
out.println("<img src=\"http://localhost:8080/mahesh/capta\" />");
HttpSession ses=req.getSession();
String original=(String)ses.getAttribute("code");
if(original!=null)
{
out.println("<h1>Original Value "+original+"</h1>");
}
ses.invalidate();
out.println("</body>");
out.println("</html>");
}
catch(Exception e)
{
}
}
public void doPost(HttpServletRequest req,HttpServletResponse rep)throws ServletException , IOException
{
doGet(req,rep);
}
}
Both servlet work fine but I am not getting the session value which is generate in Capta-code servelt(added in servlet)
I am getting session value which is generate in previous capta-image.
See output :
Output - 1
Output - 2
Output - 3
Thank you ..
Put the random number generation logic in capta_test servlet and put that number in session. Because you are rendering HTML, the capta servlet will be called after the page load like this and do not invalidate the session.
Random number generator
import javax.servlet.*;
import java.io.*;
import javax.servlet.http.*;
public class capta_test extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse rep)
{
PrintWriter out=null;
try
{
String original=getRandomNumbers();
HttpSession ses=req.getSession(false);
ses.setAttribute("code",random_String);
String input=req.getParameter("txt_capta");
out=rep.getWriter();
rep.setContentType("text/html");
out.println("<html><head><title>Capta Test</title></head>");
out.println("<body>");
out.println("<h1> Capta is Generated </h1>");
out.println("<img src=\"http://localhost:8080/mahesh/capta\" />");
out.println("<h1>Original Value "+original+"</h1>");
out.println("</body>");
out.println("</html>");
}
catch(Exception e)
{
}
}
public void doPost(HttpServletRequest req,HttpServletResponse rep)throws ServletException , IOException
{
doGet(req,rep);
}
private String getRandomNumbers()
{
Random rnd=new Random();
StringBuffer str=new StringBuffer();
for(int i=1;i<=9;i++)
{
str.append(new Integer(rnd.nextInt(9)).toString());
}
return str.toString();
}
}
Image generator servlet
import javax.servlet.*;
import java.io.*;
import java.awt.*;
import java.util.Random;
import java.awt.image.*;
import javax.imageio.*;
import javax.servlet.http.*;
public class capta extends HttpServlet
{
final int LEN=10;
BufferedImage image;
public void doGet(HttpServletRequest req,HttpServletResponse rep)
{
try
{
HttpSession ses=req.getSession(false);
String random_String=(String)ses.getAttribute("code");
image = new BufferedImage(200, 80, BufferedImage.TYPE_INT_RGB);
rep.setContentType("image/jpeg");
Graphics g = image.getGraphics();
g.setFont(new Font("Maiandra GD",1,30));
g.setColor(Color.blue);
g.drawString(random_String,3,50);
g.dispose();
/// it was here
ImageIO.write(image, "jpg", rep.getOutputStream());
}
catch(Exception e)
{
}
}
public void doPost(HttpServletRequest req,HttpServletResponse rep)throws ServletException , IOException
{
doGet(req,rep);
}
}
Your program flow is wrong , the session value is null because the capta_test servlet is called even before the capta servlet.
Have a look at this simple tutorial. Hope this helps you move in the right path
Captcha in JSP and Servlet

Resources