最近刚刚入门struts2,这里做一个简单的struts2实例来跟大家一起学习一下。
本例实现最简单的登陆,仅包含两个页面:login.jsp 用来输入用户名和密码;success.jsp 为登陆成功页面;error.jsp为登陆失败页面。
1、新建web项目“struts2”
2、引入jar包
下载struts2所需jar包 struts-2.3.24-all.zip
解压后将如下最基本的jar包导入到WebRoot/WEB-INF/lib下
3、在WebRoot下建立页面
login.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
</head>
<body>
<form action="login">
username:<input type="text" name="username" /><br>
password:<input type="password" name="password" /><br>
<input type="submit" value="submit" /><br>
</form>
</body>
</html>
success.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
</head>
<body>
恭喜您:${requestScope.username} 登陆成功<br/>
</body>
</html>
error.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
</head>
<body>
登陆失败
</body>
</html>
3、配置web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<display-name></display-name>
<welcome-file-list>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list>
<!-- 此Filter目的是设置所有的请求都由Struts2来处理 -->
<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><!-- 所有请求都由Struts2来处理 -->
</filter-mapping>
</web-app>
4、建立action
package com.danny.user.action;
public class LoginAction {
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;
}
public String execute() {
if("admin".equals(username) && "admin".equals(password))
{
return "success";
}else{
return "error";
}
}
}
5、配置struts.xml
在src目录下建立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="struts2" extends="struts-default">
<!-- extends是继承的意思,struts-default位于struts2-core-2.3.24.jar.struts-default.xml -->
<action name="login" class="com.danny.user.action.LoginAction">
<result name="success">/success.jsp</result>
<result name="error">/error.jsp</result>
</action>
</package>
</struts>
至此,部署项目,访问localhost:8080/struts2,进入登陆页面:
登陆成功时,跳转到成功页面:
用户名、密码错误时,跳转到登陆失败页面:
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-11-05 12:32:19