在struts 1.3中如何从数据库中检索数据并使用DAO显示它

时间:2021-08-16 01:38:11

*M new to struts. I am making simple login page that display username and password by retrieving it from database. I m using DAO. I have LoginDAO.java, LoginAction.java and Displaydata.jsp pages. *

* M struts新手。我正在制作简单的登录页面,通过从数据库中检索来显示用户名和密码。我正在使用DAO。我有LoginDAO.java,LoginAction.java和Displaydata.jsp页面。 *

LoginDAO.java

LoginDAO.java

 public boolean login(String user,String pass) throws SQLException
     {
         Connection con = getConnection();

         Statement st;
        try {
            st = con.createStatement();



                  st.executeQuery("select * from login where Username='" + user + "' and Password='" + pass + "'");


                return true;
            } catch (SQLException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

         return false;

     } 

LoginAction.java

LoginAction.java

public class LoginAction extends Action

{

    public ActionForward execute(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {



    DynaValidatorForm rf= (DynaValidatorForm) form;

 String username = rf.get("username").toString();
 String password = rf.get("password").toString();
 HttpSession session=request.getSession();
 session.setAttribute("user", username);

 Login dao= new Login();

 if(dao.login(username,password))
 {
      System.out.println("GOT");
        return mapping.findForward("success");}
    else
        {System.out.println("NOT");
    return mapping.findForward("failure");
        }
}
}

and also what do i write in Dislpaydata.jsp to display username and password in it dont want any java code in it. Thankyou

还有我在Dislpaydata.jsp中写什么来显示用户名和密码,其中不需要任何java代码。谢谢

2 个解决方案

#1


2  

Right. Some time ago I built an application with Struts 1.x and MySql with login.

对。前段时间我用Struts 1.x和MySql构建了一个带登录的应用程序。

LoginAction

public ActionForward login( ... ) throws Exception {
    String forward;
    final String mail = PropertyUtils.getProperty(form, "mail");
    final String password = PropertyUtils.getProperty(form, "password");
    if (LoginService.getInstance().validate(mail, password)) {
        // Do something e.g. put name of user in session
        forward = SUCCESS;
    } else {
        forward = ERROR;
    }
    return mapping.findForward(forward);
}

LoginService

public boolean validate(final String mail, final String password) 
                                                        throws ServiceException {
    try {
        final boolean valid;

        // Validate null and empty

        // Validate with DB
        final UserDAO dao = new UserDAO();
        final User user = dao.findByPk(mail);
        if (user == null) {
            valid = false;
        } else {
            if (password.equals(user.getPassword())) {
                valid = true;
            } else {
                valid = false;
            }
        }
        return valid;
    } catch (DAOException e) {
        throw new ServiceException("Error validating user and password.", e);
    }
}

UserDAO

private static final String FIND_BY_PK_SQL 
                 = "SELECT mail, name, password, admin FROM user WHERE mail = ?";

public User findByPk(final String mail) throws DAOException {
    Connection conn = null;
    PreparedStatement ps = null;
    ResultSet rs = null;
    try {
        conn = getConnection();
        ps = conn.prepareStatement(FIND_BY_PK_SQL);
        ps.setString(1, mail); // PK, NOT NULL
        rs = ps.executeQuery();
        if (rs.next()) {
            return fill(rs);
        }
        return null;
    } catch (final SQLException e) {
        throw new DAOException(e);
    } finally {
        // Close DB resources
    }
}

private User fill(final ResultSet rs) throws SQLException {
    final User user = new User();
    user.setMail(rs.getString("mail"));
    user.setName(rs.getString("name"));
    user.setPassword(rs.getString("password"));
    user.setAdmin(rs.getBoolean("admin"));
    return user;
}

In my case I have a table user with mail as a primary key. There are various forms.

在我的情况下,我有一个表用户将邮件作为主键。有各种形式。

More examples:

更多例子:


e.g. For show the name of variable user in session scope from the database:

例如要从数据库中显示会话范围中的变量用户的名称:

LoginAction

if (LoginService.getInstance().validate(mail, password)) {
    final HttpSession session = request.getSession();
    final User user = UserService.getInstance().getUser(mail);
    session.setAttribute("user", user);
    forward = SUCCESS;
}

home.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>

Welcome,
<bean:write scope="session" name="user" property="name" filter="false" />

#2


0  

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
<title>Login Page</title>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript"
	src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.1/jquery.validate.min.js"></script>
</head>
<body bgcolor="#2EFEF7">
	<form action="action" method="post" id="formDemo" name="MyForm">

		<div id="header">
			<h2 style="color: red;">Training</h2>
		</div>
		<hr>
		<h3>Login</h3>
		<div id="center" style="padding-top: 50px; padding-bottom: 220px;">
			<table align="center">

				<tr>
					<th colspan="2"><h1 style="color: BLUE;">LOGIN</h1></th>
				</tr>

				<tr>
					<th colspan="2"><h5 id="error" style="color: red;"></h5></th>
				</tr>

				<tr>
					<td>UserID:</td>
					<td><input type="text" size="40" name="UserId" maxlength="8"></td>
				</tr>

				<tr>
					<td>Password:</td>
					<td><input type="text" size="40" name="Password" maxlength="8"></td>
				</tr>

				<tr>
					<td colspan="2" align="center"><input type="submit"
						value="Login"> <input type="button" id="reset"
						value="Clear"></td>
				</tr>

			</table>
		</div>
		<hr>

		<div id="footer">
			<label>Copy right@ 2000-2008 FUJINET, All Rights Reserved.</label>

		</div>
	</form>

	<script type="text/javascript">
	<!--
		// Form validation code will come here.

		function validate() {

			if (document.MyForm.UserId.value === ""
					|| document.MyForm.UserId.value === null) {
				document.getElementById("error").innerHTML = "Please insert userId";

				return false;
			}

			if (document.MyForm.Password.value === ""
					|| document.MyForm.Password.value === null) {
				document.getElementById("error").innerHTML = "Please insert password";

				return false;

			}
			return (true);
		}
		$("#reset").click(function(event) {
			document.MyForm.UserId.value = "";
			document.MyForm.Password.value = "";
			document.getElementById("error").innerHTML = "";
		});
		$("#formDemo").submit(function(event){
			return validate();
		});
	</script>
</body>
</html>

#1


2  

Right. Some time ago I built an application with Struts 1.x and MySql with login.

对。前段时间我用Struts 1.x和MySql构建了一个带登录的应用程序。

LoginAction

public ActionForward login( ... ) throws Exception {
    String forward;
    final String mail = PropertyUtils.getProperty(form, "mail");
    final String password = PropertyUtils.getProperty(form, "password");
    if (LoginService.getInstance().validate(mail, password)) {
        // Do something e.g. put name of user in session
        forward = SUCCESS;
    } else {
        forward = ERROR;
    }
    return mapping.findForward(forward);
}

LoginService

public boolean validate(final String mail, final String password) 
                                                        throws ServiceException {
    try {
        final boolean valid;

        // Validate null and empty

        // Validate with DB
        final UserDAO dao = new UserDAO();
        final User user = dao.findByPk(mail);
        if (user == null) {
            valid = false;
        } else {
            if (password.equals(user.getPassword())) {
                valid = true;
            } else {
                valid = false;
            }
        }
        return valid;
    } catch (DAOException e) {
        throw new ServiceException("Error validating user and password.", e);
    }
}

UserDAO

private static final String FIND_BY_PK_SQL 
                 = "SELECT mail, name, password, admin FROM user WHERE mail = ?";

public User findByPk(final String mail) throws DAOException {
    Connection conn = null;
    PreparedStatement ps = null;
    ResultSet rs = null;
    try {
        conn = getConnection();
        ps = conn.prepareStatement(FIND_BY_PK_SQL);
        ps.setString(1, mail); // PK, NOT NULL
        rs = ps.executeQuery();
        if (rs.next()) {
            return fill(rs);
        }
        return null;
    } catch (final SQLException e) {
        throw new DAOException(e);
    } finally {
        // Close DB resources
    }
}

private User fill(final ResultSet rs) throws SQLException {
    final User user = new User();
    user.setMail(rs.getString("mail"));
    user.setName(rs.getString("name"));
    user.setPassword(rs.getString("password"));
    user.setAdmin(rs.getBoolean("admin"));
    return user;
}

In my case I have a table user with mail as a primary key. There are various forms.

在我的情况下,我有一个表用户将邮件作为主键。有各种形式。

More examples:

更多例子:


e.g. For show the name of variable user in session scope from the database:

例如要从数据库中显示会话范围中的变量用户的名称:

LoginAction

if (LoginService.getInstance().validate(mail, password)) {
    final HttpSession session = request.getSession();
    final User user = UserService.getInstance().getUser(mail);
    session.setAttribute("user", user);
    forward = SUCCESS;
}

home.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>

Welcome,
<bean:write scope="session" name="user" property="name" filter="false" />

#2


0  

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
<title>Login Page</title>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript"
	src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.1/jquery.validate.min.js"></script>
</head>
<body bgcolor="#2EFEF7">
	<form action="action" method="post" id="formDemo" name="MyForm">

		<div id="header">
			<h2 style="color: red;">Training</h2>
		</div>
		<hr>
		<h3>Login</h3>
		<div id="center" style="padding-top: 50px; padding-bottom: 220px;">
			<table align="center">

				<tr>
					<th colspan="2"><h1 style="color: BLUE;">LOGIN</h1></th>
				</tr>

				<tr>
					<th colspan="2"><h5 id="error" style="color: red;"></h5></th>
				</tr>

				<tr>
					<td>UserID:</td>
					<td><input type="text" size="40" name="UserId" maxlength="8"></td>
				</tr>

				<tr>
					<td>Password:</td>
					<td><input type="text" size="40" name="Password" maxlength="8"></td>
				</tr>

				<tr>
					<td colspan="2" align="center"><input type="submit"
						value="Login"> <input type="button" id="reset"
						value="Clear"></td>
				</tr>

			</table>
		</div>
		<hr>

		<div id="footer">
			<label>Copy right@ 2000-2008 FUJINET, All Rights Reserved.</label>

		</div>
	</form>

	<script type="text/javascript">
	<!--
		// Form validation code will come here.

		function validate() {

			if (document.MyForm.UserId.value === ""
					|| document.MyForm.UserId.value === null) {
				document.getElementById("error").innerHTML = "Please insert userId";

				return false;
			}

			if (document.MyForm.Password.value === ""
					|| document.MyForm.Password.value === null) {
				document.getElementById("error").innerHTML = "Please insert password";

				return false;

			}
			return (true);
		}
		$("#reset").click(function(event) {
			document.MyForm.UserId.value = "";
			document.MyForm.Password.value = "";
			document.getElementById("error").innerHTML = "";
		});
		$("#formDemo").submit(function(event){
			return validate();
		});
	</script>
</body>
</html>