1. 程式人生 > >Struts2入門案例,自動裝配

Struts2入門案例,自動裝配

入門案例:

HelloWorldAction

public class HelloWorldAction implements Action,ModelDriven<UserInfo> {
    private UserInfo userInfo=new UserInfo();
    public String execute() throws Exception {
        if ("admin".equals(userInfo.getUsername())&&"admin".equals(userInfo.getPassword())){
            return 
SUCCESS; }else { return INPUT; } } public UserInfo getUserInfo() { return userInfo; } public void setUserInfo(UserInfo userInfo) { this.userInfo = userInfo; } public UserInfo getModel() { return userInfo; } }


userinfo

public class UserInfo {
    private String username;
    private 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; } }


web.xml

<!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>Archetype Created Web Application</display-name>
  <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>
</web-app>


struts.xml

<?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="default" namespace="/" extends="struts-default">
        <action name="helloWorld" class="cn.happy.action.HelloWorldAction">
            <result name="success">success.jsp</result>
            <result name="input">1.jsp</result>
        </action>
    </package>
</struts>


1.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<s:form action="helloWorld" method="post">
    請輸入使用者名稱:
    <s:textfield name="username"></s:textfield>
    <s:textfield name="password"></s:textfield>
    <s:submit value="登入"></s:submit>
</s:form>
</body>
</html>


執行結果



成功:



失敗: