struts2入门
Posted omji0030
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了struts2入门相关的知识,希望对你有一定的参考价值。
环境搭建
1.1 jar
1.2 web.xml
1.3 struts.xml
struts.xml(核心配置文件)
添加依赖:(在pom.xml中)
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-core</artifactId>
<version>2.5.13</version>
</dependency>
开发
Action
不需要指定父类(ActionSupport)
业务方法的定义
public String xxx();//execute
Action是多例模式(注:在spring中的配置中一定要注意)
Action用来接收参数
参数赋值
Action中定义属性,并提供get/set方法
userName, getUserName/setUserName
Defultaction.java
package com.web; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts2.ServletActionContext; import org.apache.struts2.interceptor.ServletRequestAware; import org.apache.struts2.interceptor.ServletResponseAware; import com.opensymphony.xwork2.ModelDriven; /** * 1、动态方法调用 * 2、struts中的传参 * 2.1 set传参 * 2.2 参数名.属性名传参 * 2.3实现modeldriven接口 * 3、struts与tomcat的交互 * 将后台的值传到前台去 * request传值 * * 值栈传值(get方法传值) * @author xyls * */ public class DefultAction implements ModelDriven<User>, ServletRequestAware,ServletResponseAware private HttpServletRequest request; private HttpServletResponse response; private User user1=new User(); private User user2; private String sex; private String uname; public User getUser2() return user2; public void setUser2(User user2) this.user2 = user2; public String getSex() return sex; public void setSex(String sex) this.sex = sex; public String add() System.out.println("。。。"); return null; public String del() System.out.println("user1:"+user1); System.out.println("user2:"+user2); System.out.println("sex:"+sex); HttpServletRequest request=ServletActionContext.getRequest(); this.request.setAttribute("rs", user1); return "success"; public String edit() System.out.println("。。。"); return null; public String list() System.out.println("。。。"); return null; @Override public User getModel() return user1; @Override public void setServletResponse(HttpServletResponse response) this.response=response; @Override public void setServletRequest(HttpServletRequest request) this.request=request;
ModelDriven
返回实体,不能为null,不需要提供get/set方法
ModelDriven返回实体和Action中属性重名,ModelDriven中优先级更高
与J2EE容器交互
非注入
耦合
ServletActionContext
解耦(建立使用解耦模式)
ActionContext
运行结果(控制台):
demo.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!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>Insert title here</title> </head> <body> <h2>struts传参的3种方式</h2> <a href="$pageContext.request.contextPath/sy/defult_del.action?uid=001&&uname=zs">测试model driver</a> <a href="$pageContext.request.contextPath/sy/defult_del.action?sex=nan">测试set传参</a> <a href="$pageContext.request.contextPath/sy/defult_del.action?user2.uid=002&&user2.uname=ls">测试参数名.属性名传参</a> </body> </html>
以上是关于struts2入门的主要内容,如果未能解决你的问题,请参考以下文章