(下节)Spring+JDBC+Struts;实现图片上传(后台文件名要规范),加国际化;头文件basepath确保路径从webroot开始;

引入struts,spring,hibernate等jar包


测试OK后,我们现在向页面展示产品列表,省略service,直接action

package com.kane.action;




import java.io.File;
import java.io.FileNotFoundException;
import java.util.List;
import java.util.Map;


import org.apache.struts2.ServletActionContext;
import org.aspectj.util.FileUtil;


import com.kane.service.IProductService;
import com.kane.util.FileUtils;
import com.kane.util.LogUtils;
import com.kane.vo.Product;
import com.opensymphony.xwork2.ActionSupport;


public class ProductAction extends ActionSupport {
private Product product;
private List<Product> list;
private int pageNo=1;
private int pageSize=5;
private int count;
public File getPhoto1() {
return photo1;
}
public void setPhoto1(File photo1) {
this.photo1 = photo1;
}
public String getPhoto1FileName() {
return photo1FileName;
}
public void setPhoto1FileName(String photo1FileName) {
this.photo1FileName = photo1FileName;
}
private File photo1;//用来接收图片文件
private String photo1FileName;//注意这里的文件名的命名,struts自动帮我们接收文件名

private String column="name";
private String keyword="";
private String message;
private String url;
private IProductService productServiceImpl;//这里用到IOC代理工厂类,别忘了要在spring中配置
public IProductService getProductServiceImpl() {
return productServiceImpl;
}
public void setProductServiceImpl(IProductService productServiceImpl) {
this.productServiceImpl = productServiceImpl;
}

public String list() throws Exception {
Map<String,Object> map=productServiceImpl.findAll(pageNo, pageSize, column, keyword);
list=(List<Product>)map.get("allProduct");
count=(Integer)map.get("allCount");//这是装箱,取的时候拆箱成int
LogUtils.addInfo("查看了产品列表");
return "list";
}

public String insert() throws Exception {
//文件上传操作,先确定保存在images/upload下
String savePath=ServletActionContext.getServletContext().getRealPath("/images/upload")+"/";
String filename=FileUtils.saveFile(photo1, photo1FileName, savePath);
product.setImages("images/upload/"+filename);//存在数据库中的是localfilename;
productServiceImpl.insert(product);
LogUtils.addInfo("添加产品"+product.getProductid());
url="index.jsp";
return "forward";
}
/**
* 尽量做到从action跳到jsp,即使没东西也尽量符合这规矩,不要jsp跳jsp
* @return
* @throws Exception
*/
public String insertPre() throws Exception {

return "insert";
}
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
public List<Product> getList() {
return list;
}
public void setList(List<Product> list) {
this.list = list;
}
public int getPageNo() {
return pageNo;
}
public void setPageNo(int pageNo) {
this.pageNo = pageNo;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public String getColumn() {
return column;
}
public void setColumn(String column) {
this.column = column;
}
public String getKeyword() {
return keyword;
}
public void setKeyword(String keyword) {
this.keyword = keyword;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}

}


显示列表界面

<%@ 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>My JSP 'product_list.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">


  </head>  
  <body>  
  <table width="80%" border="1"  align="center">
  <s:i18n name="message">
  <tr>
  <td><s:text name="msg.product.productid"></s:text></td>
  <td><s:text name="msg.product.name"></s:text></td>
  <td><s:text name="msg.product.description"></s:text></td>
  <td><s:text name="msg.product.baseprice"></s:text></td>
  <td><s:text name="msg.product.writer"></s:text></td>
  <td><s:text name="msg.product.publish"></s:text></td>
  <td><s:text name="msg.product.pages"></s:text></td>
  <td><s:text name="msg.product.images"></s:text></td>
  </tr>
  </s:i18n>
  <s:if test="list!=null&&list.size()>0">
    <s:iterator value="list" >
    <tr>
    <td>
    ${productid}
    </td>
    <td>
    ${name}
    </td>
    <td>
    <textarea rows="8" cols="50">${description}</textarea>
   
    </td>
    <td>
    ${baseprice}
    </td>
    <td>
    ${writer}
    </td>
    <td>
    ${publish}
    </td>
    <td>
    ${pages}
    </td>
    <td>
    <img alt="images/upload/noPhoto.jpg" src="${images==null?'images/upload/noPhoto.jpg':images}" width="80px" height="100px">
    </td>
    </tr>
    </s:iterator>
    </s:if>
    </table>
    <br>
    <jsp:include page="/split_page_plugin.jsp">
<jsp:param value="${pageNo}" name="pageNo"/>
<jsp:param value="${pageSize}" name="pageSize"/>
<jsp:param value="${keyword}" name="keyword"/>
<jsp:param value="${column}" name="column"/>
<jsp:param value="${count}" name="count"/>
<jsp:param value="product!list.action" name="url"/>
<jsp:param value="name:产品名称|writer:作者" name="columnData"/>
<jsp:param value="3" name="pageStyle"/>
</jsp:include>
  </body>
</html>

