初学Struts2.0配置

本文介绍Struts2框架的基本配置方法,包括web.xml和struts.xml文件的配置细节,以及LoginAction和UploadFileAction两个示例Action的实现过程。通过示例展示了如何进行登录验证及文件上传操作。

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">
 
 <!-- 定义Struts2的FilterDispathcer的Filter -->
    <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
    </filter>

 <!-- FilterDispatcher用来初始化struts2并且处理所有的WEB请求。 -->
    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
 
 <!-- 有时文件上传时common-io.jar,commons-fileupload-1.1.1.jar,有时会出错,加入org.apache.struts2.dispatcher.ActionContextCleanUp这个过滤器就行 -->
 
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

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>
    <!-- 配置国际化信息 -->
   <constant name="struts.custom.i18n.resources" value="messages"/>
   <!-- 设置使用的解码集 -->
    <constant name="struts.i18n.encoding" value="utf-8"/>


    <package name="wang" extends="struts-default">
       <action name="login" class="wang.actions.LoginAction">
            <result name="input">/index.jsp</result>
            <result name="error">/error.jsp</result>
            <result name="success">/login.jsp</result>       
        </action>
       
        <action name="upload" class="wang.actions.UploadFileAction">
           <!-- 动态设置action的属性值 -->
           <param name="savePath">d:/upload</param>
           <result name="input">/upload.jsp</result>
           <result name="success">/upload_suc.jsp</result>  
        </action>
       
    </package>
</struts>

LoginAction文件:

package wang.actions;

import java.util.Map;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class LoginAction extends ActionSupport {

 private String userName;
 private String userPwd;
 
 //result
 private String tip;
 private String[] books;
  
 public String getUserName() {
  return userName;
 }


 public void setUserName(String userName) {
  this.userName = userName;
 }


 public String getUserPwd() {
  return userPwd;
 }


 public void setUserPwd(String userPwd) {
  this.userPwd = userPwd;
 }


 public String getTip() {
  return tip;
 }


 public void setTip(String tip) {
  this.tip = tip;
 }


 public String[] getBooks() {
  return books;
 }


 public void setBooks(String[] books) {
  this.books = books;
 }


 public String execute() throws Exception {
  ActionContext ctx = ActionContext.getContext();
  //以下相当于在session保存东西(session.setAttribute(key,value);
  //页面中用 ${sessionScope.user}输出结果信息
  ctx.getSession().put("user", this.getUserName()); 
  ctx.getSession().put("pwd", this.getUserPwd());
  /*  //这种也可以
  Map map = ctx.getSession();
  map.put("user", this.getUserName());
  map.put("pwd", this.getUserPwd());
  */
  //以下相当于在request中保存东西(request.setAttribute(key,value);
  //页面中用 ${requestScope.test}输出结果信息
  ctx.put("test", "request put test");
  
  //保存结果,页面中用<s:property value="tip"/>输出结果信息
  //备注:页面中引入标签<%@taglib prefix="s" uri="/struts-tags"%>可以在struts2-core-2.0.11.1.jar/META-INF/struts-tags.tld中找到定义
  this.setTip("Login OK!");
  return this.SUCCESS;
 }

 
 public void validate() {
  if(userName == null || userName.equals("")){ //fieldName 为表单域的名字
   //this.addFieldError("userName", "User Name is NULL");  //也是OK
   this.addFieldError("userName", this.getText("userName.required"));   //国际化
   //页面的国际化可用: '%{getText("messageKey")}'
  }
  if(userPwd == null || userPwd.equals("")){
   this.addFieldError("userPwd", this.getText("userPwd.required"));
  }
  
 }

 
}

UploadFileAction文件:

package wang.actions;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

import com.opensymphony.xwork2.ActionSupport;

public class UploadFileAction  extends ActionSupport {
 
 private String title;
 
 //封装上传文件域的属性
 private File upload;  //和表单域的name相同
 //封装上传文件类型的属性
 private String uploadContentType; //一定要是name+ContentType
 //封装上传文件名的属性
 private String uploadFileName; //一定要是name+FileName
 
 //接受依赖注入的属性
 private String savePath;
 
  
 public String getSavePath() {
  return savePath;
 }
 //接受依赖注入的方法
 public void setSavePath(String savePath) {
  this.savePath = savePath;
 }
 
 public String getTitle() {
  return title;
 }
 public void setTitle(String title) {
  this.title = title;
 }
 public File getUpload() {
  return upload;
 }
 public void setUpload(File upload) {
  this.upload = upload;
 }
 public String getUploadContentType() {
  return uploadContentType;
 }
 public void setUploadContentType(String uploadContentType) {
  this.uploadContentType = uploadContentType;
 }
 public String getUploadFileName() {
  return uploadFileName;
 }
 public void setUploadFileName(String uploadFileName) {
  this.uploadFileName = uploadFileName;
 }
 
 
 
