1、项目图解
这里做的是品牌的查询和修改
2、我们开始做我们的相应的功能模块
页面的素材我会上传的,链接是:http://download.csdn.net/detail/cutter_point/8803985
BrandAction.java 查询实现
BrandManagerAction.java里面的
/**
* 显示类别查询界面
* @return String struts2的返回跳转result
* @throws Exception
*/
public String queryUI() throws Exception
{
return"query";
}
/**
* 功能:这个是实现品牌类和web层的交互
* 时间:2015年5月23日10:31:07
* 文件:BrandAction.java
* 作者:cutter_point
*/
packagecom.cutter_point.web.action.product;
import java.util.ArrayList;
importjava.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
importjavax.annotation.Resource;
importorg.springframework.context.annotation.Scope;
importorg.springframework.stereotype.Controller;
importcom.cutter_point.bean.PageView;
importcom.cutter_point.bean.QueryResult;
importcom.cutter_point.bean.product.Brand;
importcom.cutter_point.service.product.BrandService;
importcom.opensymphony.xwork2.ActionContext;
importcom.opensymphony.xwork2.ActionSupport;
@Controller
@Scope("prototype")
public class BrandActionextends ActionSupport
{
@Resource
private BrandService brandService; //通过接口注入,aop默认的方式
private int page;
private String query; //判断是从那个页面来的
private String name; //要查询的名字
@Override
public String execute() throws Exception
{
Map request =(Map)ActionContext.getContext().get("request");
PageView<Brand> pageview = newPageView<Brand>(12, this.getPage());
int firstindex = (pageview.getCurrentpage() - 1) *pageview.getMaxresult(); //得到从哪个开始索引的值
LinkedHashMap<String, String> orderby = newLinkedHashMap<String, String>();
orderby.put("code", "asc");
StringBuilder hsql = newStringBuilder("o.visible = ?");
List<Object> params = newArrayList<Object>(); //这个用来存放需要的排序方式
params.add(true);
System.out.println(this.getQuery() + "asdjaskhfsk");
//判断来的页面是那个
if("true".equals(this.getQuery()))
{
//是从查询页面来的需求
//如果是查询的话,那么我们判定一下name是不是为空的
if(this.getName() != null &&!"".equals(this.getName().trim())) //后面那个trim是去掉空格的作用
{
//模糊查询一下
hsql.append(" and o.namelike ?");
params.add("%" + this.getName()+ "%"); //给问号赋值
}
}
QueryResult<Brand> qr =brandService.getScrollData(Brand.class, firstindex, pageview.getMaxresult(),hsql.toString(),
params.toArray(), orderby);
pageview.setQueryResult(qr);
request.put("pageView", pageview);
return "list";
}
public void setPage(int page)
{
this.page = page;
}
public int getPage()
{
return page < 1 ? 1 : page;
}
public BrandService getBrandService()
{
return brandService;
}
public void setBrandService(BrandService brandService)
{
this.brandService = brandService;
}
public String getQuery()
{
return query;
}
public void setQuery(String query)
{
this.query = query;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
}
修改功能图片路径
/**
* 显示类别修改界面
* @return String struts2的返回跳转result
* @throws Exception
*/
public String editUI() throws Exception
{
//取得相应的值传到修改的地方去
Map request = (Map) ActionContext.getContext().get("request");
Brand brand = brandService.find(Brand.class,this.getCode()); //获取相应的对象实体
name = brand.getName(); //获取要修改的对象的名字
logoimagepath = brand.getLogopath(); //得到图片路径
request.put("name", name);
request.put("logoimagepath", logoimagepath);
return"edit";
}
/**
* 类别修改操作
* @return
* @throws Exception
*/
public String edit() throws Exception
{
Map request = (Map) ActionContext.getContext().get("request");
//再上传之前判断上传图片类型是不是符合要求
if(!this.validateFileType("logofile"))
{
request.put("message", "图片格式不对");
return"message";
}
Brand brand = brandService.find(Brand.class,this.getCode()); //找到相应的对象
brand.setName(this.getName()); //新的名字
//判断文件是否获取,文件获取到,且长度大于0
if(this.getLogofile() != null && this.getLogofile().length() > 0) //如果重新填了新的图片,那么就修改为新的图片
{
//我们保存文件的格式是images/brand/2015/5/23/ssss.gif
//G:\Program Files\ApacheSoftware Foundation\Tomcat 8.0\webapps\babaSport_1100_brand\images\这个就是realpath
String realpath = ServletActionContext.getServletContext().getRealPath("/images");
//这里我们规定一下格式
SimpleDateFormat dateformat = newSimpleDateFormat("yyy\\MM\\dd\\HH");
String logopathdir = realpath + "brand\\" + dateformat.format(new Date()); //构建图片保存的目录
File logosavedir = newFile(logopathdir); //文件的保存路径
if(!logosavedir.exists())
{
//如果文件保存路径不存在,我们就创建这个路径
logosavedir.mkdirs();
}
//得到图片后缀
String ext = this.getLogofileFileName().substring(this.getLogofileFileName().lastIndexOf('.'));
//文件的名字
String showpath = "..\\" + logosavedir.toString().substring(logosavedir.toString().lastIndexOf("\\images"));
String imagename = UUID.randomUUID().toString() +ext; //构建文件名称
//这里用文件流来传进来
FileOutputStream fos = null;
FileInputStream fis = null;
try
{
String logopath = logosavedir + "\\" + imagename;
showpath += "\\" + imagename;
//建立文件输出流
fos = newFileOutputStream(logopath);
//建立文件上传流
fis = new FileInputStream(this.getLogofile());
//设定一个字节缓存
byte[] buffer = newbyte[2048];
int len = 0; //每次上传的长度
//不断地从文件上传流输出到输出流
while((len = fis.read(buffer)) != -1)
{
//输出
fos.write(buffer, 0, len);
}
brand.setLogopath(showpath);
}
catch (Exception e)
{
System.out.println("文件上传失败");
e.printStackTrace();
}
finally
{
this.close(fos, fis);
}
}
brandService.update(brand);
request.put("message", "修改品牌成功");
request.put("urladdress", SiteUrl.readUrl("control.brand.list"));
return"message";
}
ProductTypeManageAction.java
/**
* 功能:这个是品牌产品的管理动作
* 时间:2015年5月20日15:40:17
* 文件:ProductTypeManageAction.java
* 作者:cutter_point
*/
packagecom.cutter_point.web.action.product;
importjava.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.File;
importjava.io.FileInputStream;
importjava.io.FileOutputStream;
importjava.lang.reflect.Method;
importjava.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;
importjavax.annotation.Resource;
importorg.apache.commons.io.FileUtils;
importorg.apache.struts2.ServletActionContext;
importorg.springframework.context.annotation.Scope;
importorg.springframework.stereotype.Controller;
importcom.cutter_point.bean.product.Brand;
importcom.cutter_point.service.product.BrandService;
importcom.cutter_point.utils.SiteUrl;
importcom.opensymphony.xwork2.ActionContext;
importcom.opensymphony.xwork2.ActionSupport;
@Controller
@Scope("prototype")
public class BrandManageActionextends ActionSupport
{
@Resource
private BrandService brandService; //通过接口注入,aop默认的方式
private File logofile; //上传的文件
private String logofileContentType; //这个是struts2自动传进来的属性,文件的内容类型
private String logofileFileName; //这个是struts2自动传进来的属性,上传文件名
private String name; //上传的品牌的名字
private String code; //品牌代码
private String logoimagepath; //logo图片路径
/**
* 显示品牌添加界面
* @return Stringstruts2的返回跳转result
* @throws Exception
*/
public String addUI() throws Exception
{
return "add";
}
/**
* 品牌添加操作,上传文件方式2
* @return
* @throws Exception
*/
public String add2() throws Exception
{
Map request = (Map)ActionContext.getContext().get("request");
//我们保存文件的格式是images/brand/2015/5/23/ssss.gif
//G:\Program Files\Apache SoftwareFoundation\Tomcat 8.0\webapps\babaSport_1100_brand\images\ 这个就是realpath
String realpath =ServletActionContext.getServletContext().getRealPath("/images");
//这里我们规定一下格式
SimpleDateFormat dateformat = newSimpleDateFormat("yyy\\MM\\dd\\HH");
String logopath = realpath + "brand\\" +dateformat.format(new Date()); //构建图片保存的目录
Brand brand = new Brand();
brand.setName(this.getName());
//判断文件是否获取,文件获取到,且长度大于0
if(this.getLogofile() != null &&this.getLogofile().length() > 0)
{
File logosavedir = new File(logopath); //文件的保存路径
if(!logosavedir.exists())
{
//如果文件保存路径不存在,我们就创建这个路径
logosavedir.mkdirs();
}
//文件的名字
// String imagename =UUID.randomUUID().toString(); //构建文件名称
//文件输出到相应的目录,根据 parent 抽象路径名和 child 路径名字符串创建一个新File 实例。
File savefile = new File(logosavedir,this.getLogofileFileName());
FileUtils.copyFile(logofile, savefile);
}
brandService.save(brand);
request.put("message", "添加品牌成功");
return "message";
}
/**
* 品牌添加操作,上传文件方式1
* @return
* @throws Exception
*/
public String add() throws Exception
{
Map request = (Map)ActionContext.getContext().get("request");
//再上传之前判断上传图片类型是不是符合要求
if(!this.validateFileType("logofile"))
{
request.put("message", "图片格式不对");
return "message";
}
//我们保存文件的格式是images/brand/2015/5/23/ssss.gif
//G:\Program Files\Apache SoftwareFoundation\Tomcat 8.0\webapps\babaSport_1100_brand\images\ 这个就是realpath
String realpath = ServletActionContext.getServletContext().getRealPath("/images");
//这里我们规定一下格式
SimpleDateFormat dateformat = newSimpleDateFormat("yyy\\MM\\dd\\HH");
String logopathdir = realpath +"brand\\" + dateformat.format(new Date()); //构建图片保存的目录
Brand brand = new Brand();
brand.setName(this.getName());
//判断文件是否获取,文件获取到,且长度大于0
if(this.getLogofile() != null &&this.getLogofile().length() > 0)
{
File logosavedir = new File(logopathdir); //文件的保存路径
if(!logosavedir.exists())
{
//如果文件保存路径不存在,我们就创建这个路径
logosavedir.mkdirs();
}
//得到图片后缀
String ext =this.getLogofileFileName().substring(this.getLogofileFileName().lastIndexOf('.'));
//文件的名字
String showpath = "..\\" +logosavedir.toString().substring(logosavedir.toString().lastIndexOf("\\images"));
String imagename =UUID.randomUUID().toString() + ext; //构建文件名称
//这里用文件流来传进来
FileOutputStream fos = null;
FileInputStream fis = null;
try
{
String logopath = logosavedir +"\\" + imagename;
showpath += "\\" +imagename;
//建立文件输出流
fos = newFileOutputStream(logopath);
//建立文件上传流
fis = newFileInputStream(this.getLogofile());
//设定一个字节缓存
byte[] buffer = new byte[2048];
int len = 0; //每次上传的长度
//不断地从文件上传流输出到输出流
while((len = fis.read(buffer))!= -1)
{
//输出
fos.write(buffer, 0,len);
}
brand.setLogopath(showpath);
}
catch (Exception e)
{
System.out.println("文件上传失败");
e.printStackTrace();
}
finally
{
this.close(fos, fis);
}
}
brandService.save(brand);
request.put("message", "添加品牌成功");
request.put("urladdress",SiteUrl.readUrl("control.brand.list"));
return "message";
}
/**
* 显示类别修改界面
* @return Stringstruts2的返回跳转result
* @throws Exception
*/
public String editUI() throws Exception
{
//取得相应的值传到修改的地方去
Map request = (Map)ActionContext.getContext().get("request");
Brand brand = brandService.find(Brand.class,this.getCode()); //获取相应的对象实体
name = brand.getName(); //获取要修改的对象的名字
logoimagepath = brand.getLogopath(); //得到图片路径
request.put("name", name);
request.put("logoimagepath",logoimagepath);
return "edit";
}
/**
* 类别修改操作
* @return
* @throws Exception
*/
public String edit() throws Exception
{
Map request = (Map)ActionContext.getContext().get("request");
//再上传之前判断上传图片类型是不是符合要求
if(!this.validateFileType("logofile"))
{
request.put("message","图片格式不对");
return"message";
}
Brand brand = brandService.find(Brand.class,this.getCode()); //找到相应的对象
brand.setName(this.getName()); //新的名字
//判断文件是否获取,文件获取到,且长度大于0
if(this.getLogofile() != null &&this.getLogofile().length() > 0) //如果重新填了新的图片,那么就修改为新的图片
{
//我们保存文件的格式是images/brand/2015/5/23/ssss.gif
//G:\Program Files\Apache SoftwareFoundation\Tomcat 8.0\webapps\babaSport_1100_brand\images\ 这个就是realpath
String realpath =ServletActionContext.getServletContext().getRealPath("/images");
//这里我们规定一下格式
SimpleDateFormat dateformat = newSimpleDateFormat("yyy\\MM\\dd\\HH");
String logopathdir = realpath +"brand\\" + dateformat.format(new Date()); //构建图片保存的目录
File logosavedir = new File(logopathdir); //文件的保存路径
if(!logosavedir.exists())
{
//如果文件保存路径不存在,我们就创建这个路径
logosavedir.mkdirs();
}
//得到图片后缀
String ext =this.getLogofileFileName().substring(this.getLogofileFileName().lastIndexOf('.'));
//文件的名字
String showpath = "..\\" +logosavedir.toString().substring(logosavedir.toString().lastIndexOf("\\images"));
String imagename =UUID.randomUUID().toString() + ext; //构建文件名称
//这里用文件流来传进来
FileOutputStream fos = null;
FileInputStream fis = null;
try
{
String logopath = logosavedir +"\\" + imagename;
showpath += "\\" +imagename;
//建立文件输出流
fos = newFileOutputStream(logopath);
//建立文件上传流
fis = newFileInputStream(this.getLogofile());
//设定一个字节缓存
byte[] buffer = new byte[2048];
int len = 0; //每次上传的长度
//不断地从文件上传流输出到输出流
while((len = fis.read(buffer))!= -1)
{
//输出
fos.write(buffer, 0,len);
}
brand.setLogopath(showpath);
}
catch (Exception e)
{
System.out.println("文件上传失败");
e.printStackTrace();
}
finally
{
this.close(fos, fis);
}
}
brandService.update(brand);
request.put("message", "修改品牌成功");
request.put("urladdress",SiteUrl.readUrl("control.brand.list"));
return "message";
}
/**
* 显示类别查询界面
* @return Stringstruts2的返回跳转result
* @throws Exception
*/
public String queryUI() throws Exception
{
return "query";
}
/**
* 这儿函数用来验证上传的文件类型是不是符合要求的
* @return
*/
public boolean validateFileType(String propertyName) throwsException
{
//得到相应类的所有属性,字段
PropertyDescriptor[] propertydesc =Introspector.getBeanInfo(this.getClass()).getPropertyDescriptors();
boolean exsit = false; //判断属性是否存在的变量
for(PropertyDescriptor property : propertydesc) //相当于类里面的属性,字段
{
if(property.getName().equals(propertyName))
{
//名字得到匹配的话,属性是存在
exsit = true;
Method method =property.getReadMethod(); //取得用来读取属性的方法,也就是取得get方法
if(method != null)
{
File file = (File)method.invoke(this); //执行这个方法
//文件是存在的
if(file != null&& file.length() > 0)
{
List<String>arrowType = Arrays.asList("image/bmp", "image/png", "image/gif","image/jpeg", "image/pjpe", "image/jpg");
boolean b =arrowType.contains(this.getLogofileContentType().toLowerCase()); //判断类型是不是在里面,用小写比较
return b;
}
}
else
{
//如果文件没有穿进来
newRuntimeException(propertyName + "属性的getter方法不存在");
}
}
}
if(!exsit)
new RuntimeException(propertyName +"属性的不存在");
return true; //如果没有上传文件的话,还是让他通过
}
//管理文件流
protected void close(FileOutputStream fos, FileInputStreamfis)
{
if(fis != null)
{
try
{
fis.close();
}
catch (Exception e)
{
System.out.println("关闭文件输入流失败");
e.printStackTrace();
}
}
if(fos != null)
{
try
{
fos.close();
}
catch (Exception e)
{
System.out.println("关闭文件输出流失败");
e.printStackTrace();
}
}
}
public File getLogofile()
{
return logofile;
}
public void setLogofile(File logofile)
{
this.logofile = logofile;
}
public BrandService getBrandService()
{
return brandService;
}
public void setBrandService(BrandService brandService)
{
this.brandService = brandService;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getLogofileContentType()
{
return logofileContentType;
}
public void setLogofileContentType(StringlogofileContentType)
{
this.logofileContentType = logofileContentType;
}
public String getLogofileFileName()
{
return logofileFileName;
}
public void setLogofileFileName(String logofileFileName)
{
this.logofileFileName = logofileFileName;
}
public String getCode()
{
return code;
}
public void setCode(String code)
{
this.code = code;
}
public String getLogoimagepath()
{
return logoimagepath;
}
public void setLogoimagepath(String logoimagepath)
{
this.logoimagepath = logoimagepath;
}
}
SiteUrl.java
/**
* 功能:获取配置文件里面的属性
* 时间:2015年5月24日20:52:02
* 文件:SiteUrl.java
* 作者:cutter_point
*/
packagecom.cutter_point.utils;
import java.io.IOException;
import java.util.Properties;
public class SiteUrl
{
public static String readUrl(String key)
{
Properties properties = new Properties(); //得到属性类型的集合类
//获取属性的集合
try
{
//得到这个类的类加载路径,然后根据这个类加载器的路径找到对应的配置文件
properties.load(SiteUrl.class.getClassLoader().getResourceAsStream("config/properties/siteurl.properties"));
}
catch (IOException e)
{
e.printStackTrace();
}
return (String) properties.get(key); //根据key值获取相应的属性值
}
}
Siteurl.properties
control.brand.list=brandlist
control.producttype.list=producttypelist
显示界面
edit_brand.jsp
<%@ page isELIgnored="false"contentType="text/html;charset=UTF-8" %>
<%@ taglib uri="/struts-tags"prefix="s" %>
<html>
<head>
<title>修改品牌</title>
<meta http-equiv="Content-Type"content="text/html; charset=UTF-8">
<link rel="stylesheet"href="/css/vip.css" type="text/css">
<SCRIPT language=JavaScript src="/js/FoshanRen.js"></SCRIPT>
<script language="JavaScript">
function checkfm(form){
if (trim(form.name.value)==""){
alert("品牌名称不能为空!");
form.name.focus();
return false;
}
if (byteLength(form.note.value)>200){
alert("图片名不能大于200字!");
form.note.focus();
return false;
}
return true;
}
</script>
</head>
<body bgcolor="#FFFFFF"text="#000000" leftmargin="0" topmargin="0"marginwidth="0" marginheight="0">
<s:form action="brandmanage-edit" method="post" enctype="multipart/form-data" οnsubmit="returncheckfm(this)">
<s:hidden name="code" value="%{#request.code}"/>
<br>
<table width="90%"border="0" cellspacing="2"cellpadding="3" align="center">
<tr bgcolor="6f8ac4">
<td colspan="2" ><fontcolor="#FFFFFF">修改品牌:</font></td>
</tr>
<tr bgcolor="f5f5f5">
<td width="22%" ><div align="right">品牌名称:</div></td>
<td width="78%"><input type="text"name="name" value="${name }"size="50" maxlength="50"/>
<fontcolor="#FF0000">*</font>
</td>
</tr>
<tr bgcolor="f5f5f5">
<td width="22%" >
<div align="right">Logo图片:</div>
</td>
<td width="78%">
<input type="file" name="logofile"size="50" maxlength="100"/>
<s:if test="%{#request.logoimagepath != null}">
<img src="${logoimagepath}" width="200" />
</s:if>
<s:if test="%{#request.logoimagepath == null}">
NOLogo!
</s:if>
</td>
</tr>
<tr bgcolor="f5f5f5">
<td colspan="2"><div align="center">
<input type="submit" value=" 确定 " class="frm_btn">
</div></td>
</tr>
</table>
</s:form>
<br>
</body>
</html>
query_brand.jsp
<%@ page isELIgnored="false"contentType="text/html;charset=UTF-8" %>
<%@ taglib uri="/struts-tags" prefix="s"%>
<html>
<head>
<title>品牌查询</title>
<meta http-equiv="Content-Type"content="text/html; charset=UTF-8">
<link rel="stylesheet"href="/css/vip.css" type="text/css">
<SCRIPT language=JavaScript src="/js/FoshanRen.js"></SCRIPT>
<script language="JavaScript">
function checkfm(form){
if (trim(form.name.value)==""){
alert("品牌名称不能为空!");
form.name.focus();
return false;
}
return true;
}
</script>
</head>
<body bgcolor="#FFFFFF"text="#000000" leftmargin="0" topmargin="0"marginwidth="0" marginheight="0">
<s:form action="brandlist" method="post" οnsubmit="returncheckfm(this)">
<s:hidden name="query" value="true"/>
<table width="90%"border="0" cellspacing="2"cellpadding="3" align="center">
<tr bgcolor="6f8ac4"><td colspan="2"><fontcolor="#FFFFFF">查询品牌:</font></td>
</tr>
<tr bgcolor="f5f5f5">
<td width="22%" ><div align="right">品牌名称:</div></td>
<td width="78%"><input type="text"name="name" size="50"maxlength="40" />
<fontcolor="#FF0000">*</font></td>
</tr>
<tr bgcolor="f5f5f5">
<td colspan="2"><div align="center">
<input type="submit" value=" 确定 " class="frm_btn">
</div></td>
</tr>
</table>
</s:form>
<br>
</body>
</html>
4、struts2的配置
<?xml version="1.0"encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD StrutsConfiguration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<include file="struts-default.xml" />
<constant name="struts.ObjectFactory" value="spring" /><!-- 表示这里面的action由spring进行创建 -->
<constant name="struts.devMode" value="true" />
<!--解决乱码 -->
<constant name="struts.i18n.encoding" value="UTF-8" />
<package name="control" namespace="/control"extends="struts-default">
<global-results>
<result name="message">/page/share/message.jsp</result>
</global-results>
<action name="center-*"><!-- 直接跳转,不需要经过class的验证,默认返回success -->
<result name="success">/page/controlcenter/{1}.jsp</result>
</action>
<!-- 产品类别展示 -->
<action name="producttypelist" class="productTypeAction" method="execute">
<result name="list">/page/product/producttypelist.jsp</result>
</action>
<!-- 产品类别管理 -->
<action name="*-producttypemanage" class="productTypeManageAction" method="{1}UI">
<result name="{1}">/page/product/{1}_productType.jsp</result>
</action>
<action name="producttypemanage-*" class="productTypeManageAction" method="{1}">
<result name="{1}">/page/product/{1}_productType.jsp</result>
</action>
<!-- 品牌类别展示 -->
<action name="brandlist" class="brandAction"method="execute">
<result name="list">/page/product/brandlist.jsp</result>
</action>
<!-- 品牌类别管理 -->
<action name="*-brandmanage" class="brandManageAction" method="{1}UI">
<result name="{1}">/page/product/{1}_brand.jsp</result>
</action>
<action name="brandmanage-*" class="brandManageAction" method="{1}">
<result name="{1}">/page/product/{1}_brand.jsp</result>
</action>
</package>
</struts>
5、接下来我们测试一下页面的效果
我们访问这个网站
http://localhost:8080/babaSport_1200_brand_edit_find/control/center-main
查询
然后我们的修改功能
关于网站为什么要这样写,上几篇blog有介绍
6、总结
这里我们做的就是如何把图片上传到服务器,修改的时候验证格式,并且修改路径,查询的时候可以根据名字模糊查询