我是spring mvc的新手,使用Netbeans 8尝试了http://krazytech.com/programs/a-login-application-in-java-using-model-view-controllermvc-design-pattern的教程。
编码部分是,
login.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login</title>
</head>
<body>
<form name="form1" action="LoginServlet" method="post">
<table align="center">
<tr>
<td>Username</td>
<td><input type="text" name="username" /></td>
</tr>
<tr>
<td>Password</td>
<td><input type="text" name="password" /></td>
</tr>
<tr>
//Error message display in case of wrong credentials. This reply will come from LoginServlet.java
<td>< %=(request.getAttribute("errMessage") == null) ? "" : request.getAttribute("errMessage")%></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Login"></input><input type="reset" value="Reset"></input></td>
</tr>
</table>
</form>
</body>
</html>
LoginServlet.java
package com.mvc.controller;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.mvc.bean.LoginBean;
import com.mvc.dao.LoginDao;
public class LoginServlet extends HttpServlet {
public LoginServlet() {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//Here username and password are the names which I have given in the input box in Login.jsp page. Here I am retrieving the values entered by the user and keeping in instance variables for further use.
String userName = request.getParameter("username");
String password = request.getParameter("password");
LoginBean loginBean = new LoginBean(); //creating object for LoginBean class, which is a normal java class, contains just setters and getters. Bean classes are efficiently used in java to access user information wherever required in the application.
loginBean.setUserName(userName); //setting the username and password through the loginBean object then only you can get it in future.
loginBean.setPassword(password);
LoginDao loginDao = new LoginDao(); //creating object for LoginDao. This class contains main logic of the application.
String userValidate = loginDao.authenticateUser(loginBean); //Calling authenticateUser function
if(userValidate.equals("SUCCESS")) //If function returns success string then user will be rooted to Home page
{
request.setAttribute("userName", userName); //with setAttribute() you can define a "key" and value pair so that you can get it in future using getAttribute("key")
request.getRequestDispatcher("/Home.jsp").forward(request, response);//RequestDispatcher is used to send the control to the invoked page.
}
else
{
request.setAttribute("errMessage", userValidate); //If authenticateUser() function returnsother than SUCCESS string it will be sent to Login page again. Here the error message returned from function has been stored in a errMessage key.
request.getRequestDispatcher("/Login.jsp").forward(request, response);//forwarding the request
}
}
}
LoginDao.java
package com.mvc.dao;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import com.mvc.bean.LoginBean;
import com.mvc.util.DBConnection;
public class LoginDao {
public String authenticateUser(LoginBean loginBean)
{
String userName = loginBean.getUserName(); //Keeping user entered values in temporary variables.
String password = loginBean.getPassword();
Connection con = null;
Statement statement = null;
ResultSet resultSet = null;
String userNameDB = "";
String passwordDB = "";
try
{
con = DBConnection.createConnection(); //establishing connection
statement = con.createStatement(); //Statement is used to write queries. Read more about it.
resultSet = statement.executeQuery("select userName,password from users"); //Here table name is users and userName,password are columns. fetching all the records and storing in a resultSet.
while(resultSet.next()) // Until next row is present otherwise it return false
{
userNameDB = resultSet.getString("userName"); //fetch the values present in database
passwordDB = resultSet.getString("password");
if(userName.equals(userNameDB) && password.equals(passwordDB))
{
return "SUCCESS"; ////If the user entered values are already present in database, which means user has already registered so I will return SUCCESS message.
}
}
catch(SQLException e)
{
e.printStackTrace();
}
return "Invalid user credentials"; // Just returning appropriate message otherwise
}
}
LoginBean.java
package com.mvc.bean;
public class LoginBean
{
private String userName;
private String password;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
DBConncection.java:
package com.mvc.util;
import java.sql.Connection;
import java.sql.DriverManager;
public class DBConnection {
public static Connection createConnection()
{
Connection con = null;
String url = "jdbc:mysql://localhost:3306/ravi"; //for SQL and oracle or any other db server this url differs. where ravi is the database name and 3306 is the port where mysql is running
String username = "root"; //username of database user
String password = "root"; //password
try
{
try
{
Class.forName("com.mysql.jdbc.Driver");// differs from DB server to server
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
con = DriverManager.getConnection(url, username, password);
}
catch (Exception e)
{
e.printStackTrace();
}
return con;
}
}
的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_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>Mvc</display-name>
<welcome-file-list>
<welcome-file>Login.jsp</welcome-file>
</welcome-file-list>
<servlet>
<description></description>
<display-name>LoginServlet</display-name>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>com.mvc.controller.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
</web-app>
回到Home.jsp
<html>
<head>
<title>Home Page</title>
</head>
<body>
<center>
<h2>Home Page</h2>
</center>
Welcome <%=request.getAttribute("userName") %>
</body>
</html>
在Tomcat中我获取以下信息和警告,
20-Sep-2016 03:35:05.642 SEVERE [http-nio-8084-exec-7] org.apache.catalina.loader.WebappClassLoader.clearReferencesThreads The web application [/log] appears to have started a thread named [Abandoned connection cleanup thread] but has failed to stop it. This is very likely to create a memory leak.
20-Sep-2016 03:35:06.548 INFO [http-nio-8084-exec-7] org.apache.catalina.startup.HostConfig.undeploy Undeploying context [/log]
20-Sep-2016 03:35:13.892 INFO [http-nio-8084-exec-5] org.apache.catalina.startup.HostConfig.deployDescriptor Deploying configuration descriptor C:\Users\Tamil Taf\AppData\Roaming\NetBeans\8.0\apache-tomcat-8.0.3.0_base\conf\Catalina\localhost\log.xml
20-Sep-2016 03:35:13.908 WARNING [http-nio-8084-exec-5] org.apache.catalina.startup.SetContextPropertiesRule.begin [SetContextPropertiesRule]{Context} Setting property 'antiJARLocking' to 'true' did not find a matching property.
20-Sep-2016 03:35:17.361 INFO [http-nio-8084-exec-12] org.apache.catalina.util.LifecycleBase.start The start() method was called on component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/log]] after start() had already been called. The second call will be ignored.
和
20-Sep-2016 03:06:39.401 INFO [localhost-startStop-2] org.apache.catalina.core.ApplicationContext.log Destroying Spring FrameworkServlet 'spring'
20-Sep-2016 03:07:38.565 INFO [localhost-startStop-1] org.apache.catalina.core.ApplicationContext.log No Spring WebApplicationInitializer types detected on classpath
20-Sep-2016 03:07:43.565 INFO [localhost-startStop-1] org.apache.catalina.core.ApplicationContext.log No Spring WebApplicationInitializer types detected on classpath
20-Sep-2016 03:07:43.909 INFO [localhost-startStop-1] org.apache.catalina.core.ApplicationContext.log Initializing Spring FrameworkServlet 'spring'
20-Sep-2016 03:35:17.283 INFO [http-nio-8084-exec-5] org.apache.catalina.core.ApplicationContext.log No Spring WebApplicationInitializer types detected on classpath
localhost显示404错误
帮助我在这里玩了超过5个小时。 提前谢谢。