Struts2核心流程图

1. Struts2 和 Struts1 对比

struts1:基于Servlet(ActionServlet),actionForm众多(类的爆炸),action单例(数据安全[线程安全]问题).

  将所有任务的解决都集于一身.(不容易扩展和定制)

  action位于控制层. extends Action{...}

  action更struts1的action和原生servlet api(HttpServletRequest,HttpServlerResponse)绑定在一起,

  因此不容易测试,需要部署到web容器中进行测试.

  回显数据:struts-html.tld <html:checkbox> html:text

  struts-bean.tld

  struts-logic.tld

  //

  class CustomerAction extends DispatchAction{

   public ActionForward save(ActionMapping ActionForm Request,Response){

}

   public ActionForward update(ActionMapping ActionForm Request,Response){

}

  }

<action-mappings>

   <action path="/customerAction"

     name="customerForm"

     scope="request|session"

     validate="true"

     input="/xxx.jsp"

     type="xxxx..CustomerAction"

     parameter="method" />

  http://xxx/sss/customerAction.do?method=save

struts2:基于filter,没有actionform,action(原型的,独占).

  seperate aware:分离关注.解耦.(interceptor,拦截器).

  action是模型层(接受参数+pojo).

  action不需要和struts的action和原生servlet API(HttpServletRequest,HttpServlerResponse)耦合在一起.

  所以更容易测试,不需要一定要部署到web环境中进行测试.

  struts2是更加整洁的mvc框架(原因是采用了seperate aware技术,实现任务的拆解).

