1. 新建工程后,先引入struts2的jar包:右击项目---myeclipse---add struts capabilities,引入后,web.xml中会生成对应的filter:
- <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>*.action</url-pattern>
- </filter-mapping>
一个filter对应一个filter-mapping.也可以写自己的filter,比如写一个过滤器用来设置编码的,这样,就可以在web.xml中配置写好的action.
2. struts2的配置:
- <package namespace="/" name="default" extends="struts-default">
- <action name="UploadAction"
- class="com.up.action.UploadAction" >
- <!-- 将savePath设置为"根目录下的upload文件夹" -->
- <param name="savePath">/upload</param>
- <result name="show">/showc.jsp</result>
- <result name="error">/index.jsp</result>
- </action>
- </package>
首先是package,之后是action,action中对应一个或者多个result,如果有其他需要,再进行其他的设置,比如上面的param是用来上传文件的.
3. 编写对应的action,并在jsp页面中进行请求:
编写action要按照配置的struts.xml文件进行编写,action要继承ActionSupport类,并override public String execute(){} 方法
4. 最后,页面和action的传递工作可以由get和set方法实现.
哇,现在才发现,struts2真的很方便呢~
接下来记录今天写的功能啦!
首先用struts2自带的文件上传功能进行文件的上传,之后是读取上传的word文档.读取word文档用到了一个jar包:tm-extractors-0.4,在网上有下的.
具体代码如下:
index.jsp:
- <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
- <%@ taglib uri="/struts-tags" prefix="s"%>
- <%
- 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>Demo of upload files</title>
- <script type="text/javascript">
- function checkup(){
- //提示信息
- var div=document.getElementById("uploadname");
- if(document.form1.gljueyi.value.length==0){
- div.innerHTML="请选择要上传的文件";
- document.form1.gljueyi.focus();
- return false;
- }
- return true;
- }
- </script>
- <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">
- -->
- <style>
- *{ font-size:14px;}
- </style>
- </head>
- <body>
- <form action="UploadAction.action" name="form1" method="post" enctype="multipart/form-data">
- <table>
- <tr>
- <td > </td>
- <td ><span id="message" style="font-size:16px;color:red;" >
- </span></td>
- </tr>
- <tr>
- <td style="line-height:30px;">选择上传的文件:</td>
- <td> <input type="file" id="uploadname" name="upload"></td>
- </tr>
- <tr>
- <td style="line-height:30px;"><input type="submit" name="button" id="button" value="提交" onClick="return checkup();"></td>
- <td><input type="reset" name="button2" id="button2" value="重置"></td>
- </tr>
- </table>
- </form>
- </body>
- </html>
struts.xml文件:
- <?xml version="1.0" encoding="UTF-8" ?>
- <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
- <struts>
- <package namespace="/" name="default" extends="struts-default">
- <action name="UploadAction"
- class="com.up.action.UploadAction" >
- <!-- 将savePath设置为"/upload" -->
- <param name="savePath">/upload</param>
- <result name="show">/showc.jsp</result>
- <result name="error">/index.jsp</result>
- </action>
- </package>
- </struts>
UploadAction.java:
- package com.up.action;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileOutputStream;
- import java.text.SimpleDateFormat;
- import java.util.Date;
- import org.apache.struts2.ServletActionContext;
- import org.textmining.text.extraction.WordExtractor;
- import com.opensymphony.xwork2.ActionSupport;
- public class UploadAction extends ActionSupport {
- File upload;
- String uploadContentType;
- String uploadFileName;
- String str;
- private String savePath;
- public String execute() throws Exception{
- // System.out.println("开始上传单个文件-----------------------");
- // System.out.println(getSavePath());
- // System.out.println("==========" + getUploadFileName());
- // System.out.println("==========" + getUploadContentType());
- // System.out.println("==========" + getUpload());
- // 以服务器的文件保存地址和原文件名建立上传文件输出流
- /*
- * 文件上传工作
- */
- String doc = getFilename(getUploadFileName());
- String filename =getTime() + "." + doc;
- //文件上传
- //getSavepath()是获取struts.xml中传过来的值
- FileOutputStream fos = new FileOutputStream(getSavePath() + "\\" + filename);
- FileInputStream fis = new FileInputStream(getUpload());
- byte[] buffer = new byte[1024];
- int len = 0;
- while ((len = fis.read(buffer)) > 0)
- {
- fos.write(buffer , 0 , len);
- }
- int ch = 0;
- String path = ServletActionContext.getServletContext().getRealPath("/upload");
- try{
- FileInputStream in = new FileInputStream (path + "\\" + filename);
- WordExtractor extractor = new WordExtractor(); //这里用tm-extractors-0.4.jar实现对word的读取操作.
- str = extractor.extractText(in);
- System.out.println(str);
- }catch(Exception e){
- e.printStackTrace();
- }
- return "show";
- }
- String getTime(){
- /**
- * 获取时间来定义文件名称
- * @return String as the name of the file
- */
- SimpleDateFormat formatter_f = new SimpleDateFormat("yyyyMMddHHmmss");
- Date now = new Date();
- String time = formatter_f.format(now);
- return time;
- }
- String getTrueTime(){
- /**
- * 获取当前时间
- * @return String time
- */
- SimpleDateFormat formatter_f = new SimpleDateFormat("yyyy-MM-dd");
- Date now = new Date();
- String time = formatter_f.format(now);
- return time;
- }
- String getFilename(String name){
- /**
- * 获取文件名的后缀
- * @return String
- */
- int i = name.lastIndexOf(".")+1;
- return name.substring(i,name.length());
- }
- //接受依赖注入的方法
- public void setSavePath(String value)
- {
- this.savePath = value;
- }
- @SuppressWarnings("deprecation")
- private String getSavePath() throws Exception
- {
- return ServletActionContext.getRequest().getRealPath(savePath);
- }
- public void setUpload(File upload) {
- this.upload = upload;
- }
- public void setUploadContentType(String uploadContentType) {
- this.uploadContentType = uploadContentType;
- }
- public void setUploadFileName(String uploadFileName) {
- this.uploadFileName = uploadFileName;
- }
- public File getUpload() {
- return (this.upload);
- }
- public String getUploadContentType() {
- return (this.uploadContentType);
- }
- public String getUploadFileName() {
- return (this.uploadFileName);
- }
- public String getStr() {
- return str;
- }
- public void setStr(String str) {
- this.str = str;
- }
- }
最后显示,showc.jsp:
- <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
- <%@ taglib uri="/struts-tags" prefix="s"%>
- <%
- 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>Demo of upload files</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">
- -->
- <style>
- *{ font-size:14px;}
- </style>
- </head>
- <body>
- <s:property value="str"/>
- </body>
- </html>