學習struts筆記2——登入示例

本文展示了一个基于Struts框架的项目,包含详细的目录结构,如index.jsp、Welcome.jsp等文件。还给出了多个Java类代码,如LogoffAction、LogonAction等,以及struts-config.xml、web.xml等配置文件内容,体现了Struts框架在登录、登出等功能上的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目錄結構:
SimpleExamples
|_   index.jsp
|_    pages
|       |_    Welcome.jsp
|       |_    logon.jsp
|_    pic
|        |_  
|_    WEB-INF
         |_    classes
         |            |_    ApplicationResources.properties
         |            |_    strutsinactionexamples
         |                        |_    LogonAction.class
         |                        |_    LogonForm.class
         |                        |_    LogoffAction.class
         |_    lib
         |            |_    jdbc2_0-stdext.jar
         |            |_    struts.jar
         |_    struts-bean.tld
         |_    struts-html.tld
         |_    struts-logic.tld
         |_    struts-config.xml
         |_    web.xmlsss

    /*---------------------------ApplicationResources.properties-----------------------------------*/
# -- standard errors --
errors.header=<H3><font color="red">Validation Error</font></H3>You must correct the following error(s) before proceeding:<UL>
errors.footer=</UL><HR>

error.username.required=<li>Username is required</li>
error.password.required=<li>Password is required</li>
error.logon.connect=<li>Connectiong is failure</li>
error.logon.invalid=<li>Username/password combination is invalid</li>

# -- welcome --
welcome.title=Welcome !

 

   /*-------------------Constants.jsp ---------------------*/

package strutsinactionexamples;

public final class Constants {

    /**
     * 當前用戶的用戶名在session中的id
     */
    public static final String USER_KEY = "user";
    /**
     * 除錯信息的值
     */
    public static final int DEBUG = 1;
    /**
     * 正常訊息的值
     */
    public static final int NORMAL = 0;
    /**
     * ActionForward中的正常結果
     */
    public static final String SUCCESS = "success";
    /**
     * 代表ActionForward 中地正常結果的符號
     */
    public static final String LOGON = "logon";

    /**
     * 這個符號代表ActionForward中的登陸行動的符號
     */
    public static String WELCOME = "welcome";
}


    /*-------------------------LogoffAction.java--------------------------*/
 package strutsinactionexamples;

import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForm;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.Action;

public class LogoffAction extends Action {
    public ActionForward perform(ActionMapping actionMapping,
                                 ActionForm actionForm,
                                 HttpServletRequest servletRequest,
                                 HttpServletResponse servletResponse) {
        javax.servlet.http.HttpSession session=servletRequest.getSession();
        LogonForm user=(LogonForm)session.getAttribute(Constants.USER_KEY);
        if(user!=null){
            if(servlet.getDebug()>=Constants.NORMAL){
                StringBuffer message=new StringBuffer("LogoffAcion:user '");
                message.append(user.getUsername());
                message.append("' logged off in session ");
                message.append(session.getId());
                servlet.log(message.toString());
            }        
        }       
        session.removeAttribute(Constants.USER_KEY);
        //session.invalidate();//同時也會摧毀本地話物件
        return (actionMapping.findForward(Constants.SUCCESS));
    }
}


    /*--------------------LogonAction .java----------------*/
package strutsinactionexamples;

import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForm;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionError;
import javax.servlet.http.HttpSession;