体验struts2:

 1.创建web项目

 2.引入struts2类库

  ${struts解压目录}/app/struts2-blank-2.1.8.1.war/web-inf/lib/*.jar

 3.创建action.

  package cn.itcast.struts2.action;

/**

   * HelloWorldAction

   */

  public class HelloWorldAction {

   public String execute(){

    System.out.println("hello world");

    return null ;

   }

  }

 4.创建struts配置文件.src/struts.xml

  dtd:struts-core.jar/struts-2.1.7.dtd/30行

  <?xml version="1.0"?>

  <!DOCTYPE struts PUBLIC

   "-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN"

   "http://struts.apache.org/dtds/struts-2.1.7.dtd">

  <struts>

   <package name="HelloWorldPkg" namespace="/helloworld">

    <action name="HelloWorldAction" class="cn.itcast.struts2.action.HelloWorldAction" />

   </package>

  </struts>

 5.配置struts2的过滤器web-inf/web.xml文件中

  类:org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter

  <?xml version="1.0" encoding="UTF-8"?>

  <web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

   xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee

   http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

   <filter>

    <filter-name>action</filter-name>

    <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>

   </filter>

   <filter-mapping>

    <filter-name>action</filter-name>

    <url-pattern>/*</url-pattern>

   </filter-mapping>

   

   <welcome-file-list>

    <welcome-file>index.jsp</welcome-file>

   </welcome-file-list>

  </web-app>

struts2包搜索顺序:

 http://localhost:8085/lsn_struts2/helloworld/aaa/bbb/HelloWorldAction.action

 http://localhost:8085/lsn_struts2/helloworld/aaa/bbb/

 http://localhost:8085/lsn_struts2/helloworld/aaa/

 http://localhost:8085/lsn_struts2/helloworld

list lst = .. ;

request.setAttribute("list",list); Map<String,Object>

request.getRequestDispatcher("/xxxx.jsp").forward(request,response);

HttpServletResponse.sendRedirect("/xx");

ContentType:

response.setContentType("text/html");

mime:

(HttpServletRequest)request.getAttribute("list");

request.setAttribute("list",list);

map:Sessoin (ServletContext)Application.setAttri

使用Token拦截器避免表单重复提交:

 1.在jsp页面上使用<s:token />

 2.在拦截器栈中加入token拦截器.

Google:

Web:异步执行.

2. 实例: 表单提交 ,校验,防重复提交,文件上传

web.xml 配置

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<filter>
<filter-name>action</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>action</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping> <welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>

struts.xml配置  包含模块 reg.xml

<?xml version="1.0"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN"
"http://struts.apache.org/dtds/struts-2.1.7.dtd">
<struts> <!-- 通过常量方式改变struts默认的属性配置, -->
<constant name="struts.action.extension" value="do" />
<!-- 设置开发模式,重新加载国际化资源文件和配置文件 -->
<constant name="struts.devMode" value="true" />
<!-- 动态方法调用 -->
<constant name="struts.enable.DynamicMethodInvocation" value="true" /> <package name="HelloWorldPkg" namespace="/helloworld" extends="struts-default">
<!-- 默认该包下默认的action引用,若该包没有要访问的action元素,则使用默认的action引用 -->
<default-action-ref name="HelloWorldAction" /> <!-- 设置默认的class引用,将摸个类作为默认的action类 -->
<default-class-ref class="cn.itcast.struts2.action.HelloWorldAction" /> <!-- 通过通配符的方式实现动态方法调用 -->
<action name="HelloWorldAction_*" class="cn.itcast.struts2.action.HelloWorldAction"
method="{1}">
<result name="success">/index.jsp</result>
<result name="save">/index.jsp</result>
<result name="update">/success.jsp</result>
</action> <!-- 没有类的action -->
<action name="ActionNoClass">
<result>/index.jsp</result>
</action>
</package>
<!-- 模块话编程,包含配置文件 -->
<include file="cn/itcast/struts2/action/reg.xml" />
</struts>

reg.xml  配置

<?xml version="1.0"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN"
"http://struts.apache.org/dtds/struts-2.1.7.dtd">
<struts>
<package name="RegPkg" namespace="/regns" extends="struts-default">
<action name="RegAction_*" class="cn.itcast.struts2.action.RegAction" method="{1}">
<result name="success">/reg/success.jsp</result>
<result name="error">/reg/error.jsp</result>
<result name="regView">/reg/reg.jsp</result>
<result name="input">/reg/reg.jsp</result>
<interceptor-ref name="defaultStack"> <!--动态方法调用,方式之一-->
<param name="validation.excludeMethods">input,back,cancel,toRegView</param>
</interceptor-ref>
</action>
</package>
</struts>

token.xml 防止重复提交 配置

<?xml version="1.0"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN"
"http://struts.apache.org/dtds/struts-2.1.7.dtd">
<struts>
<package name="TokenPkg" namespace="/token" extends="struts-default">
<action name="TokenAction_*" class="cn.itcast.struts2.token.TokenAction" method="{1}">
<result name="success">/token/success.jsp</result>
<result name="regView">/token/reg.jsp</result>
<!--无效令牌-->
<result name="invalid.token">/token/reg.jsp</result>
<result name="wait">/wait.jsp</result>
<!-- 如果指定了一个拦截器,则覆盖默认的配置,必须手动指定默认栈 -->
<interceptor-ref name="token">
<param name="excludeMethods">toRegView,findAllCustomers</param>
</interceptor-ref>
<interceptor-ref name="defaultStack" />
<!-- 执行等待拦截器 -->
<interceptor-ref name="execAndWait" />
</action>
</package>
</struts>

reg.jsp 表单提交 JSP, 使用struts-tags 标签,数据回显与校验

<%@ page language="java" contentType="text/html; charset=utf-8"%>
<%@taglib uri="/struts-tags" prefix="s"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>reg.jsp</title>
</head>
<body>
<s:debug />
<s:actionerror />
<s:form namespace="/regns" action="RegAction_reg" method="post" enctype="multipart/form-data">
<s:token /> <!--防止重复提交-->
<s:textfield name="name" label="UserName" />
<s:textfield name="age" label="UserAge" />
<s:file name="photo" label="UserPhoto" />
<s:submit />
</s:form>
</body>
</html>

RegAction.java  处理action

public class RegAction extends ActionSupport {

	private static final long serialVersionUID = 2941355104469235318L;
private String name;
private Integer age; /* 接受上传的文件 */
private File photo ;
/* 接受文件名称 */
private String photoFileName ;
/* 接受文件内容类型的 */
private String photoContentType ; public String getPhotoFileName() {
return photoFileName;
} public void setPhotoFileName(String photoFileName) {
this.photoFileName = photoFileName;
} public String getPhotoContentType() {
return photoContentType;
} public void setPhotoContentType(String photoContentType) {
this.photoContentType = photoContentType;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public Integer getAge() {
return age;
} public void setAge(Integer age) {
this.age = age;
} /**
*
*/
public String reg(){
System.out.println("reg : " + name);
String dir = ServletActionContext.getServletContext().getRealPath("/upload");
String ext = photoFileName.substring(photoFileName.lastIndexOf("."));
long l = System.nanoTime();
File newFile = new File(dir,l + ext);
photo.renameTo(newFile);
return SUCCESS;
} /**
* 达到注册页面, 动态方法调用之一, 使用SkipValidation标签掉过校验
*/
//@SkipValidation
public String toRegView(){
return "regView" ;
} /**
* 动态方法调用之一,命名: validate + 要校验方法(Reg) == void validateReg() {}
*/
public void validate() {
if(name == null || name.length() == 0){
//国际化,getText会从配置文件获得message,配置文件名和类名一致,位置相同,RegAction.properties
addFieldError("name",getText("error.name.empty"));
}
} public File getPhoto() {
return photo;
} public void setPhoto(File photo) {
this.photo = photo;
}
}

