Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 5 of 5

Thread: need help getting started

  1. #1
    Junior Member
    Join Date
    Mar 2014
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default need help getting started

    Hello. I am a long time programmer in C++ who has had some experience with Java in the past, but almost exclusively simple, good old fashioned stuff, with no databases or web servers or anything like that.

    Now, I need to learn how to write servlets, both for my own uses (a personal project I'm working on) but also to show a potential employer that I know how. Because this is also for a potential employer, I am using their tool chain. I have no problem learning from tutorials and the like, so this is also no big issue. The problem is I can't seem to get the silly environment configured, and all the tutorials I've went through just take for granted certain steps.

    I am using Eclipse, Tomcat, and postgres. If anyone could please post a step by step set of instructions to get all three of these things working together, that would be great. I've gotten Eclipse and postgres talking and have worked through several turorials there, and I have also gotten Eclipse and Tomcat working together, and don some tutorials in that direction. The problem is making all three work together.

    Any help anyone can offer would be greatly appreciated. I am at my wits end after 3 days of struggling with this, and I am about to toss the whole thing out the window.

    P.S. Windows or Linux, doesn't matter.


  2. #2
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,520
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: need help getting started

    Welcome to the forum! Please read this topic to learn how to post code correctly and other useful info for new members.

    It seems you're well past getting started. Phew!

    Please post the code you've tried to connect all 3 elements of your development environment, and provide any errors or descriptions of other evidence you're seeing that indicate the code is not achieving the desired result.

  3. #3
    Junior Member
    Join Date
    Mar 2014
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: need help getting started

    Quote Originally Posted by GregBrannon View Post
    Welcome to the forum! Please read this topic to learn how to post code correctly and other useful info for new members.

    It seems you're well past getting started. Phew!

    Please post the code you've tried to connect all 3 elements of your development environment, and provide any errors or descriptions of other evidence you're seeing that indicate the code is not achieving the desired result.
    Ok. First of all, this is from a tutorial from this site: http://met.guc.edu.eg/

    I've not altered the code in any appreciable way (hopefully not at all, but i had to alter some to fit my server specs, etc, anything beyond that was accidental)

    Anyway, this is the ConnectionManager.java class:

    package ExamplePackage;
     
     import java.sql.*;
     
     
       public class ConnectionManager {
     
          static Connection con;
          static String url;
     
          public static Connection getConnection()
          {
     
             try
             {
                String url = "jdbc:odbc:" + "jason"; 
                // assuming "DataSource" is your DataSource name
     
                Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
     
                try
                {            	
                   con = DriverManager.getConnection(url,"jason","Pass1234"); 
     
                // assuming your SQL Server's	username is "username"               
                // and password is "password"
     
                }
     
                catch (SQLException ex)
                {
                   ex.printStackTrace();
                }
             }
     
             catch(ClassNotFoundException e)
             {
                System.out.println(e);
             }
     
          return con;
    }
       }

    This is the LoginServlet.java

    package ExamplePackage;
     
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
     
    /**
     * Servlet implementation class LoginServlet
     */
    public class LoginServlet extends HttpServlet {
     
     
    public void doGet(HttpServletRequest request, HttpServletResponse response) 
    			           throws ServletException, java.io.IOException {
     
    try
    {	    
     
         UserBean user = new UserBean();
         user.setUserName(request.getParameter("un"));
         user.setPassword(request.getParameter("pw"));
     
         user = UserDAO.login(user);
     
         if (user.isValid())
         {
     
              HttpSession session = request.getSession(true);	    
              session.setAttribute("currentSessionUser",user); 
              response.sendRedirect("userLogged.jsp"); //logged-in page      		
         }
     
         else 
              response.sendRedirect("invalidLogin.jsp"); //error page 
    } 
     
     
    catch (Throwable theException) 	    
    {
         System.out.println(theException); 
    }
           }
    	}

    this is UserBean.java

    package ExamplePackage;
     
    public class UserBean {
     
        private String username;
        private String password;
        private String firstName;
        private String lastName;
        public boolean valid;
     
     
        public String getFirstName() {
           return firstName;
    	}
     
        public void setFirstName(String newFirstName) {
           firstName = newFirstName;
    	}
     
     
        public String getLastName() {
           return lastName;
    			}
     
        public void setLastName(String newLastName) {
           lastName = newLastName;
    			}
     
     
        public String getPassword() {
           return password;
    	}
     
        public void setPassword(String newPassword) {
           password = newPassword;
    	}
     
     
        public String getUsername() {
           return username;
    			}
     
        public void setUserName(String newUsername) {
           username = newUsername;
    			}
     
     
        public boolean isValid() {
           return valid;
    	}
     
        public void setValid(boolean newValid) {
           valid = newValid;
    	}	
    }

    and this is UserDAO.java

    package ExamplePackage;
     
    	import java.text.*;
       import java.util.*;
       import java.sql.*;
     
       public class UserDAO 	
       {
          static Connection currentCon = null;
          static ResultSet rs = null;  
     
     
     
          public static UserBean login(UserBean bean) {
     
             //preparing some objects for connection 
             Statement stmt = null;    
     
             String username = bean.getUsername();    
             String password = bean.getPassword();   
     
             String searchQuery =
                   "select * from users where username='"
                            + username
                            + "' AND password='"
                            + password
                            + "'";
     
          // "System.out.println" prints in the console; Normally used to trace the process
          System.out.println("Your user name is " + username);          
          System.out.println("Your password is " + password);
          System.out.println("Query: "+searchQuery);
     
          try 
          {
             //connect to DB 
             currentCon = ConnectionManager.getConnection();
             stmt=currentCon.createStatement();
             rs = stmt.executeQuery(searchQuery);	        
             boolean more = rs.next();
     
             // if user does not exist set the isValid variable to false
             if (!more) 
             {
                System.out.println("Sorry, you are not a registered user! Please sign up first");
                bean.setValid(false);
             } 
     
             //if user exists set the isValid variable to true
             else if (more) 
             {
                String firstName = rs.getString("FirstName");
                String lastName = rs.getString("LastName");
     
                System.out.println("Welcome " + firstName);
                bean.setFirstName(firstName);
                bean.setLastName(lastName);
                bean.setValid(true);
             }
          } 
     
          catch (Exception ex) 
          {
             System.out.println("Log In failed: An Exception has occurred! " + ex);
          } 
     
          //some exception handling
          finally 
          {
             if (rs != null)	{
                try {
                   rs.close();
                } catch (Exception e) {}
                   rs = null;
                }
     
             if (stmt != null) {
                try {
                   stmt.close();
                } catch (Exception e) {}
                   stmt = null;
                }
     
             if (currentCon != null) {
                try {
                   currentCon.close();
                } catch (Exception e) {
                }
     
                currentCon = null;
             }
          }
     
    return bean;
     
          }	
       }

    And just to be safe, this is the LoginPage.jsp

    <%@ page language="java" 
        contentType="text/html; charset=windows-1256"
        pageEncoding="windows-1256"
    %>
     
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
     
    <html>
    	<head>
                                    <meta http-equiv="Content-Type" content="text/html; charset=windows-1256">
    		<title>Login Page</title>
    	</head>
     
    	<body>
    		<form action="LoginServlet">
     
    			Please enter your username 		
    			<input type="text" name="un"/><br>		
     
    			Please enter your password
    			<input type="text" name="pw"/>
     
    			<input type="submit" value="submit">			
     
    		</form>
    	</body>
    </html>


    Edit: almost forgot, when I run the LoginPage.jsp it looks like it should, then when I go to hit the submit button, I get this error:

    type Status report
     
    message /LoginExample/LoginServlet
     
    description The requested resource (/LoginExample/LoginServlet) is not available.

    but I know that the database is accessible, because I have run other code on that exact connection host/user/password before.
    Last edited by eternal_sage; March 18th, 2014 at 09:00 PM.

  4. #4
    Junior Member
    Join Date
    Mar 2014
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: need help getting started

    Upon viewing the error from tomcat more closely, I don't think my original thought was correct. It looks more like the LoginServlet did not get called (or found?) correctly when called from the LoginPage. This may have nothing to do with db access at all. If so, sorry.

    Edit: After doing a little more digging, I'm beginning to think that it may have something to do with the web.xml file, but I really don't understand what this file does or what I might need to do to fix it. This is my web.xml file:

    <?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"
    	version="3.0">
    	<display-name>LoginExample</display-name>
    	<welcome-file-list>
    		<welcome-file>index.html</welcome-file>
    		<welcome-file>index.htm</welcome-file>
    		<welcome-file>index.jsp</welcome-file>
    		<welcome-file>default.html</welcome-file>
    		<welcome-file>default.htm</welcome-file>
    		<welcome-file>default.jsp</welcome-file>
    	</welcome-file-list>
    </web-app>

    I will keep digging on this, but again, any help would be great. Thanks everyone!

    Edit2: Ok. So I attempted to adjust the web.xml to include a servlet definition (I think its called) and got a completely new error, which makes me think I am close.

    type Exception report
     
    message
     
    description The server encountered an internal error () that prevented it from fulfilling this request.
     
    exception
     
    javax.servlet.ServletException: Error instantiating servlet class LoginServlet
    	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.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:302)
    	java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    	java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    	java.lang.Thread.run(Thread.java:744)
    root cause
     
    java.lang.ClassNotFoundException: LoginServlet
    	org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1676)
    	org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1521)
    	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.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:302)
    	java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    	java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    	java.lang.Thread.run(Thread.java:744)
    note The full stack trace of the root cause is available in the Apache Tomcat/7.0.12 logs.

    and this is my newly edited 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"
    	version="3.0">
    	<display-name>LoginExample</display-name>
    	<welcome-file-list>
    		<welcome-file>index.html</welcome-file>
    		<welcome-file>index.htm</welcome-file>
    		<welcome-file>index.jsp</welcome-file>
    		<welcome-file>default.html</welcome-file>
    		<welcome-file>default.htm</welcome-file>
    		<welcome-file>default.jsp</welcome-file>
    	</welcome-file-list>
    <servlet>
        <servlet-name>Login</servlet-name>
        <servlet-class>LoginServlet</servlet-class>
      </servlet>
      <servlet-mapping>
        <servlet-name>Login</servlet-name>
        <url-pattern>/LoginServlet</url-pattern>
      </servlet-mapping>
    </web-app>
    Last edited by eternal_sage; March 19th, 2014 at 12:42 PM.

  5. #5
    Junior Member
    Join Date
    Mar 2014
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: need help getting started

    Ok, got the silly errors out of the way, and I am back to the issue that brought me here originally. It was a problem with my web.xml file. This is the correct one, in case anyone is trying this on their own. I was basically missing the package name in the class definition (oops... silly me )

    <?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"
    	version="3.0">
    	<display-name>LoginExample</display-name>
    	<welcome-file-list>
    		<welcome-file>LoginPage.jsp</welcome-file>
    	</welcome-file-list>
    <servlet>
        <servlet-name>Login</servlet-name>
        <servlet-class>ExamplePackage.LoginServlet</servlet-class>
      </servlet>
      <servlet-mapping>
        <servlet-name>Login</servlet-name>
        <url-pattern>/LoginServlet</url-pattern>
      </servlet-mapping>
    </web-app>

    Now, when I run the program, it seems to do its thing, but it tells me i do not exist in the db, even when I do. Its definitely passing the info into the right classes, etc, because in my console in Eclipse I am getting this output:

    Your user name is eternal_sage
    Your password is Pass1234
    Query: select * from users where username='eternal_sage' AND password='Pass1234';
    java.lang.ClassNotFoundException: sun.jdbc.odbc.JdbcOdbcDriver
    Log In failed: An Exception has occurred! java.lang.NullPointerException

    which is consistent with the error checking in the UserDAO class. I know the statement generated by the code works, as I've copied it verbatim into psql in the terminal and it gets exactly the result I'm looking for. What I am not understanding is the class not found exception. What does this mean? Am I missing some include or a lib or something? I am not sure I understand this statement in the source code either (its copied from a tutorial, not my own). What purpose does it serve? Is it just error checking? More digging, I suppose.

    Oh, and sorry for posting and editing so much. I guess this thread is the equivalent of me thinking out loud so far. If this is somehow disrespectful, please just delete the thread. I just can't wait until someone answers to keep hacking at this thing, and as I am figuring out my screw ups it seems important to keep the thread updated so if someone does try to help me they have full info. I know you guys are busy, don't misunderstand. Its just that I have the time to work on this today, and may not for a while. Besides, I learn better when I figure it out on my own sometimes I just need a nudge in the right direction.

    --- Update ---

    Ok. Seems that the tutorial I was following was using the ODBC to try and connect to the DB, which from my understanding, is a terrible, outdated, and not cross-platform compatible method of doing things. So I replaced all that code with the code I used in my DB program that I know works (using the JDBC postgres driver) and registered the silly thing in the classpath (oops) and viola, I'm to a whole new error . Looking at my console, it seems that I have actually accessed the db now, it seems to be an issue with the UserLogged.jsp which is the destination page when the db access is successful. This error seems to have something to do with the UserBean class, or at least how it is being used in this case.

    UserLogged:
       <%@ page language="java" 
             contentType="text/html; charset=windows-1256"
             pageEncoding="windows-1256"
             import="ExamplePackage.UserBean"
       %>
     
       <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
       "http://www.w3.org/TR/html4/loose.dtd">
     
       <html>
     
          <head>
             <meta http-equiv="Content-Type" 
                content="text/html; charset=windows-1256">
             <title>   User Logged Successfully   </title>
          </head>
     
          <body>
     
             <center>
                <% UserBean currentUser = (UserBean(session.getAttribute("currentSessionUser")));%>
     
                Welcome <%= currentUser.getFirstName() + " " + currentUser.getLastName() %>
             </center>
     
          </body>
     
       </html>

    The error is pointing at the line UserBean currentUser = (UserBean(session.getAttribute("currentSessionUser ")));
    which looks alittle weird to me as well, although I'm not sure exactly what its doing, so I'm going to keep digging.


    Edit: N/M I realized I needed to cast the UserBean. The code should have looked like this: <% UserBean currentUser = ((UserBean) (session.getAttribute("currentSessionUser")));%>

    Which means that I am up and running completely! WOOT! I'll mark this as solved then. Sorry for all the trouble. Maybe my ramblings will help someone else, though.
    Last edited by eternal_sage; March 19th, 2014 at 04:30 PM.

Similar Threads

  1. hello everyone! what is the best way to get started?
    By mikef1965 in forum Java Theory & Questions
    Replies: 1
    Last Post: May 31st, 2013, 10:31 PM
  2. Getting started in AI.
    By Bitterguy in forum Java Theory & Questions
    Replies: 3
    Last Post: January 1st, 2013, 08:39 PM
  3. Help getting started
    By gettnstarted in forum Member Introductions
    Replies: 19
    Last Post: January 1st, 2013, 01:19 PM
  4. Help me get started
    By blockme2011 in forum What's Wrong With My Code?
    Replies: 3
    Last Post: September 16th, 2012, 06:28 AM
  5. Can anyone help get me started?
    By linkazoid in forum What's Wrong With My Code?
    Replies: 1
    Last Post: September 14th, 2012, 04:02 PM