public class LogonAction extends Action {
    public LogonAction() {
        try {
            jbInit();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public ActionForward perform(ActionMapping actionMapping,
                                 ActionForm actionForm,
                                 HttpServletRequest servletRequest,
                                 HttpServletResponse servletResponse) {
        LogonForm logonForm = (LogonForm) actionForm;
        String username = logonForm.getUsername();
        String password = logonForm.getPassword();
        boolean validated = false;
        try {
            validated = this.isUserLogon(username, password);
        } catch (Exception e) {
            ActionErrors errors = new ActionErrors();
            errors.add(ActionErrors.GLOBAL_ERROR,
                       new ActionError("error.logon.connect"));
            saveErrors(servletRequest, errors);
            return (new ActionForward(actionMapping.getInput())); //struts-config裡面一定要些input='xx'
        }
        if (!validated) {
            ActionErrors errors = new ActionErrors();
            errors.add(ActionErrors.GLOBAL_ERROR,
                       new ActionError("error.logon.invalid"));
            saveErrors(servletRequest, errors);
            return (new ActionForward(actionMapping.getInput())); //回到輸入頁
        } else {
            HttpSession session = servletRequest.getSession();
            session.setAttribute(Constants.USER_KEY, logonForm);
            //form存入session中表示簽入成功
            if (servlet.getDebug() >= Constants.NORMAL) { //出錯層級大於一定時記錄,ActionServlet.getDebug 取得<init-param><param-name>debug</><param-value>2</></>中得數值
                StringBuffer message = new StringBuffer("LogonAciont:User '");
                message.append(username);
                message.append("' logged on is session ");
                message.append(session.getId());
                servlet.log(message.toString());
            }
            return (actionMapping.findForward(Constants.SUCCESS));
        }
    }

    private boolean isUserLogon(String username, String password) {
        return (username.equals("a") && password.equals("a"));
    }

    private void jbInit() throws Exception {
    }
}



    /*---------------------LogonForm.java---------------------*/
package strutsinactionexamples;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionMapping;
import javax.servlet.http.HttpServletRequest;

public class LogonForm extends ActionForm {
    private String password;
    private String username;
    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getUsername() {
        return username;
    }

    public ActionErrors validate(ActionMapping actionMapping,
                                 HttpServletRequest httpServletRequest) {
        ActionErrors errors=new ActionErrors();
        if((this.username==null)||(this.username.length()<1))
            errors.add("username",new ActionError("error.username.required"));
        if((this.password==null)||(this.password.length()<1))
            errors.add("password",new ActionError("error.password.required"));
        return errors;
    }

    public void reset(ActionMapping actionMapping,
                      HttpServletRequest servletRequest) {
        password = null;
        username = null;
    }
}


    /*------------------web.xml------------------------------*/
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
  <display-name>WebModuleStruts1_0</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>2</param-value>
    </init-param>
    <init-param>
      <param-name>application</param-name>
      <param-value>ApplicationResources</param-value>
    </init-param>
    <load-on-startup>2</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>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
  </welcome-file-list>
  <taglib>
    <taglib-uri>/WEB-INF/struts-bean.tld</taglib-uri>
    <taglib-location>/WEB-INF/struts-bean.tld</taglib-location>
  </taglib>
  <taglib>
    <taglib-uri>/WEB-INF/struts-html.tld</taglib-uri>
    <taglib-location>/WEB-INF/struts-html.tld</taglib-location>
  </taglib>
  <taglib>
    <taglib-uri>/WEB-INF/struts-logic.tld</taglib-uri>
    <taglib-location>/WEB-INF/struts-logic.tld</taglib-location>
  </taglib>
  <taglib>
    <taglib-uri>/WEB-INF/struts-template.tld</taglib-uri>
    <taglib-location>/WEB-INF/struts-template.tld</taglib-location>
  </taglib>
</web-app>



    /*------------------------struts-config.xml------------------------------*/
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.0//EN" "http://jakarta.apache.org/struts/dtds/struts-config_1_0.dtd">
<struts-config>
  <form-beans>
    <form-bean name="logonForm" type="strutsinactionexamples.LogonForm" />
    <form-bean name="registerForm" type="strutsinactionexamples.RegisterForm" />
  </form-beans>
  <global-forwards>
  <forward name="welcome" path="/Welcome.do" />
  <!--這兩個一個作用,下面的可隱藏路徑但還得再寫一個action
   <forward name="logon" path="/pages/logon.jsp" />
   <forward name="logon" path="/Logon.do" />
  -->
    <forward name="logon" path="/Logon.do" />
    <forward name="logoff" path="/logoffAction.do" />
    <forward name="success" path="/Welcome.do" />
  </global-forwards>
  <action-mappings type="org.apache.struts.action.ActionMapping">
  <!--下面兩個一樣作用
    <action path="/Welcome" parameter="/pages/Welcome.jsp"  type="org.apache.struts.action.ActionForward" /> 
 -->    
    <action path="/Welcome" forward="/pages/Welcome.jsp"/>
   
    <!--config for logon and logoff-->
    <action path="/Logon" forward="/pages/logon.jsp"/><!--第一次進入logon時-->
    <action path="/LogonSubmit" name="logonForm" input="/pages/logon.jsp" scope="request" type="strutsinactionexamples.LogonAction" validate="true" />
    <action path="/logoffAction" type="strutsinactionexamples.LogoffAction" />

    <action name="registerForm" path="/register" scope="request" type="strutsinactionexamples.RegisterAction" validate="false">
      <forward name="success" path="/success.jsp" />
      <forward name="failure" path="/failure.jsp" />
    </action>
   
  </action-mappings>
</struts-config>
<!--關於welcom
index.jsp頁面自動加載,轉向到welcom ,Servlet 中得到 從定向到Welcome.do
再由path="/Welcome" 的action接受  ,forward到 真實的頁面xx/xx/Welcome.jsp
-->
<!-- *.do 由action直接接受,其它格式請求 先到global-forwards中找相應的 -->



    /*----------------------index.jsp-----------------------*/
<%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %>

<logic:redirect forward="welcome"/><%--/Welcome.do不可以,<form action='*.do'才可以 --%>

<%--

Redirect default requests to Welcome global ActionForward.
By using a redirect, the user-agent will change address to match the path of our Welcome ActionForward.

--%>



    /*-------------------------Welcome.jsp----------------------------------*/
<%@ page contentType="text/html; charset=Big5" %>
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
<%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %>

<html>
<head>
<title><bean:message key="welcome.title"/></title>
<html:base/>
<!--產生HTML<base>標簽,這樣引用諸如影像的東西時,就會以相對於原本jsp網頁的位置來算起
    否則會以xx.do的等等或虛擬路徑或動態變化路徑來尋找影像
  -->
</head>
<body bgcolor="#ffffff">
<logic:present name="user"><!--logic:present,看有沒有user這個bean,有則顯示下列內容-->
  <h3>Welcome <bean:write name="user" property="username"/>!</h3>
</logic:present>
<logic:notPresent scope="session" name="user"><!--logic:present,看有沒有user這個bean,無則顯示下列內容-->
  <h3>Welcome !</h3>
</logic:notPresent>
<html:errors/>
<ul>
  <li><html:link forward="logon">Sign in</html:link></li>
  <logic:present name="user">
    <li><html:link forward="logoff">Sign out</html:link></li>   
  </logic:present>
</ul>
<img alt="Powered by Struts" src="../pic/struts-power.gif" />
</body>
</html>



/*-----------------------logon.jsp--------------------------*/
<%@ page contentType="text/html; charset=Big5" %>
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<html>
<head>
<title>Sign in, Please!</title>
</head>
<body>
<html:errors/>
<%-- 一樣效果:
<html:form action="/LogonSubmit" focus="username">
<html:form action="LogonSubmit.do" > 
  --%>
<html:form action="/LogonSubmit.do" >

 Username:<html:text property="username"/><br>
 Password:<html:password property="password" redisplay="false"></html:password><br>
 <html:submit /><html:reset value="Reset"/>
</html:form>
</body>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值