RegAction.properties 国际化配置文件

error.name.empty=name is required!
error.name.age=age is required!

success.jsp 成功跳转JSP

<%@ page language="java" contentType="text/html; charset=utf-8"%>
<%@taglib uri="/struts-tags" prefix="s"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>index.jsp</title>
</head>
<body>
you input's name is <s:property value="name" />.<br>
you input's age is <s:property value="age" />.<br>
</body>
</html>

wait.jsp 等待页面

<%@ page language="java" contentType="text/html; charset=utf-8"%>
<%@taglib uri="/struts-tags" prefix="s"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>wait.jsp</title>
<meta http-equiv="refresh" content="2;url=<s:url/>"/>
</head>
<body>
处理中,请稍后....
</body>
</html>

JavaWeb -- Struts2,对比, 简单表单提交,校验,防重复提交, 文件上传的更多相关文章

  1. 表单同时有中文字段和文件上传,加上enctype="multipart/form-data"后导致的中文乱码问题

    因为一个表单需要同时上传字段和文件,所以加上enctype="multipart/form-data",但是上传后的中文字段变成了乱码. 把enctype="multip ...

  2. PHP表单处理、会话管理、文件上传、文件处理、执行函数(10.8 第十六天)

    表单处理 服务器接收用户发过来的数据方式: $_GET 接收用户以GET方式发过来的数据 $_POST 接收用户以POST方式发过来的数据 $_COOKIE 接收用户COOKIE $_REQUEST ...

  3. php表单加入Token防止重复提交的方法分析

    http://www.jb51.net/article/94395.htm 这篇文章主要介绍了php表单加入Token防止重复提交的方法,结合实例形式分析了Token防止重复提交的原理与使用技巧,需要 ...

  4. IE兼容性问题解决方案4--form表单在IE下重复提交

    遇到过一种情况,点击提交按钮的时候,在IE下重复提交,而在其他浏览器下正常. 原因:button按钮不设置type时,在IE下被浏览器默认解析为type="submit",用js提 ...

  5. 前端 HTML form表单标签 input标签 type属性 file 上传文件

     加上上传文件功能 input type='file' - 依赖form表单里一个属性 enctype="multipart/form-data" 加上这个属性表示把你上次文件一点 ...

  6. 简单原始的ASP.NET WEBFORM中多文件上传【参考其他资料修改】

    首先是ASPX页面中添加file标签 <input onclick="addFile()" type="button" value="增加&qu ...

  7. angular 1.2.29版本下 动态添加多个表单、 校验全部、 提交 、ng-form方案

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  8. Javaweb学习笔记——(二十二)——————文件上传、下载、Javamail

    文件上传概述      1.文件上传的作用          例如网络硬盘,就是用来上传下载文件的.          在网络浏览器中,时常需要上传照片 2.文件上传对页面的要求          上 ...

  9. 超全面的JavaWeb笔记day22<文件上传>

    文件上传概述 1 文件上传的作用 例如网络硬盘!就是用来上传下载文件的. 在智联招聘上填写一个完整的简历还需要上传照片呢. 2 文件上传对页面的要求 上传文件的要求比较多,需要记一下: 1. 必须使用 ...

  10. thinkphp5.0 实现单文件上传功能

    思路是:在app/ceshi/fire下面有一个index操作方法来渲染显示前端文件,然后前端文件跳转到upload操作方法进行处理,成功显示"文件上传成功",失败显示错误. 首先 ...

