struts2实战(1):登录验证和退出

来源:互联网 发布:中文安卓编程开创者 编辑:程序博客网 时间:2024/06/06 18:44

本教程是基于本人的毕业设计,拿出来分享一下,比较简单,上手快。

1、对应的jar包,放在lib文件夹中(蓝色是必须的)

这里写图片描述


**

2、对应的数据库的user表

**

DROP TABLE IF EXISTS `user`;CREATE TABLE `user` (  `userId` varchar(20) COLLATE utf8_bin NOT NULL,  `password` varchar(20) COLLATE utf8_bin NOT NULL,  `name` varchar(20) COLLATE utf8_bin DEFAULT NULL,  PRIMARY KEY (`userId`)) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;-- ------------------------------ Records of user-- ----------------------------INSERT INTO `user` VALUES ('admin', '123456', 'Billy');INSERT INTO `user` VALUES ('wang', '123456', 'Wang');

3、对应的方法

数据库方面使用的是MySQL
DB

package jwgl.util;import java.sql.*;import java.sql.Connection;  import java.sql.DriverManager;  import java.sql.SQLException;  /**  * @author Billy  */  public class DB {      // 连接实例      private static Connection conn = null;      //连接地址      String url = "jdbc:mysql://localhost:3306/jwgl?useUnicode=true&characterEncoding=UTF-8";      // MySQL用户名      String user = "root";      // MySQL密码      String password = "123456";      public DB() throws Exception {          Class.forName("com.mysql.jdbc.Driver");          conn=DriverManager.getConnection(url,user,password);      }      //获得连接对象      public static Connection getConnection(){          return conn;      }      //关闭连接      public static void CloseCon() throws SQLException{          conn.close();      }  }  

4、实现一个user的对象

包括userID,password 为了减少代码,直接封装在登录的方法中,并实现用户登录后分配一个session,退出系统后实现清除当前的session,防止别人登录。

loginAction

package jwgl.action;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.util.Map;import jwgl.util.DB;import com.opensymphony.xwork2.ActionContext;import com.opensymphony.xwork2.ActionSupport;public class LoginAction extends ActionSupport {   private String userId;   private String password;   private String name;   private String type;   public String execute() {      String ret = ERROR;      try {          new DB();          String sql = "SELECT name FROM user WHERE";          sql+=" userId = ? AND password = ?";          PreparedStatement ps = DB.getConnection().prepareStatement(sql);          ps.setString(1, userId);          ps.setString(2, password);          ResultSet rs = ps.executeQuery();          while (rs.next()) {             name = rs.getString(1);             //获取当前选中的用户类型radio             if(type.equals("admin")){                 Map<String, Object> attibutes = ActionContext.getContext().getSession();                 //记录用户登录信息                  attibutes.put("UserId", userId);                  attibutes.put("password", password);                 attibutes.put("name",name);                 ret = SUCCESS;                 System.out.println("管理员"+userId+"登录成功");                 }else{                 System.out.println("当前选择的用户类型"+type+"与目标类型不匹配");                 ret = ERROR;             }            }       } catch (Exception e) {          ret = ERROR;          System.out.println("管理员"+userId+"登录失败");       } finally {          if (DB.getConnection() != null) {             try {                DB.getConnection();             } catch (Exception e) {             }          }       }        System.out.println(userId+"当前返回的结果:"+ret);       return ret;   }        /**         * @return the userId         */        public String getUserId() {            return userId;        }        /**         * @param userId the userId to set         */        public void setUserId(String userId) {            this.userId = userId;        }        /**         * @return the password         */        public String getPassword() {            return password;        }        /**         * @param password the password to set         */        public void setPassword(String password) {            this.password = password;        }        /**         * @return the name         */        public String getName() {            return name;        }        /**         * @param name the name to set         */        public void setName(String name) {            this.name = name;        }        /**         * @return the type         */        public String getType() {            return type;        }        /**         * @param type the type to set         */        public void setType(String type) {            this.type = type;        }}

logoutAction

package jwgl.action;//退出系统import java.util.Map;import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionSupport;import jwgl.action.LoginAction;public class LogoutAction extends ActionSupport {    private static final long serialVersionUID = 1L;@SuppressWarnings("unchecked")     @Override     public String execute() throws Exception {         Map<String, Object> attibutes = ActionContext.getContext().getSession();         //记得退出的时候清除session,否则下次登录是当前的值        attibutes.remove("userId");         System.out.println("刚刚有人退出系统了");        attibutes.remove("name");         return SUCCESS;     } }

5、拦截器

避免未登录的用户通过+login.action登录页面,非法操作。
CheckLoginInterceptor

package jwgl.util;//拦截器,拦截未登录的用户import java.util.Map;import jwgl.action.LoginAction;import com.opensymphony.xwork2.ActionContext;import com.opensymphony.xwork2.ActionInvocation;import com.opensymphony.xwork2.interceptor.AbstractInterceptor;public class CheckLoginInterceptor extends AbstractInterceptor {    @Override    public String intercept(ActionInvocation invocation) throws Exception {        //获取ActionContext        ActionContext ac = invocation.getInvocationContext();        //获取session        Map<String, Object> session = ac.getSession();        //获取session中的用户信息        String name = (String)session.get("name");        //判断用户信息是否正确        if(name != null ) {            return invocation.invoke();        }else {            return "relogin";        }     }}

6、struts2核心文件设置

struts.xml

<!-- 配置 Struts 可以受理的请求的扩展名 -->    <constant name="struts.action.extension" value="action,do,"></constant>    <!-- 拦截器包 -->    <package name="lanjie" extends="struts-default" namespace="/">        <!--此处加入拦截器 防止未登录的用户尝试登录页面 -->        <interceptors>          <interceptor name="authority" class="jwgl.util.CheckLoginInterceptor"/>          <interceptor-stack name="myStack">              <interceptor-ref name="defaultStack"/>              <interceptor-ref name="authority"/>              </interceptor-stack>          </interceptors>          <default-interceptor-ref name="myStack"></default-interceptor-ref>          <!-- 全局的跳转结果 和下面的action中是对应的 -->           <global-results>              <result name="relogin">/WEB-INF/login.jsp</result>          </global-results>        <!--此处是跳转的映射,每一个action映射到特定的jsp页面-->        <action name="new">            <result>/WEB-INF/login.jsp</result>        </action></package>  <!-- 此处登录验证 --><package name="LoginAction"  extends="struts-default" namespace="/">         <action name="login" class="jwgl.action.LoginAction" method="execute" >            <result name="success">/WEB-INF/html/demo.jsp</result>            <result name="error">/WEB-INF/html/error.jsp</result>        </action>        <!-- 此处获取session并退出系统 -->        <action name="logout" class="jwgl.action.LogoutAction" method="execute">            <result>/WEB-INF/login.jsp</result>        </action>    </package>  

**

7、最后一步,配置web.xml

**
web.xml

<!-- 配置 Struts2 的 Filter,struts2版本为2.3.15.1-->    <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>

截图:
登录窗口

登录成功

参考资料:
Struts2 MySQL数据库访问
http://www.yiibai.com/struts_2/struts_database_access.html

0 0
原创粉丝点击