使用Servlet& JSP

时间:2017-08-10 22:18:33

标签: java maven jsp servlets login

我尝试使用JSP和Servlet创建登录页面。它给了我一个并没有真正说出这么多的错误,所以我不知道从哪里开始才能解决它。

这是我的JSP代码:

<form class="form-horizontal" action="Login" method="POST">
                        <div class="form-group">
                            <label class="control-label col-sm-2" for="username">Username:</label>
                            <div class="col-sm-4">
                                <input type="text" class="form-control" id="username" placeholder="Enter username" name="un">
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="control-label col-sm-2" for="pwd">Password:</label>
                            <div class="col-sm-4">
                                <input type="password" class="form-control" id="pwd" placeholder="Enter password" name="pwd">
                            </div>
                        </div>

                        <div class="form-group">
                            <div class="col-sm-offset-2 col-sm-4">
                                <div class="checkbox">
                                    <label><input type="checkbox" name="remember"> Remember me</label>
                                </div>
                            </div>
                        </div>
                        <div class="form-group">
                            <div class="col-sm-offset-2 col-sm-4">
                                <button type="submit" class="btn btn-success">Submit</button>
                            </div>
                        </div>
                    </form>

登录Servlet:

@WebServlet("/Login")
public class LoginServlet extends HttpServlet {

/**
     * 
     */
    private static final long serialVersionUID = 1L;

public void doPost(HttpServletRequest request, HttpServletResponse response) 
                       throws ServletException, java.io.IOException {

try
{       

     User user = new User();
     user.setUsername(request.getParameter("un"));
     user.setPassword(request.getParameter("pwd"));

     if (UserDAO.authUser(user))
     {
          System.out.println("in!");
          HttpSession session = request.getSession(true);       
          session.setAttribute("currentSessionUser",user); 
          response.sendRedirect("home.jsp"); //logged-in page           
     }

     else {
         System.out.println("not in!");
            response.sendRedirect("invalidLogin.jsp"); //error page 
     }

} 

catch (Throwable theException)      
{
     System.out.println(theException); 
}
       }



    }

我的pom依赖文件:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>licenta</groupId>
  <artifactId>Tutoring</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>Tutoring Maven Webapp</name>
  <url>http://maven.apache.org</url>

  <dependencies>
  <dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>5.2.10.Final</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>6.0.5</version>
</dependency>

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>

    <dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.1.0</version>
</dependency>

 <dependency>
        <groupId>commons-codec</groupId>
        <artifactId>commons-codec</artifactId>
        <version>1.10</version>
    </dependency>
    <dependency>
         <groupId>commons-logging</groupId>
         <artifactId>commons-logging</artifactId>
         <version>1.1.1</version>
    </dependency>
    <dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.5</version>
</dependency>
    <dependency>
    <groupId>dom4j</groupId>
    <artifactId>dom4j</artifactId>
    <version>1.6.1</version>
</dependency>
<dependency>
    <groupId>xalan</groupId>
    <artifactId>xalan</artifactId>
    <version>2.7.2</version>
</dependency>
<dependency>
    <groupId>xerces</groupId>
    <artifactId>xerces</artifactId>
    <version>2.4.0</version>
</dependency>

<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-core</artifactId>
    <version>2.1</version>
</dependency>
  <dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-yaml</artifactId>
    <version>2.8.6</version>
</dependency>

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
</dependency>


  </dependencies>
  <build>
    <finalName>Tutoring</finalName>
  </build>


</project>

错误日志如下所示:

  Aug 11, 2017 6:44:41 PM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.j2ee.server:Tutoring' did not find a matching property.
