Struts2+mysql登录验证实例

文件结构如下:
Struts2+mysql登录验证实例_第1张图片

  • controller为控制层:jsp传过来的值action负责处理(execute方法)并返回字符串实现页面跳转。
  • business为业务层:被action调用实现业务逻辑。
  • dao为数据访问层,主要负责数据的CUID操作。

接下来开始从JSP+struts+mysql实现登录操作。

  • 建立login.jsp:
<%@ page language="java" pageEncoding="UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>请登录</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

</head>

<body>
   <h1>
    请输入
   </h1>
   <s:form action = "login" method = "post" >
   <s:textfield key = "username"></s:textfield>
   <s:password key = "password"></s:password>
   <s:submit value = "登录"></s:submit>
   </s:form>
</body>
</html>
  • 建立main.jsp为登录成功跳转的页面:
<%@ page language="java" pageEncoding="UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>主页面</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

</head>

<body>
   <h1>
   <s:property value = "username"/>你登录了主页面
   </h1>
</body>
</html>
  • error.jsp为没能登陆跳转的页面:
<%@ page language="java" pageEncoding="UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>错误</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

</head>

<body>
   <h1>
   你没能登录,这是错误页面。
   </h1>
</body>
</html>

页面已经创建好了,接下来action处理页面传来的数据,创建LoginAction:

package controller;

import java.util.ArrayList;

import business.LoginHandler;

import com.opensymphony.xwork2.ActionSupport;

/** @author:micro_hz 2015年8月12日 */

public class LoginAction extends ActionSupport{
    String username;
    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;
    }
    @Override
    public String execute() throws Exception {
        // TODO Auto-generated method stub
        ArrayList<String> userList = new ArrayList<String>();
        userList.add(username);
        userList.add(password);
        LoginHandler login = new LoginHandler();
        boolean mark = login.checkLogin(userList);
        if(mark) return SUCCESS;
        else return ERROR;
    }
}
  • 其中调用业务逻辑LoginHandler完成用户的验证:
package business;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

import dao.Dao;

/** @author:micro_hz 2015年8月12日 */
public class LoginHandler {
    public boolean checkLogin(ArrayList list)
    {
        String user = (String)list.get(0);
        String password = (String)list.get(1);
        boolean rt = false;

        try
        {
            Dao dao = new Dao();
            Connection conn = dao.getConnection();
            PreparedStatement p = conn.prepareStatement("select * from test");
            ResultSet rs = p.executeQuery();
            HashMap<String,String> hm = new HashMap();
            while(rs.next())
            {
                hm.put(rs.getString("username"), rs.getString("password"));
            }
            dao.close(rs, p, conn);
            Set<String> set = hm.keySet();
            Iterator it = set.iterator();
            while(it.hasNext())
            {
                if(it.next().equals(user))
                {

                    if(password.equals(hm.get(user)))
                    {
                        rt = true;
                        break;
                    }
                }
            }
        }
        catch(SQLException e)
        {
            System.out.println("数据库出问题");
        }
        return rt;
    }
}

然后是struts.xml配置LoginAction与返回后页面跳转:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
    <package name="struts" extends="struts-default">
        <action name="login" class="controller.LoginAction">
            <result name="success">/main.jsp</result>
            <result name="error">/error.jsp</result>
        </action>
    </package>
</struts>
  • 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" version="2.5">
    <filter>
    <filter-name>struts2</filter-name>
    <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
    </filter>
    <filter-mapping>
    <filter-name>struts2</filter-name>
    <url-pattern>/*</url-pattern>
    </filter-mapping>
    <welcome-file-list>
    <welcome-file>login.jsp</welcome-file>
    </welcome-file-list>
</web-app>
  • 数据访问层:
package dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.swing.text.html.HTMLDocument.HTMLReader.PreAction;

/** @author:micro_hz 2015年8月12日 */
public class Dao {
    public Connection getConnection()
    {
        String url = "jdbc:mysql://localhost:3306/micro";
        String username = "root";
        String password = "root";
        Connection conn = null;
        try
        {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(url, username, password);
        }
        catch(ClassNotFoundException e)
        {
            System.out.println("驱动加载出错");
        }
        catch(SQLException e)
        {
            System.out.println("数据库连接出错");
        }
        return conn;

    }
    public void close(ResultSet rs,PreparedStatement p,Connection conn)
    {
        try
        {
            rs.close();
            p.close();
            conn.close();
        }
        catch(SQLException e)
        {
            System.out.println("数据库关闭出错");
        }
    }
}
  • 建立的micro数据库,表为test,结构如下:
    Struts2+mysql登录验证实例_第2张图片

  • 需要的jar包:
    Struts2+mysql登录验证实例_第3张图片
    PS:之前一直报告Dispatcher not inistailled,后来将jar包删除(除mysql-java-connector.jar外)重新导入了\struts-2.3.24\apps下struts-blank里面示例的jar包成功解决问题。
    jsp中使用struts的taglib配置

<%@ taglib prefix="s" uri="/struts-tags" %>

顺序不能颠倒,否则无效。

你可能感兴趣的:(Struts2+mysql登录验证实例)