 从这开始我加入了国际化,对国际化有不清楚的可以参照我的博客http://blog.csdn.net/needkane/article/details/21120027

添加界面

<%@ 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>My JSP 'product_insert.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>
  <!-- 这里的namespace对应struts配置文件的,namespace=”/“,可以不写 -->
  <s:form action="product!insert.action" method="post" theme="simple" 
  namespace="/" enctype="multipart/form-data">
  名称:<s:textfield name="product.name"></s:textfield><br/>
  描述:<s:textarea name="product.description"></s:textarea><br/>
  产品价格:<s:textfield name="product.baseprice"></s:textfield><br/>
  作者:<s:textfield name="product.writer"></s:textfield><br/>
  出版社:<s:textfield name="product.publish"></s:textfield><br/>
  页数:<s:textfield name="product.pages"></s:textfield><br/>
  图片:<s:file name="photo1"></s:file><br/>
  <s:submit value="添加"></s:submit><s:reset value="重置"></s:reset>
  </s:form>
  </body>
</html>

当然不能忘了我的文件工具类

package com.kane.util;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;


public class FileUtils {
/**
* 保存文件功能
* @param file要保存的文件
* @param filename原文件名(用来取得扩展名)
* @param savePath要保存的路径(物理路径)
* @throws FileNotFoundException 
*/
public static String saveFile(File file,String filename,String savePath) throws FileNotFoundException {
//生成存下来的文件名,唯一性
String localFilename=UUID.randomUUID().toString();
//处理扩展名
String extName=filename.substring(filename.lastIndexOf("."));
//先将图片输入到java程序,再输出到物理路径
FileInputStream is =new FileInputStream(file);
//将图片输出到保存的物理路径
FileOutputStream os=new FileOutputStream(new File(savePath+localFilename+extName));
byte[] data=new byte[1024];//设置传输容器,jvm默认内存大小时64m
int length=0;
try {
//输入图片流
while ((length=is.read(data))!=-1) {
//输出图片流,写出
os.write(data,0,length);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
try {
if (is!=null) {
is.close();
}
if (os!=null) {
os.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
LogUtils.addInfo("保存了一个文件"+localFilename+extName);
return localFilename+extName;

}
/**
* 文件删除,删除产品信息,应该清除对应图片
* @param filePath
* @param fileName
*/
public static void deleteFile(String filePath, String fileName) {
File file = new File(filePath + fileName);
if (file.exists()) {
file.delete();
}
}
}


struts配置

<?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 name="root" namespace="/" extends="struts-default"><!--
<interceptors>
<interceptor name="localeInterceptor" class="com.kane.intercepor.LocaleInterceptor">
</interceptor>
struts本身有拦截器栈,不能因为一个拦截器,而不要其他,只能往里面加 
<interceptor-stack name="myDefaultStack">
<interceptor-ref name="localeInterceptor"></interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>
</interceptor-stack>

</interceptors>
<default-interceptor-ref name="myDefaultStack"></default-interceptor-ref>

-->
<interceptors>
<interceptor name="localeInterceptor"
class="com.kane.intercepor.LocaleInterceptor"></interceptor>
<interceptor-stack name="myDefaultStack">
<interceptor-ref name="localeInterceptor"></interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>
</interceptor-stack>
</interceptors>
<default-interceptor-ref name="myDefaultStack"></default-interceptor-ref>



<!-- 注意这里的action的class属性不是长类名,而是指向spring的配置 -->
<action name="product" class="productAction">
<!-- 路径名前面统计加/。表示从从webroot下寻找 -->
<result name="list">/pages/product_list.jsp</result>
<result name="forward">/forward.jsp</result>
<result name="insert">/pages/product_insert.jsp</result>

</action>
<!-- 这里不用!标记,这里_可以换成任何其他标示符,安全,{1}相当于取出后面跟的方法 -->
<action name="language_*" class="languageAction" method="{1}">
<result name="index">/index.jsp</result>
<result name="forward">/forward.jsp</result>
</action>


</package>

</struts>    

demo:项目代码

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值