??xml version="1.0" encoding="utf-8" standalone="yes"?>
l常看见jsp版里有h问时间操作的问题Q这些问题一般包括:取当前时_把一个指定的字符串时间{化成旉cdQ求两个旉之间的天敎ͼ求一D|间以前的旉Q求一D|间以后的旉Q在q里把q些问题汇M下?br /><%@ page contentType="text/html;charset=gb2312"%>
<%@ page import="java.text.*"%>
<%@ page import="java.util.*"%>
<%
//字符串{化成旉cdQ字W串可以是Q意类型,只要和SimpleDateFormat中的格式一致即可)
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("M/dd/yyyy hh:mm:ss a",java.util.Locale.US);
java.util.Date d = sdf.parse("5/13/2003 10:31:37 AM");
out.println(d);
out.println("<br>");
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String mDateTime1=formatter.format(d);
out.println(mDateTime1);
out.println("<br>");
out.println(d.getTime());
out.println("<br>");
//当前旉
Calendar cal = Calendar.getInstance();
// SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss G E D F w W a E F");
String mDateTime=formatter.format(cal.getTime());
out.println(mDateTime);
out.println("<br>");
//1q前日期
java.util.Date myDate=new java.util.Date();
long myTime=(myDate.getTime()/1000)-60*60*24*365;
myDate.setTime(myTime*1000);
String mDate=formatter.format(myDate);
out.println(mDate);
out.println("<br>");
//明天日期
myDate=new java.util.Date();
myTime=(myDate.getTime()/1000)+60*60*24;
myDate.setTime(myTime*1000);
mDate=formatter.format(myDate);
out.println(mDate);
out.println("<br>");
//两个旉之间的天?br />SimpleDateFormat myFormatter = new SimpleDateFormat("yyyy-MM-dd");
java.util.Date date= myFormatter.parse("2003-05-1");
java.util.Date mydate= myFormatter.parse("1899-12-30");
long day=(date.getTime()-mydate.getTime())/(24*60*60*1000);
out.println(day);
out.println("<br>");
//加半时
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
java.util.Date date1 = format.parse("2002-02-28 23:16:00");
long Time=(date1.getTime()/1000)+60*30;
date1.setTime(Time*1000);
String mydate1=formatter.format(date1);
out.println(mydate1);
out.println("<br>");
//q月周求日期
SimpleDateFormat formatter2 = new SimpleDateFormat("yyyy-MM F E");
java.util.Date date2= formatter2.parse("2003-05 5 星期?);
SimpleDateFormat formatter3 = new SimpleDateFormat("yyyy-MM-dd");
String mydate2=formatter3.format(date2);
out.println(mydate2);
out.println("<br>");
//求是星期?br />mydate= myFormatter.parse("2001-1-1");
SimpleDateFormat formatter4 = new SimpleDateFormat("E");
String mydate3=formatter4.format(mydate);
out.println(mydate3);
out.println("<br>");
%>
原来怀疑与xml面的编码有兌了一下,好像不v作用?br />
q个问题让我郁闷了两三天旉,最后才发现问题是在JSP端?<html:form action="/uploadsAction" enctype="multipart/form-data" >
标签如果了" enctype="multipart/form-data" 服务器就会报?
下面把代码脓出来.
JSP?br /> <html:errors />
<html:form action="/uploadsAction" enctype="multipart/form-data" >
<html:file property="theFile" />
<html:radio property="upType" value="a" />CSVFileReader
<html:radio property="upType" value="b" />FileUp
<html:submit value="OK" />
</html:form>
FormBean中将属性定义ؓFormFile,geter seter Ҏ依旧.
Action 中的代码如下:实现图片上传至UPLOAD文g夹内 如果文g大于20K或是宽&高超q规定范围的,会重新勾?实现对上传图片的控制.
当然q只是测试Action没有跌{面..
package upload;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForm;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.Action;
import org.apache.struts.upload.*;
import java.io.IOException;
import java.awt.Image;
import java.awt.image.BufferedImage;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import com.sun.image.codec.jpeg.JPEGCodec;
import java.io.File;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
public class UploadAction extends Action {
public ActionForward execute(ActionMapping actionMapping,
ActionForm actionForm,
HttpServletRequest servletRequest,
HttpServletResponse servletResponse)throws Exception {
System.out.println("asdasdasdasdasdasd");
UploadForm uploadForm = (UploadForm) actionForm;
FormFile pic = uploadForm.getPic();
String picname = pic.getFileName();
String uploadFileName = servletRequest.getSession()
.getServletContext()
.getRealPath("upload")+"\\"+picname;
File upliadFile = new File(uploadFileName);
BufferedInputStream bis = null;
Image image = null;
BufferedOutputStream bos = null;
try{
if(pic.getFileSize()<2*1024*1024){
bis = new BufferedInputStream(pic.getInputStream());
image = javax.imageio.ImageIO.read(bis);
int width = image.getWidth(null);
int height = image.getHeight(null);
int w = 160;
int h = 120;
if(width>w||height>h){
BufferedImage bi = new BufferedImage(w,h,
BufferedImage.TYPE_INT_RGB);
bi.getGraphics().drawImage(image,0,0,w,h,null);
bos = new BufferedOutputStream(new FileOutputStream(
upliadFile));
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(bos);
encoder.encode(bi);
System.out.println(width * height);
}else{
bos = new BufferedOutputStream(new FileOutputStream(upliadFile));
byte[] date = new byte[5*1024];
int len = bis.read(date);
while (len!=-1){
bos.write(date);
len = bis.read(date);
}
}
}
return actionMapping.findForward("ok");
}catch(Exception e){
e.printStackTrace();
} finally {
try {
if (bis != null)
bis.close();
} catch (IOException e1) {
e1.printStackTrace();
}
try {
if (bos != null)
bos.close();
} catch (IOException e2) {
e2.printStackTrace();
}
}
return actionMapping.findForward("ok");
}
}
配置q程Q?/p>
一、下载必要的jar包。有四个包要下蝲Q网上有贴子说只要下面前三个包就可以了,但我在配|的时候如果没有第四个包会报错Q?br />http://apache.linuxforum.net/dist/jakarta/commons/dbcp/binaries/commons-dbcp-1.2.zip
http://apache.linuxforum.net/dist/jakarta/commons/pool/binaries/commons-pool-1.2.zip
http://apache.linuxforum.net/dist/jakarta/struts/struts-legacy/struts-legacy-1.0.zip
http://apache.linuxforum.net/dist/jakarta/commons/collections/binaries/commons-collections-3.1.zip
把这四个jar包放到web应用的WEB-INF/lib目录下,q有要把MySQL的驱动程序包也放到这里(也可以把数据库的驱动包放?Tomcat_Home%/common/lib目录下或%Resin_Home%/lib目录下,q样在启动Web服务器的时候就会加载这个包Q服务器和Web应用都可以用驱动程序类Q?/p>
二、在struts-config.xml中添加Data Source。MyEclipse的Design模式下可以可视化地编辑struts-config.xml和添加Data SourceQ但它在struts-config.xml中生成的数据源的代码是错误的Q就是因个耽误了我很多旉Q?br />我们手工~辑代码Q?/p>
<data-sources>
<data-source key="datasource" type="org.apache.commons.dbcp.BasicDataSource">
<set-property property="password" value="admin" />
<set-property property="minCount" value="3" />
<set-property property="maxCount" value="10" />
<set-property property="username" value="admin" />
<set-property property="driverClassName" value="com.mysql.jdbc.Driver" />
<set-property property="description" value="test" />
<set-property property="url" value="jdbc:mysql://localhost/test" />
<set-property property="readOnly" value="false" />
<set-property property="autoCommit" value="true" />
</data-source>
</data-sources>
如果要配|多个data sourceQ可以给每个data source指定不同的keyQ然后在E序中根据key指定要引用的数据源?/p>
三、测试数据源。配|好以后可以在ActionServlet中用了?/p>
DataSource ds = getDataSource(request,"datasource");
Connection conn = ds.getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SQL String");
附: Struts1.1中struts-config.xml的配|:
<data-sources >
<data-source key="datasource" type="org.apache.struts.util.GenericDataSource">
<set-property property="password" value="admin" />
<set-property property="minCount" value="2" />
<set-property property="maxCount" value="10" />
<set-property property="user" value="admin" />
<set-property property="driverClass" value="com.mysql.jdbc.Driver" />
<set-property property="description" value="test" />
<set-property property="url" value="jdbc:mysql://localhost/test" />
<set-property property="readOnly" value="false" />
<set-property property="autoCommit" value="true" />
</data-source>
</data-sources>
注意Q蓝色字体的部分?.1?.2在配|上不一L地方?br />
<!DOCTYPE struts-config PUBLIC
</data-sources> <action-mappings> <controller> 二、Actionc? package page; import java.util.*; public class DataSourceAction extends Action { public DataSourceAction(){} // if there is a previous page, set the previous variable // if there is a next page, set the next variable }catch(SQLException e){
public int getId(){ public String getAuthor() { public void setAuthor(String author) { public String getBookname() { public void setBookname(String bookname) { <logic:iterate id="book" name="list" type="bean.Book"> <form action="/TestPage/page.do"> <logic:present name="next"> 每页<c:out value="${page}"/>条记??lt;c:out value="${pages}"/>?跛_<input type="text" name="go" size="3" maxlength="30" > OK!!!!
"-//Apache Software Foundation//DTD Struts Configuration 1.2//EN"
"
<struts-config>
<data-sources>
<data-source key="dataSource" type="org.apache.commons.dbcp.BasicDataSource">
<set-property property="driverClassName" value="sun.jdbc.odbc.JdbcOdbcDriver" />
<set-property property="url" value="jdbc:odbc:page" />
<set-property property="username" value="admin" />
<set-property property="password" value="" />
<set-property property="maxActive" value="20" />
<set-property property="maxWait" value="5000" />
<set-property property="defaultAutoCommit" value="true" />
<set-property property="defaultReadOnly" value="false" />
<set-property property="validationQuery" value="SELECT 1" />
<set-property property="removeAbandoned" value="true" />
<set-property property="removeAbandonedTimeout" value="120" />
<set-property property="encoding" value="false" />
</data-source>
<form-beans>
</form-beans>
<global-forwards>
</global-forwards>
<action path="/page" type="page.DataSourceAction" scope="request">
<forward name="success" path="/pagetest.jsp"/>
</action>
</action-mappings>
</controller>
</struts-config>
?page.do?start=1 来显C第一个页面?
参数说明Q?
listQ信息列表?
startQ开始位|?
pageQ每|C的信息数目
pages: 总页?
previousQ上开始位|?
nextQ下开始位|?
import org.apache.struts.action.*;
import javax.servlet.http.*;
import javax.sql.*;
import java.sql.*;
import bean.*;
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
try{
DataSource ds=this.getDataSource(request,"dataSource");
Connection con = ds.getConnection();
Statement stmt = con.createStatement();
ResultSet resultSet = stmt.executeQuery("select count(*) from book" );
resultSet.next();
int data_num=resultSet.getInt(1);
int start=1;
int page = 4; //每页的记录数?
int pages=data_num/page;
if(data_num%page!=0)
pages++;
if(request.getParameter("start")!=null)
start = Integer.parseInt(request.getParameter("start"));
if(request.getParameter("go")!=null){
int go = Integer.parseInt(request.getParameter("go"));
if(go<=1)
start=1;
else if(go>pages)
start=(pages-1)*page+1;
else
start=(go-1)*page+1;
}
String sql = "SELECT * FROM book where id>="+start+" and id<"+(start+page);
resultSet = stmt.executeQuery(sql);
ArrayList list = new java.util.ArrayList();
while(resultSet.next())
{
int id=resultSet.getInt("id");
String name = resultSet.getString("name");
String author = resultSet.getString("author");
String price = resultSet.getString("price");
System.out.println("开始数据封装:name="+name+"author="+author+"price="+price);
Book book= new Book(id,name,author,price);
list.add(book);
}
con.close();
request.setAttribute("pages",new Integer(pages));
request.setAttribute("list",list);
//request.setAttribute("start", new Integer(start));
request.setAttribute("page", new Integer(page));
int previous = start-page;
if ( previous>=0 ){
request.setAttribute("previous", new Integer(previous));
System.out.println ("previous:" + previous);
}
int next = start+page;
if ( next<=data_num ){
request.setAttribute("next", new Integer(next));
System.out.println ("next:" + next);
}
e.printStackTrace();
System.out.println("数据库连接出现异?);
}
return (mapping.findForward("success"));
}
}
三、beancBook.java
package bean;
import java.sql.*;
import java.util.ArrayList;
public class Book {
int id;
private String bookname; //书名
private String author; //作?
private String price; //h
public Book(int id,String name,String author,String price){
this.id=id;
this.bookname=name;
this.author=author;
this.price=price;
}
return id;
}
return author;
}
this.author = author;
}
return bookname;
}
this.bookname = bookname;
}
public String getPrice(){
return this.price;
}
public void setPrice(String price){
this.price=price;
}
}
四、分늚jsp面pagetest.jsp,用了jstl中的c标记?
<%@ page contentType="text/html; charset=gb2312" language="java"%>
<%@ page import="java.util.*" %>
<%@ page import="bean.*" %>
<%@ taglib prefix="c" uri="<%@ taglib uri="/tags/struts-bean" prefix="bean" %>
<%@ taglib uri="/tags/struts-html" prefix="html" %>
<%@ taglib uri="/tags/struts-logic" prefix="logic" %>
<br><html:link
paramId="id" paramName="book" paramProperty="id"
page="/messagedetail.do">
<bean:write name="book" property="bookname" />
</html:link>
</logic:iterate>
<logic:present name="previous">
<html:link
paramId="start" paramName="previous"
page="/page.do">
上一?
</html:link>
</logic:present>
<html:link
paramId="start" paramName="next"
page="/page.do">
下一?
</html:link>
</logic:present>
<input type="submit" value="go" >
</form>
五、测试,请下载本实例的目录结构TestPage,攑օtomcat的webapps下,在浏览器中输入:
http://127.0.0.1:8080/TestPage/page.do
来源Q?java学习?br />
]]>
一、在struts中分|两种l构Q?
1. 在Action中通过DAO查询出所有的记录Q然后加到session或request对象中,传到客户端,由JSPq行分页。这U方法对于在数据量少的时候很方便Q也不媄响速度?
2.在Action中每ơ通过DAO只查询出一늚记录Q再传给JSP面。这U结构对于数据量大的E序很好Q但对于数据量小的情况,会增加对服务器的hQ加大服务器的负载?
二、Hibernate查询
׃在Hibernate中直接提供了Ҏ据库定点定量的查询方法,所以我采用的是W?U方法?
如:
从第1万条开始取?00条记?
Query q = session.createQuery("from Cat as c");
q.setFirstResult(10000);
q.setMaxResults(100);
List l = q.list();
三、具体实?
1.Pagerc?
package com.jpcf.db.helper;
import java.math.*;
public class Pager {
private int totalRows; //总行?
private int pageSize = 10; //每页昄的行?
private int currentPage; //当前号
private int totalPages; //总页?
private int startRow; //当前在数据库中的v始行
public Pager() {
}
public Pager(int _totalRows) {
totalRows = _totalRows;
totalPages=totalRows/pageSize;
int mod=totalRows%pageSize;
if(mod>0){
totalPages++;
}
currentPage = 1;
startRow = 0;
}
public int getStartRow() {
return startRow;
}
public int getTotalPages() {
return totalPages;
}
public int getCurrentPage() {
return currentPage;
}
public int getPageSize() {
return pageSize;
}
public void setTotalRows(int totalRows) {
this.totalRows = totalRows;
}
public void setStartRow(int startRow) {
this.startRow = startRow;
}
public void setTotalPages(int totalPages) {
this.totalPages = totalPages;
}
public void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public int getTotalRows() {
return totalRows;
}
public void first() {
currentPage = 1;
startRow = 0;
}
public void previous() {
if (currentPage == 1) {
return;
}
currentPage--;
startRow = (currentPage - 1) * pageSize;
}
public void next() {
if (currentPage < totalPages) {
currentPage++;
}
startRow = (currentPage - 1) * pageSize;
}
public void last() {
currentPage = totalPages;
startRow = (currentPage - 1) * pageSize;
}
public void refresh(int _currentPage) {
currentPage = _currentPage;
if (currentPage > totalPages) {
last();
}
}
}
Pagercȝ于计首c前一c下一c尾늚在数据库中的起始行,当前的页码?
2.PagerHelpc?
package com.jpcf.db.helper;
import javax.servlet.http.*;
public class PagerHelper {
public static Pager getPager(HttpServletRequest httpServletRequest,int totalRows) {
//定义pager对象Q用于传到页?
Pager pager = new Pager(totalRows);
//从Request对象中获取当前页?
String currentPage = httpServletRequest.getParameter("currentPage");
//如果当前号为空Q表CZؓ首次查询该页
//如果不ؓI,则刷新pager对象Q输入当前页L信息
if (currentPage != null) {
pager.refresh(Integer.parseInt(currentPage));
}
//获取当前执行的方法,首页Q前一,后一,N?
String pagerMethod = httpServletRequest.getParameter("pageMethod");
if (pagerMethod != null) {
if (pagerMethod.equals("first")) {
pager.first();
} else if (pagerMethod.equals("previous")) {
pager.previous();
} else if (pagerMethod.equals("next")) {
pager.next();
} else if (pagerMethod.equals("last")) {
pager.last();
}
}
return pager;
}
}
PageHelperq个c,我不用说应该也知道用来干嘛了
3.DAOc?
package com.jpcf.db.dao;
import com.jpcf.db.model.*;
import com.jpcf.db.helper.HibernateUtil;
import net.sf.hibernate.*;
import java.util.*;
import com.jpcf.db.controller.*;
public class VehiclePropertyDAO {
public Collection findWithPage(int pageSize, int startRow) throws HibernateException {
Collection vehicleList = null;
Transaction tx = null;
try {
Session session = HibernateUtil.currentSession();
tx = session.beginTransaction();
Query q = session.createQuery("from VehicleProperty vp");
q.setFirstResult(startRow);
q.setMaxResults(pageSize);
vehicleList = q.list();
tx.commit();
} catch (HibernateException he) {
if (tx != null) {
tx.rollback();
}
throw he;
} finally {
HibernateUtil.closeSession();
}
return vehicleList;
}
public int getRows(String query) throws HibernateException {
int totalRows = 0;
Transaction tx = null;
try {
Session session = HibernateUtil.currentSession();
tx = session.beginTransaction();
totalRows = ((Integer) session.iterate(query).next()).intValue();
tx.commit();
} catch (HibernateException he) {
if (tx != null) {
tx.rollback();
}
throw he;
} finally {
HibernateUtil.closeSession();
}
return totalRows;
}
}
DAOcLpq些分页需要的代码了?
“from VehicleProperty vp”也可以用一个参Cq来Q有兴趣的自己改一下吧
4.Action
下面是在Action中用到的代码Q?
public ActionForward execute(ActionMapping actionMapping,
ActionForm actionForm,
HttpServletRequest httpServletRequest,
HttpServletResponse httpServletresponse) {
Collection clInfos = null;//用于输出到页面的记录集合
int totalRows;//记录总行?
VehiclePropertyDAO vehicleDAO = new VehiclePropertyDAO();
//取得当前表中的总行?
try {
totalRows = vehicleDAO.getRows("select count(*) from VehicleProperty");
} catch (Exception ex) {
servlet.log(ex.toString());
return actionMapping.findForward(Constants.FAILURE);
}
//通过PagerHelpercL获取用于输出到页面的pager对象
Pager pager=PagerHelper.getPager(httpServletRequest,totalRows);
//取出从startRow开始的pageSize行记?
try {
clInfos = vehicleDAO.findWithPage(pager.getPageSize(), pager.getStartRow());
} catch (Exception ex) {
servlet.log(ex.toString());
return actionMapping.findForward(Constants.FAILURE);
}
//把输出的记录集和pager对象保存到request对象?
httpServletRequest.setAttribute("CLINFOS", clInfos);
httpServletRequest.setAttribute("PAGER", pager);
return actionMapping.findForward(Constants.SUCCESS);
}
查询语句select count(*) from VehicleProperty 也可以换成你需要的L的条Ӟselect count(*)
from VehicleProperty where ..)
5.JSP面使用
下面是在JSP中的应用了:
<td colspan="8" align="right" class="head">
W?lt;bean:write name="PAGER" property="currentPage"/>?
?lt;bean:write name="PAGER" property="totalPages"/>?
<html:link action="/bussiness/clInfo/queryWithPage.do?method=queryWithPage&pageMethod=first"
paramName="PAGER" paramProperty="currentPage" paramId="currentPage">首页</html:link>
<html:link action="/bussiness/clInfo/queryWithPage.do?method=queryWithPage&pageMethod=previous"
paramName="PAGER" paramProperty="currentPage" paramId="currentPage">上一?lt;/html:link>
<html:link action="/bussiness/clInfo/queryWithPage.do?method=queryWithPage&pageMethod=next"
paramName="PAGER" paramProperty="currentPage" paramId="currentPage">下一?lt;/html:link>
<html:link action="/bussiness/clInfo/queryWithPage.do?method=queryWithPage&pageMethod=last"
paramName="PAGER" paramProperty="currentPage" paramId="currentPage">N</html:link>
</td>
解释一下这一?"/bussiness/clInfo/queryWithPage.do?method=queryWithPage&pageMethod=first
method=queryWithPage 是由于我的Actionl承的是DispatchAction,需要一个method参数
pageMethod=first 是用来在PageHelpercM判断执行哪个操作
四、ȝ
我做的这个也只是一个借鉴Q还有很多没有实现的Q比如还可以加一?go 直接到第n늚功能?
其实最关键的是把当前页号和要执行的是功?上一,下一?的参C面传进来,在Action中就可以Ҏq两个参数去取下一个页面上要显C的记录集了?
Jsp上传面Q?
<%@ page contentType="text/html; charset=GBK" %>
<html>
<head>
<title>
strutsUploadForm
</title>
</head>
<body bgcolor="#ffffff">
<h1>
上传试
</h1>
<form action="uploadTestAction.do" method="post" enctype="multipart/form-data" name="form1">
<p>文本
<input name="theText" type="text" id="theText">
</p>
<p>文g
<input name="theFile" type="file" id="theFile">
</p>
<p>保存?
<input name="saveTo" type="text" id="saveTo">
</p>
<p>
<input type="submit" name="Submit" value="提交">
</p>
</form>
</body>
</html>
actionForm
package hehe;
import org.apache.struts.action.*;
import javax.servlet.http.*;
import org.apache.struts.upload.FormFile;
public class UploadTestForm extends ActionForm {
private String saveTo;
private String theText;
private org.apache.struts.upload.FormFile theFile;//文g框对应的是formFilecd
public String getSaveTo() {
return saveTo;
}
public void setSaveTo(String saveTo) {
this.saveTo = saveTo;
}
public org.apache.struts.upload.FormFile getTheFile() {
return theFile;
}
public void setTheFile(org.apache.struts.upload.FormFile theFile) {
this.theFile = theFile;
}
public String getTheText() {
return theText;
}
public void setTheText(String theText) {
this.theText = theText;
}
public ActionErrors validate(ActionMapping actionMapping, HttpServletRequest httpServletRequest) {
/**@todo: finish this method, this is just the skeleton.*/
if(!this.getTheFile().getContentType().equals("image/pjpeg")){
System.out.println("不是jpg");
}//可以判断cd
if(this.getTheFile().getFileSize()>100){
System.out.println("长度大于1000");
}//可以判断大小
return null;
}
public void reset(ActionMapping actionMapping, HttpServletRequest httpServletRequest) {
saveTo = null;
theFile = null;
theText = null;
}
}
Action
package hehe;
import org.apache.struts.action.*;
import org.apache.struts.upload.FormFile;
import javax.servlet.http.*;
import java.io.*;
public class UploadTestAction
extends Action {
public ActionForward execute(ActionMapping actionMapping,
ActionForm actionForm,
HttpServletRequest request,
HttpServletResponse response) {
UploadTestForm uploadForm = (UploadTestForm) actionForm;
FormFile file = uploadForm.getTheFile();
String path = uploadForm.getSaveTo();
String theText = uploadForm.getTheText();
try {
InputStream input = file.getInputStream();//能从FormFile中获得输入流
OutputStream output = new FileOutputStream(path);
int bytesReader = 0;
byte[] readbuffer = new byte[8192];
while ( (bytesReader = input.read(readbuffer, 0, 8192)) != -1) {
output.write(readbuffer, 0, bytesReader);
}
output.close();
}
catch (Exception e) {
e.printStackTrace();
}
request.setAttribute("theText", theText);
request.setAttribute("fileName", file.getFileName());//上传的文件名
request.setAttribute("fileSize", new Integer(file.getFileSize()));//文g大小
request.setAttribute("fileType", file.getContentType());//文gcd
return actionMapping.findForward("success");
}
}
l果面
<%@ page contentType="text/html; charset=GBK" %>
<html>
<head>
<title>
strutsUploadResult
</title>
</head>
<body bgcolor="#ffffff">
<h1>
上传l果
</h1>
文g名:<%=request.getAttribute("fileName")%><br />
文本Q?lt;%=request.getAttribute("theText")%><br />
文gcdQ?lt;%=request.getAttribute("fileType")%><br />
文g大小Q?lt;%=request.getAttribute("fileSize")%><br />
</body>
</html>
java
代码
:
|
|
在程序中定义错误和信息类
,
q个例子写在
JSP
?/span>
java
代码
:
|
|
昄错误
:
java
代码
:
|
|
昄信息
:
java
代码
:
|
|
2.对于参数g定的,paramName和paramProperty来输出,用paramId属性指定参数名?br />对于paramName指定的对象应该存在于page、request、session、application其中之一。一般来_是从ActioncMq来的,作ؓrequest的属性之一Qrequst.setAttribute("name",object)Q?br />如果paramName指定的对象是action的ActionFormQ则无需使用request.setAttributeҎ?br />例:<html:link page="/test.do" paramId="userid" paramName="uid">uname</html:link>
若参数值是一个bean对象的属性|比如ActionForm,或者集合中存放的对象)则:
<html:link page="/test.do" paramId="userid" paramName="user" paramProperty="uid">uname</html:link>
3.若两个参敎ͼ一个确定一个不定Q则是以上两U方法的l合Q即Q?br /><html:link page="/test.do?action=modify" paramId="userid" paramName="uid">modify</html:link>
4.对于多个参数的问题,可以使用一个HashMap集合对象来存放所有的参数名及对应的参数值的方式QparamName属性值指定ؓ该HashMap集合对象卛_?br />举例Q?br /><%
//代码理想的位|应该是在action?br />//可以在jsp面试
java.util.HashMap pms = new java.util.HashMap();
pms.put("code", "001002");
pms.put("name", "tester");
pms.put("alias", new String[]{"matin","jack"});
request.setAttribute("params", pms);
%>
<html:link action="/test.do" name="params" >test</html:link>
~译后的l果Q?lt;a href="/test.do?code=001002&name=tester&alias=matin&alias=jack">test</a>
q种方式虽然可以解决传多参数的问题,但是实现h也比较麻烦,特别是对记录集中的数据逐条列出的时?/p>
5.针对有的|友?lt;html:link>标签中嵌入用jsp脚本(scriptlet)的问题,
例如:
<html:link page="/test.do?code=<%=varible%>">add</html:link>Q这U写法是错误的,是无法编译的?br />有的|友认ؓ在struts标签内是不允怋用jsp脚本的,q种说法也不准确。如果前面的写法Ҏ:
<html:link page="<%="/test.do?code="+varible%>">add</html:link>Q就可以被执行,但是要注意URL相对路径的问题?/p>
虽然在struts标签中嵌入jsp脚本不是真正意义上的struts应用Q但是有时在委曲求全的情况下也只能如此了Q除非用自定义标签。比如在form表单中可能需要根据具体数据让某个字段是只ȝQ就可以用嵌入jsp脚本来实玎ͼ
<%
boolean rdonly=false;
if(2==2) rdonly=true;
%>
<html:text property="userid" readonly="<%=rdonly%>" />
6.另外一U比较变态的ҎQ既不是真正意义上的strutsQ也不符合xml规范。那是?lt;a>标签中用<bean:write>标签输出参数倹{?br />如:<a href="test.do?uid=<bean:write name="user" property="userid"/>&name=<bean:write name="user" property="username"/>">test</a>