struts2 注解实现零配置实例
程序员文章站
2022-04-06 22:54:34
...
1新建一个web项目,添加struts2相关的包,在web.xml中配置struts2
2. AnnotationAction.java
3 login.jsp
4. 登陆即可跳转到index.jsp
<!-- struts2的Filter 分发器 --> <filter> <filter-name>struts2</filter-name> <filter-class> org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter </filter-class> <!--零配置需在filter中指定Action包的位置 --> <init-param> <param-name>actionPackages</param-name> <!--零配置Action包的位置 --> <param-value>com.test.action.AnnotationAction</param-value> </init-param> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>*.action</url-pattern> </filter-mapping> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>*.jsp</url-pattern> </filter-mapping>
2. AnnotationAction.java
package com.test.action; import com.opensymphony.xwork2.ActionSupport; import org.apache.struts2.convention.annotation.Namespace; import org.apache.struts2.convention.annotation.Action; import org.apache.struts2.convention.annotation.Results; import org.apache.struts2.convention.annotation.Result; import org.apache.struts2.dispatcher.ServletRedirectResult; //命名空间 @Namespace(value="/test") //结果集 @Results({ //AnnotationAction传出参数"success"时,页面会跳转到index.jsp @Result(name="success",location="/index.jsp"), @Result(name="login",location="/login.jsp") }) //@注解action为annotationAction,在jsp页面可以使用;若无此注解, //jsp页面中可用action="annotation!add.action",即将Action去掉,首字母小写 @Action(value="annotationAction") public class AnnotationAction extends ActionSupport{ public String add(){ return "success"; } public String login(){ return "login"; } }
3 login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>用户登录</title> </head> <body> <s:form name="form_login" action="annotationAction!add.action" method="post" namespace="/test"> <table> <tr> <td>用户名:</td> <td><s:textfield name="userName" /></td> </tr> <tr> <td>密 码:</td> <td><s:password name="userPassword"/></td> </tr> <tr> <td> </td> <td> <s:submit value="登陆"/> <s:reset value="取消"/> </td> </tr> </table> </s:form> </body> </html>
4. 登陆即可跳转到index.jsp