  public String execute() throws Exception
  {
   System.out.println("开始上传单个文件-----------------------");
   System.out.println(getSavePath());
   System.out.println("==========" + getUploadFileName());
   System.out.println("==========" + getUploadContentType());
   System.out.println("==========" + getUpload());
   //以服务器的文件保存地址和原文件名建立上传文件输出流
   //自己的修改的:ServletActionContext.getServletContext().getRealPath("/UploadImages")   
   FileOutputStream fos = new FileOutputStream(getSavePath() + "//" + getUploadFileName());
   FileInputStream fis = new FileInputStream(getUpload());
   byte[] buffer = new byte[1024];
   int len = 0;
   while ((len = fis.read(buffer)) > 0)
   {
    fos.write(buffer , 0 , len);
   }
         return SUCCESS;
     }
 
 

 
 
}

index.jsp文件:

<%@ page language="java" import="java.util.*" pageEncoding="utf-8" contentType="text/html;charset=utf-8"%>
<%@taglib prefix="s" uri="/struts-tags"%>


<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
   
    <title>My JSP 'index.jsp' starting page</title>
 <meta http-equiv="pragma" content="no-cache">
 <meta http-equiv="cache-control" content="no-cache">
 <meta http-equiv="expires" content="0">   
 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
 <meta http-equiv="description" content="This is my page">
 <!--
 <link rel="stylesheet" type="text/css" href="styles.css">
 -->
  </head>
 
  <body>
   This is my JSP page. <br>
   <s:fielderror></s:fielderror>
   <s:form action="login.action" method="post">
     <s:textfield name="userName" label='%{getText("userName.label")}'></s:textfield>
     <s:password name="userPwd" label="密码"></s:password>
    
     <s:submit value="Login"></s:submit>
   </s:form>
  
    <form action="login.action" method="post">
      UserName:<input type="text" name="userName">
      UserPwd :<input type="password" name="userPwd">
      <input type="submit" name="sbm" value="OK">
    </form>
  
  </body>
</html>

login.jsp文件:

输出结果2种方式如下:

<body>
    <s:property value="tip"/>
    ${sessionScope.user}<br/>
    ${sessionScope.pwd}<br/>
    ${requestScope.test}<br/>

</body>

upload.jsp文件:

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
   
    <title>My JSP 'upload.jsp' starting page</title>
   
 <meta http-equiv="pragma" content="no-cache">
 <meta http-equiv="cache-control" content="no-cache">
 <meta http-equiv="expires" content="0">   
 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
 <meta http-equiv="description" content="This is my page">
 <!--
 <link rel="stylesheet" type="text/css" href="styles.css">
 -->

  </head>
 
  <body>
    <form action="upload.action" method="post" enctype="multipart/form-data">
   文件标题:<input type="text" name="title" /><br>
   选择文件:<input type="file" name="upload" /><br>
 <input value="上传" type="submit" />
</form>
  </body>
</html>

 

内容概要:本文档系统性地介绍了2024年最新提出的两种智能优化算法——青蒿素优化算法与霜冰优化算法(RIME)的原理、实现方法及其性能对比分析,并提供了完整的Matlab代码实现。文档不仅聚焦于核心算法的仿真与验证,还整合了大量前沿科研资源,涵盖微电网优化、风电功率预测、无人机三维路径规划、电动汽车调度、图像融合、负荷预测、通信信号处理、电力系统故障恢复等多个高价值应用场景。所有案例均基于Matlab/Simulink平台进行建模与仿真,强调算法在复杂工程系统中的实际应用能力,旨在为科研人员提供一套从理论到代码再到应用的完整复现体系。; 适合人群:具备一定编程基础和科研背景的研究生、高校教师及工程技术人员,尤其适合从事智能优化算法研究、新能源系统优化、自动化控制、电力系统调度、无人机导航与路径规划等相关领域的研究人员。; 使用场景及目标:①用于高水平学术论文的复现与创新性研究,提升科研效率与成果产出;②应用于复杂工程系统的建模仿真与智能优化设计,如多能互补系统调度、无人机避障路径规划、微电网能量管理等;③作为智能优化算法的教学与学习资料,深入理解现代元启发式算法的设计思想与实现机制。; 阅读建议:建议读者结合文档中提供的Matlab代码与Simulink仿真模型,按照目录结构循序渐进地学习与实践,优先选择与自身研究方向契合的案例进行代码复现,重点关注算法参数设置、收敛曲线分析与多算法对比实验部分,以全面提升算法应用与科研创新能力。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值