随机推荐

  1. 160704、commons-beanutils.jar常用方法

    package com.test.beanutils; import java.lang.reflect.InvocationTargetException;import java.text.Pars ...

  2. Trifo-VIO:Roubst and Efficient Stero Visual Inertial Odometry using Points and Lines论文笔记

    这是2018-IROS上的一篇文章,亮点是作者提出了Lines特征的VIO方案,还有就是提出一个新颖的回环检测,不是用传统的基于优化的方法或者BA,另外作者还发布了一个新的用于VIO的数据集.亮点主要 ...

  3. 巨蟒python全栈开发数据库前端3:CSS基础2

    1.文本属性 2.背景属性 3.边框属性 4.display属性 5.盒子模型

  4. 机器被感染病毒文件zigw的处理流程

    1.现象 服务器CPU报警,查看时,已接近100%. 2.查找 使用top查看是哪个进程在占用CPU,此时zigw立刻出现,记录下进程的PID,假如为12345. (1) 如果在不知道程序的路径前,就 ...

  5. python基础之类的继承与派生、组合、接口与归一化设计、抽象类、子类中调用父类方法

    一.什么是继承 继承是一种创建新的类的方式,新建的类可以继承自一个或者多个父类,原始类称为基类或超类,新建的类称为派生类或子类. 派生:子类继承了父类的属性,然后衍生出自己新的属性,如果子类衍生出的新 ...

  6. windows下安装Composer提示缺少openssl的解决方法

    在Windows环境下安装Composer(注:Composer要求PHP版本在5.3.2+),你可能会遇到这种安装失败的情况:出错信息是 "The openssl extension is ...

  7. 使用Xcode改动iOS项目project名和路径名

    对,好.错.改正. ------ 前言 系统 10.9 开发平台 xcode 5.0 旧project名 MyProject-iPad 改动之后 新project名 FjSk-iPad 点击项目,进入 ...

  8. tornado下使用静态文件和文件缓存

    静态文件和文件缓存 1.在应用配置 settings 中指定 static_path 选项来提供静态文件服务:   2.在应用配置 settings 中指定 static_url_prefix 选项来 ...

  9. day3-python-文件操作(2)

    本文内容涉及python中的os模块和os.path模块的常用操作,这两个模块提供了与平台和操作系统无关的文件系统访问方法.os模块负责大部分的文件系统操作,包括:删除文件.重命名文件.遍历目录树等: ...

  10. python2中range和xrange的区别

    range和xrange用法相同,不同的是xrange不是生成一个序列,而是作为一个生成器,即生成一个取出一个 相对来说,xrange比range性能优化很多,因为不需要一下子开辟一块很大的内存,特别 ...