使用Struts框架,实现用户登录功能

      前言:本篇文章是本人这周学习的一个小结,在自我总结的同时,但愿也可以给其余同窗带来一点帮助。本文主要知识是参照书本上的知识点以及网上其余博客文章,在上机操练后的所得,具体源码主要来自http://blog.csdn.net/lovesummerforever/article/details/17348871css

本文主要包括如下三点:MVC设计模式基本概念、Struts工做原理、使用Struts框架实现用户登录具体实例操做。html

 

1、        MVC设计模式java

    在了解MVC模式以前,先要弄清楚什么是设计模式。web

    设计模式是一套被反复使用、多数人知晓的、代码设计经验的总结,模式必须是典型问题的解决方案。设计模式的做用是解决一类问题的成功经验,是为了可重用代码、让代码更容易被他人理解、保证代码的可靠性。数据库

    MVC是一种流行的软件设计模式,这种模式将应用程序实现分为模型(Model)、视图(View)和控制器(Controller)三个部分,主要特色是把显示和数据分离,增长了软件的可重用性。MVC设计模式具体如图一:apache

 

图一:MVC设计模式设计模式

一、  模型(Model)浏览器

    模型表示数据和业务处理,它能够分为数据模型和业务模型,分别表明应用程序的状态和业务逻辑。模型对应的组件是JavaBean或者Java类,只需写一次就能够被多个视图重用,减小了代码的重复性。用一句话来讲:模型就是实现系统中的具体功能模块。app

二、  视图(View)框架

    视图是用户看到的与之交互的界面,负责数据采集和处理用户的请求。视图只是做为一种输出数据并容许用户操纵的方式,对应的组件是JSP或HTML文件。

三、  控制器(Controller)

    控制器是接受用户端的请求,将模型和视图联系在一块儿,实现用户请求的功能。对应的组件是Servlet,起承上启下的枢纽做用。

 

2、        Struts工做原理

    Struts是第一个按照MVC设计模式搭建的Web开发框架,基于Struts开发的应用由三类组件构成:控制器组件、模型组件和视图组件。具体模型如图二:

图二:Struts结构图

一、  控制器组件

    控制器组件包括ActionServlet(核心控制器)和自定义的Action(表明一个用户的操做)。ActionServlet的只要功能是将一个客户端的请求映射到相应的Action,若是该Action配置了指定的ActionForm,那么就在request中抓取数据填充到这个ActionForm,而后调用Action的execute方法。在execute方法执行完成后,ActionServlet将接受包括有下一个资源信息的ActionFoward对象,并将请求转至下一个资源。

二、  视图组件

    视图组件包括JSP页面、ActionForm和Struts标签。视图组件通常由JSP实现,还包括自定义的ActionForm类和Struts标签。自定义的ActionForm类用于封装页面提交的数据,且ActionForm类须要在struts-config.xml中配置,从页面得到输入属性与表单域name属性值一致。

三、  模型组件

   模型组件包括定义和实现业务逻辑的接口和类。模型组件并不禁Struts提供,由普通的接口和JavaBean充当,须要用户本身编码实现。例如,用户登录时获取用户名和密码并与数据库中数值比较的接口等。

 

3、        使用Struts框架实现用户登录具体实例操做

一、 建立Web项目,添加Struts到项目

      首先建立一个Web项目,输入项目名Struts_Login后,选择MyEclipse工具中的MyEclipse菜单中的Project Capabilities->Add Struts Capabilities命令,具体如图三:

图三:添加Struts框架Jar包到项目

    在添加完Struts框架jar包文件后,系统为自动产生struts-config.xml文件,并在web.xml中自动添加ActionServlet。

二、  实现登录功能的ActionForm类和Action类编写

    ActionForm主要用来封装页面输入的表单信息,本例中只设置了用户名和密码两个信息,具体类名是LoginActionForm。代码以下:

package com.liu.struts;

import org.apache.struts.action.ActionForm;

public class LoginActionForm extends ActionForm {
    
     /**
     * 
     */
    private static final long serialVersionUID = 1L;
    //用户名。  
    private String username;  
    //密码。  
    private String password;  
     
    //设置密码。  
    public void setPassword(String password) {  
       this.password = password;  
    }  
    //获得用户名。  
    public String getUsername() {  
       return username;  
    }  
    //设置用户名。  
    public void setUsername(String username) {  
       this.username = username;  
    }  
    //获得密码。  
    public String getPassword() {  
     
       return password;  
    }  

}

    Action类主要是用来实现具体用户操做的功能,本例中LoginAction类继承Action,表示用户的登录操做。具体代码以下:

package com.liu.struts;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

public class LoginAction extends Action{
    
