Struts2簡單例項開發
阿新 • • 發佈:2018-11-19
##Struts2簡單例項開發
1.下載struts2
2.建立專案,匯入struts2的jar包
3.配置web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name >
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- Welcome file lists -->
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
4.編寫Action類
package com.controller;
import com.opensymphony.xwork2.ActionSupport;
public class FirstAction extends ActionSupport {
//用來接收表單提交的資料,需要get,set方法
private String userName;
private String password;
public String getUserName() {
return userName;
}
public String getPassword() {
return password;
}
public void setUserName(String userName) {
this.userName = userName;
}
public void setPassword(String password) {
this.password = password;
}
//重寫execute方法
@Override
public String execute() throws Exception {
//模擬資料庫查詢,驗證使用者名稱及密碼
if(userName.equals("LeBron")){
if(password.equals("123456")){
return "ok";
}else{
return "fail";
}
}else{
return "fail";
}
}
}
5.建立並配置struts.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="default" extends="struts-default">
<action name="welcome" class="com.controller.FirstAction">
<result name="ok">/welcome.jsp</result>
<result name="fail">/index.jsp</result>
</action>
</package>
</struts>
6.編寫使用者登入介面
<%--
Created by IntelliJ IDEA.
User: yangxuechen
Date: 2018/10/25
Time: 7:59
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
<form action="welcome.action">
使用者名稱:<input type="text" name="userName"><br>
密 碼:<input type="password" name="password"><br>
<input type="submit" value="登陸">
</form>
</body>
</html>
如果登入成功,則返回welcome.jsp,內容如下
<%--
Created by IntelliJ IDEA.
User: yangxuechen
Date: 2018/10/25
Time: 8:35
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>welcome</title>
</head>
<body>
<b>歡迎,登入成功!</b>
</body>
</html>
否則返回index.jsp
7.部署執行
8.獲取原始碼地址https://github.com/yangxuechen/ssh-learning-example