Attempting to add a record into database using a shared connection(connection created upon intialising a request) Here i'm request.getAttribute() method to retrieve attribute from RequestListener.java and assigning it to Connection type reference.
here's my code:RequestListener.java
public class RequestListener implements ServletRequestListener {
#Override
public void requestDestroyed(ServletRequestEvent sre) {
try {
Connection connection=(Connection) sre.getServletContext().getAttribute("conn");
connection.close();
} catch (SQLException ex) {
Logger.getLogger(RequestListener.class.getName()).log(Level.SEVERE, null, ex);
}
}
#Override
public void requestInitialized(ServletRequestEvent sre) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection connection= DriverManager.getConnection("jdbc:mysql://localhost/school?user=root&password=mysql");
sre.getServletContext().setAttribute("conn",connection);
} catch (Exception ex) {
Logger.getLogger(RequestListener.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
error:java.lang.NullPointerException
at servlets.One.processRequest(One.java:45)
at servlets.One.doGet(One.java:89)
//////
One.java (servlet)
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
String t1=request.getParameter("text1");
out.println("A");
Connection connection = (Connection) request.getAttribute("conn");
//line45 **PreparedStatement ps = connection.prepareStatement("insert into tb1 values(?)");**
ps.setString(1, t1);
ps.executeUpdate();
ps.close();
request.setAttribute("conn", connection);
request.getRequestDispatcher("B").forward(request, response);
request.getRequestDispatcher("Two").forward(request, response);
} catch (SQLException ex) {
Logger.getLogger(One.class.getName()).log(Level.SEVERE, null, ex);
}
}
RequestListener.java
"sre.getServletContext().setAttribute("conn",connection)" has to corrected as sre.getServletRequest().setAttribute("conn",connection) and avoid sending requests to two servlets as "request.getRequestDispatcher("B").forward(request, response);
request.getRequestDispatcher("Two").forward(request, response);" which results a illegalStateException
Related
I am trying to access an Oracle DB connection using Jboss datasource but it's throwing java.lang.NullPointerException.
Below is my code and jboss shows below logs during startup.
What's wrong in my code?
WFLYJCA0001: Bound data source [java:/jdbc/testOracleDS]
#WebServlet("/Index")
public class Index extends HttpServlet {
private static final long serialVersionUID = 1L;
private DataSource dataSource;
Connection conn = null;
public Index() {
super();
// TODO Auto-generated constructor stub
}
public void init() throws ServletException {
try {
DataSource anotherDataSource = InitialContext.doLookup("java:/jdbc/testOracleDS");
} catch (NamingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
conn = dataSource.getConnection();
System.out.println("connection established");
response.getWriter().println("connection established");
} catch (Exception e) {
e.printStackTrace();
response.getWriter().println("failed to establish connection: " + e);
} finally {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
I fixed this issue by adjusting code, The Datasource variable was not correctly initialized
public class Index extends HttpServlet {
private static final long serialVersionUID = 1L;
private DataSource dataSource;
Connection conn = null;
public Index() {
super();
// TODO Auto-generated constructor stub
}
public void init() throws ServletException {
try {
dataSource = InitialContext.doLookup("java:/jdbc/testOracleDS");
} catch (NamingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
conn = dataSource.getConnection();
System.out.println("connection established");
response.getWriter().println("connection established");
} catch (Exception e) {
e.printStackTrace();
response.getWriter().println("failed to establish connection: " + e);
} finally {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}}
I have a class which connect to a MSSQL Database.
The connection is successfully because if i run the code in my debugger (Eclipse) i can see that the connection is not null.
Also the If-Statement is called because the connection is not null
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String query = "My Query";
con = DBVerbindung();
//The connection is not null
if (con != null) {
try {
//Here the connection is closed
stmt = con.prepareStatement(query);
} catch (Exception e) {
e.printStackTrace();
}
}
private Connection DBVerbindung() {
return DatabaseConnection.Verbindung();
}
}
But in the next line if i want to call the preparedStatement i got a Connection fail error:
Here is my DatabaseConnection Class
public class DatabaseConnection {
public static Connection Verbindung() {
final String connectionUrlMsSQLDEV = "jdbc:sqlserver://XXXXX:1234;databaseName=hrpap_itha_apps_dev;user=HRPAP-dev;password=XXXXX";
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try (Connection conn = DriverManager.getConnection(connectionUrlMsSQLDEV)) {
if (conn != null) {
System.out.println("Verbunden!");
} else {
System.out.println("Fehler: Verbindung konnte nicht hergestellt werden! ---> " + DatabaseConnection.class.getName() );
}
return conn;
} catch (SQLException e) {
System.err.format("SQL State: %s\n%s", e.getSQLState(), e.getMessage());
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
So why is the connection at this point null ?
Thanks
I am unable to get a connection from a datasource and it returns an error-500 The server encountered an internal error () that prevented it from fulfilling this request.
public class Student extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String id = null;
String pass = null;
Authenticate a=new Authenticate();
response.setContentType("text/html");
PrintWriter out = response.getWriter();
id = request.getParameter("name");
pass = request.getParameter("password");
String result=a.validate(id, pass);
out.println(result);
out.close();
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request,response);
}
}
public class Authenticate extends HttpServlet {
DataSource datasource = null;
String query = "SELECT COUNT(*) FROM studentlogin WHERE name=? and password=?";
public void init(ServletConfig config) throws ServletException {
try {
// Look up the JNDI data source only once at init time
Context envCtx = new InitialContext();
datasource = (DataSource) envCtx.lookup("java:/apalya");
System.out.println("\t datasooource :: " + datasource);
//datasource = (DataSource) ctx.lookup("apalya");
}
catch (NamingException e) {
e.printStackTrace();
}
}
private Connection getConnection() throws SQLException {
return datasource.getConnection();
}
public String validate(String name1, String password1) {
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultset = null;
int count = 0;
try {
connection = getConnection();
statement = connection.prepareStatement(query);
statement.setString(1, name1);
statement.setString(2, password1);
resultset = statement.executeQuery();
if (resultset.next()) {
count = resultset.getInt(1);
}
if (count == 0) {
return "Invalid Credentials";
} else {
return "Successfully Loggedin";
}
} catch (SQLException sqlException) {
sqlException.printStackTrace();
return "Internal Problem";
}
finally {
if (resultset != null) {
try {
resultset.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
I get a NullPointerException at the getConnection method and error 500 is shown in the browser. I gave the same name of the lookup in the datasource xml file.
<servlet>
<servlet-name>abc</servlet-name>
<servlet-class>com.apalya.records.Student</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>abc</servlet-name>
<url-pattern>/stu</url-pattern>
</servlet-mapping>
</web-app>
I have a strange issue with servlet page. I have simple web application which contains just a servlet.I deployed it in Tomcat 7. When user enters url, the servlet should get directly executed, get the data from the database and print the output. But it shows blank page after some time. When I undeploy and deploy, it shows data. After some time when I access the page, it shows blank page. Then again when I redeploy, it shows data. Can someone please let me know how to resolve this? I have no clue why it happens. Below is my code.
I am using mysql database.mysql-connector-java-5.1.29-bin.jar added in lib folder and added to buildpath.
public class Homeservlet extends HttpServlet {
private static final long serialVersionUID = 1L;
static final String mysqldblink = "************";
static final String mysqlUsername = "username";
static final String mysqlPassword = "pw";
Connection connection =null;
Statement stmt = null;
/**
* #see HttpServlet#HttpServlet()
*/
public Homeservlet() {
super();
// TODO Auto-generated constructor stub
}
public void init(ServletConfig config) throws ServletException
{
super.init(config);
try{
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(mysqldblink,
mysqlUsername, mysqlPassword);
stmt = connection.createStatement();
}
catch(Exception E)
{
E.printStackTrace();
}
}
#Override
public void service(ServletRequest request, ServletResponse response)
{
PrintWriter pw = null;
try {
String query = "querytogetdata";
pw = response.getWriter();
ResultSet rs = stmt.executeQuery(query);
while(rs.next())
{
pw.println(rs.getString(1));
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch(Exception e)
{
e.printStackTrace();
}finally{
try{
pw.close();
}catch(Exception e)
{
e.printStackTrace();
}
}
}
#Override
public void destroy( ) {
// Close the connection
try {
if (connection != null)
connection.close( );
if(stmt != null)
stmt.close();
} catch (SQLException ignore) { }
}
}
I wrote a servlet whose purpose is to login into the application only if the query executes...now what is the condition to be used for invalid username and id...I'm unable to write the condition..pls help me out...the servlet is...
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:orcl ","scott","tiger");
System.out.println("cnnection est");
int Id = Integer.parseInt(request.getParameter("id"));
String Name=request.getParameter("firstname");
boolean b=true;
//Connection con =JdbcConnectionUtil.getConnection();
PreparedStatement pst = con.prepareStatement("select * from login where id=? and firstname=?");
pst.setInt(1, Id);
pst.setString(2, Name);
ResultSet rs = pst.executeQuery();
if(rs!=null && rs.next())
{
//while(rs.next()){
PrintWriter pw = response.getWriter();
System.out.println("here");
pw.println("hello");
pw.println(rs.getInt(1));
pw.println(rs.getString(2));
pw.println(rs.getString(3));
}
//}
else
{
RequestDispatcher rd = request.getRequestDispatcher("/LoginFailed.html");
}
//
}
catch(Exception ex){
ex.printStackTrace();
}
}
Using rd.forward will solve the problem I think.
How to forward requests from Servlet to JSP
First you check for the correct parameters and then you do the logic. Also do not forget to close statements and connections to avoid memory leaks.
Here is refactored code:
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//get parameters from request
try {
String idParam = request.getParameter("id");
String name = request.getParameter("firstname");
//check if request contains such parameters
if (idParam == null || name == null) {
throw new IllegalArgumentException(
"Id and Name parameters must not be null.");
}
//try casting idParam to int
Integer id = null;
try {
id = Integer.parseInt(idParam);
} catch (NumberFormatException nfe) {
throw nfe;
}
PreparedStatement pst = null;
Connection con = null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection(
"jdbc:oracle:thin:#localhost:1521:orcl ", "scott", "tiger");
pst = con.prepareStatement(
"select * from login where id=? and firstname=?");
pst.setInt(1, id);
pst.setString(2, name);
//check if result returned any data
ResultSet rs = pst.executeQuery();
if (!rs.next()) {
throw new Exception(
"No such user for id: " + id + " and name: " + name);
}
PrintWriter pw = response.getWriter();
pw.println("hello");
pw.println(rs.getInt(1));
pw.println(rs.getString(2));
pw.println(rs.getString(3));
} catch (Exception ex) {
throw ex;
} finally {
try {
if (pst != null) {
pst.close();
}
if (con != null) {
con.close();
}
} catch (SQLException sqle) {
throw sqle;
}
}
} catch (Exception ex) {
ex.printStackTrace();
RequestDispatcher rd = request.getRequestDispatcher("/LoginFailed.html");
rd.forward(request, response);
}
}
Something like that would be appropriate I think.