    public ActionForward execute(ActionMapping mapping,ActionForm form,  
                  HttpServletRequest request, HttpServletResponse response)  
                  throws Exception {  
 
 
           LoginActionForm laf = (LoginActionForm)form;  
           String username = laf.getUsername();  
           String password = laf.getPassword();  
             
           UserManager userManager = new UserManager();  
           //传递用户名和密码  
           try  
           {  
                  userManager.login(username, password);  
                  request.setAttribute("username", username);  
                  return mapping.findForward("success");  
           }catch(UserNotFoundException e)  
           {  
                  e.printStackTrace();  
                  request.setAttribute("msg","用户不能找到,用户名称=[" +username +"+]");  
           }catch(PasswordErrorException e)  
           {  
                  e.printStackTrace();  
                  request.setAttribute("msg","密码错误");  
           }  
             
           return mapping.findForward("error");  
    }  
}

三、  处理用户登录的业务逻辑层userManager类的书写

    本例中用户登录成功的用户名和密码均为admin,是直接写在.java文件中的信息,没有与数据库中信息进行验证交互,但弄清楚本例后,本身再去进行数据库中信息验证,具体步骤操做也是大同小异。

    userManager类具体源码以下:

package com.liu.struts;

public class UserManager {
     public void login(String username,String password)  
     {  
            if(!"admin".equals(username))  
            {  
                   throw new UserNotFoundException();  
            }  
              
              
            if(!"admin".equals(password))  
            {  
                   throw new PasswordErrorException();  
            }  
     }  
}

UserNotFoundException具体代码以下:

package com.liu.struts;

public class UserNotFoundException extends RuntimeException {
    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    public UserNotFoundException() {  
    }  
 
    public UserNotFoundException(String message) {  
           super(message);  
    }  
 
    public UserNotFoundException(Throwable cause) {  
           super(cause);  
    }  
 
    public UserNotFoundException(String message,Throwable cause) {  
           super(message, cause);  
    }  
}

    PasswordErrorException具体代码以下:

package com.liu.struts;

public class PasswordErrorException extends RuntimeException {
     /**
     * 
     */
    private static final long serialVersionUID = 1L;

    public PasswordErrorException() {  
     }  
  
     public PasswordErrorException(String message) {  
            super(message);  
     }  
  
     public PasswordErrorException(Throwable cause) {  
            super(cause);  
     }  
  
     public PasswordErrorException(String message,Throwable cause) {  
            super(message, cause);  
     }  
}

      以上即是业务逻辑层处理用户登录的具体代码。

 

四、 配置sturts-config文件

    具体Struts-config代码以下:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.3//EN" "http://struts.apache.org/dtds/struts-config_1_3.dtd">

<struts-config>
  <form-beans>  
       <form-bean name="loginForm" type="com.liu.struts.LoginActionForm"/>  
  </form-beans>
  <global-exceptions />
  <global-forwards />
  <action-mappings>  
       <action path="/login"  
              type="com.liu.struts.LoginAction"  
              name="loginForm"  
              scope="request"  
              >  
              <forward name="success" path="/Login_success.jsp"/>  
              <forward name="error" path="/Login_error.jsp"/>  
       </action>  
    </action-mappings>    
  <message-resources parameter="com.yourcompany.struts.ApplicationResources" />
</struts-config>

    与是相关的Web.xml代码以下(此处用的系统自动导入Struts的jar包文件,因此web.xml不须要配置,不过能够参考看一下):

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="3.0" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
  <display-name />
  <servlet>
    <servlet-name>action</servlet-name>
    <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
    <init-param>
      <param-name>config</param-name>
      <param-value>/WEB-INF/struts-config.xml</param-value>
    </init-param>
    <init-param>
      <param-name>debug</param-name>
      <param-value>3</param-value>
    </init-param>
    <init-param>
      <param-name>detail</param-name>
      <param-value>3</param-value>
    </init-param>
    <load-on-startup>0</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>action</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

六、 编写视图层JSP文件

    index.jsp源码以下(此JSP文件为登录界面):

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.jsp' starting page</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
  </head>
  
  <body>
   <form action="login.do" method="post">  
   用户:<input type="text" name="username"><br>  
   密码:<input type="password" name="password"><br>  
   <input type="submit" value="登陆">  
</form>  
  </body>
</html>

    当用户密码或用户名输入错误时,跳转到Login_error.jsp界面,具体源码以下:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'Login_error.jsp' starting page</title>
    
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->

  </head>
  
  <body>
   <%--  
  <%=request.getAttribute("msg") %>  
  --%>  
    
  ${msg },登录错误!!!  
  </body>
</html>

    当用输入用户名和密码均正确时,跳转到Login_success.jsp界面,具体源码以下:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'Login_success.jsp' starting page</title>
    
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->

  </head>
  
  <body>
   ${username},登陆成功! 
  </body>
</html>

    附:下图四是项目Struts_Login目录结构,以下:

图四:Struts_Login项目目录结构

6、部署、运行项目

     首先开启Tomcat服务,而后给Struts_Login项目配置具体Tomcat,完成这两步后,在浏览器中输入http://localhost:8080/Struts_Login便可获得预期目标。具体步骤截图及运行截图以下:

图五:打开Tomcat服务

图六:给Struts_Login配置Tomcat

 

 

图七:登录界面

 

图八:登录成功界面

 

图九:登录失败界面

    好了,以上就是使用Struts框架,实现用户登录功能的具体步骤,写了两个小时终于把本文写完了~

相关文章
相关标签/搜索