Aug 11, 2017 6:44:42 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server version:        Apache Tomcat/7.0.78
Aug 11, 2017 6:44:42 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server built:          May 10 2017 15:02:19 UTC
Aug 11, 2017 6:44:42 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server number:         7.0.78.0
Aug 11, 2017 6:44:42 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: OS Name:               Windows 10
Aug 11, 2017 6:44:42 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: OS Version:            10.0
Aug 11, 2017 6:44:42 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Architecture:          amd64
Aug 11, 2017 6:44:42 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Java Home:             C:\Program Files\Java\jre1.8.0_121
Aug 11, 2017 6:44:42 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: JVM Version:           1.8.0_121-b13
Aug 11, 2017 6:44:42 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: JVM Vendor:            Oracle Corporation
Aug 11, 2017 6:44:42 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: CATALINA_BASE:         C:\Users\buciu\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp2
Aug 11, 2017 6:44:42 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: CATALINA_HOME:         C:\Program Files\Apache Software Foundation\Tomcat 7.0
Aug 11, 2017 6:44:42 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dcatalina.base=C:\Users\buciu\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp2
Aug 11, 2017 6:44:42 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dcatalina.home=C:\Program Files\Apache Software Foundation\Tomcat 7.0
Aug 11, 2017 6:44:42 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dwtp.deploy=C:\Users\buciu\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp2\wtpwebapps
Aug 11, 2017 6:44:42 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Djava.endorsed.dirs=C:\Program Files\Apache Software Foundation\Tomcat 7.0\endorsed
Aug 11, 2017 6:44:42 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dfile.encoding=Cp1252
Aug 11, 2017 6:44:42 PM org.apache.catalina.core.AprLifecycleListener lifecycleEvent
INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program Files\Java\jre1.8.0_121\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:/Program Files/Java/jre1.8.0_121/bin/server;C:/Program Files/Java/jre1.8.0_121/bin;C:/Program Files/Java/jre1.8.0_121/lib/amd64;C:\ProgramData\Oracle\Java\javapath;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\Windows Live\Shared;C:\Program Files (x86)\Skype\Phone\;C:\Python27;C:\Anaconda;C:\Anaconda\Scripts;C:\Program Files\nodejs\;C:\Program Files\MySQL\MySQL Utilities 1.6\;C:\apache-maven-3.5.0\bin;C:\apache-maven-3.5.0;C:\Program Files\Java\jdk1.8.0_121\bin;C:\apache-maven-3.5.0\bin;C:\Users\buciu\Anaconda3;C:\Users\buciu\Anaconda3\Scripts;C:\Users\buciu\Anaconda3\Library\bin;C:\Users\buciu\AppData\Local\Programs\Python\Python36-32\Scripts\;C:\Users\buciu\AppData\Local\Programs\Python\Python36-32\;C:\RailsInstaller\Git\cmd;C:\RailsInstaller\Ruby2.3.0\bin;C:\Program Files\nodejs\;C:\Program Files(x86)\nodejs;C:\Users\buciu\AppData\Roaming\npm;C:\Users\me\AppData\Roaming\npm\node_modules\bower\bin;C:\apache-maven-3.5.0\bin;C:\apache-maven-3.5.0;C:\Users\buciu\Desktop;;.
Aug 11, 2017 6:44:44 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-bio-8080"]
Aug 11, 2017 6:44:44 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["ajp-bio-8009"]
Aug 11, 2017 6:44:44 PM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 5454 ms
Aug 11, 2017 6:44:44 PM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Catalina
Aug 11, 2017 6:44:44 PM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/7.0.78
Aug 11, 2017 6:44:48 PM org.apache.catalina.util.SessionIdGeneratorBase createSecureRandom
INFO: Creation of SecureRandom instance for session ID generation using [SHA1PRNG] took [1,130] milliseconds.
Aug 11, 2017 6:44:50 PM org.apache.catalina.loader.WebappClassLoaderBase validateJarFile
INFO: validateJarFile(C:\Users\buciu\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp2\wtpwebapps\Tutoring\WEB-INF\lib\javax.servlet-api-3.1.0.jar) - jar not loaded. See Servlet Spec 3.0, section 10.7.2. Offending class: javax/servlet/Servlet.class
Aug 11, 2017 6:44:58 PM org.apache.catalina.startup.TldConfig execute
INFO: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
Aug 11, 2017 6:44:58 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-bio-8080"]
Aug 11, 2017 6:44:58 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-bio-8009"]
Aug 11, 2017 6:44:58 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 13927 ms
java.lang.NullPointerException

以下是UserDAO类:

public class UserDAO {

    private static final Log LOGGER = LogFactory.getLog(UserDAO.class);

    private static SessionFactory factory;

    public UserDAO(SessionFactory factory) {
        this.factory = factory;
    }

    public static User getUserByUsername(String username) {

        Session session = factory.openSession();
        Transaction tx = null;
        List<User> result=null;
        try{
            tx = session.beginTransaction();
            Query query = session.createQuery("FROM User WHERE username = :username ");
             query.setParameter("username", username);
            List<User> list = (List<User>)query.list();
            result = list;

            tx.commit();

         }catch (HibernateException e) {
             if (tx!=null) tx.rollback();
             e.printStackTrace(); 
          }finally {
             session.close(); 
          }

        return result != null && !result.isEmpty() ? result.get(0) : null;
    }


       public void listUsers( ){
              Session session = factory.openSession();
              Transaction tx = null;
              try{
                  tx = session.beginTransaction();
                 List users = session.createQuery("FROM User").list(); 
                 for (Iterator iterator = 
                                   users.iterator(); iterator.hasNext();){
                    User user = (User) iterator.next(); 
                    System.out.print("First Name: " + user.getUsername()); 
                    System.out.print("Last Name: " + user.getPassword()); 
                    System.out.println("Address: " + user.getAddress()); 
                 }
                 tx.commit();
              }catch (HibernateException e) {
                 if (tx!=null) tx.rollback();
                 e.printStackTrace(); 
              }finally {
                 session.close(); 
              }
           }


       public static User addUser(User user) {
            int userId = -1;
            Session session = factory.openSession();
            Transaction tx = null;
            try {
                tx = session.beginTransaction();
                userId = (Integer) session.save(user);
                user.setId(userId);
                tx.commit();
            } catch (HibernateException e) {
                if (tx != null) {
                    tx.rollback();
                }
                LOGGER.error("", e);
            } finally {
                session.close();
            }
            return user;
        }
       @SuppressWarnings("unchecked")
        public User findUser(int id) {
            Session session = factory.openSession();
            Transaction tx = null;
            List<User> users = null;
            try {
                tx = session.beginTransaction();
                Query query = session.createQuery("FROM User WHERE id = :id");
                query.setParameter("id", id);
                users = query.list();
                tx.commit();
            } catch (HibernateException e) {
                if (tx != null) {
                    tx.rollback();
                }
                LOGGER.error("", e);
            } finally {
                session.close();
            }
            return users != null && !users.isEmpty() ? users.get(0) : null;
        }


       public static boolean authUser(User user) {
            // TODO Auto-generated method stub

            User userDB = UserDAO.getUserByUsername(user.getUsername());
            System.out.println(userDB.getUsername()+" "+userDB.getPassword());
            System.out.println(user.getUsername()+" "+user.getPassword());

            if (userDB != null && userDB.getUsername().equals(user.getUsername()) && userDB.getPassword().equals(user.getPassword())) {
                return true;
            } else {
                return false;
            }
        }
//     public User deleteUser(int id) {
//          Session session = factory.openSession();
//          Transaction tx = null;
//          User user = (User)session.load(User.class, id);
//          try {
//              tx = session.beginTransaction();
//              session.delete(user);
//              tx.commit();
//          } catch (HibernateException e) {
//              if (tx != null) {
//                  tx.rollback();
//              }
//              LOGGER.error("", e);
//          } finally {
//              session.close();
//          }
//          return user;
//      }

       public void deleteUser(int id){
              Session session = factory.openSession();
              Transaction tx = null;
              try{
                 tx = session.beginTransaction();
                 User user = 
                            (User)session.get(User.class, id); 
                 user.setDeleted(1);
                 session.update(user); 
                 tx.commit();
              }catch (HibernateException e) {
                 if (tx!=null) tx.rollback();
                 e.printStackTrace(); 
              }finally {
                 session.close(); 
              }
           }

}

它指示我一个LoginServlet的空白页面,没有打印任何内容,也没有将我重定向到其他东西。

这里有什么想法吗?非常感谢你提前了!

0 个答案:

没有答案