标签:
文件上传
1,在servlet.xml下配置
<bean id = "mutipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="1024000"></property>
</bean>
2,在form配置
//action中是接下来访问的函数。
<body>
<form action="test/pers0.do" method="post" enctype="multipart/form-data">
name:<input name="name" type="text"> <br>
age:<input name="age" type="text"> <br>
address:<input name="adress" type="text"> <br>
<input name="name" type="submit" value="submit"><br>"
pic:<input type="file" name="pic"/>
</form>
</body>
3 代码中
@RequestMapping(value="/toPerson8.do")
public String toPerson8(Person person,HttpServletRequest request) throws Exception{
//第一步转化request
MultipartHttpServletRequest rm = (MultipartHttpServletRequest) request;
//获得文件
CommonsMultipartFile cfile = (CommonsMultipartFile) rm.getFile("pic");
//获得文件的字节数组
byte[] bfile = cfile.getBytes();
String fileName = "";
//获得当前时间的最小精度
SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmssSSS");
fileName = format.format(new Date());
//获得三位随机数
Random random = new Random();
for(int i = 0; i < 3; i++){
fileName = fileName + random.nextInt(9);
}
//获得原始文件名
String origFileName = cfile.getOriginalFilename();
//XXX.jpg
String suffix = origFileName.substring(origFileName.lastIndexOf("."));
//拿到项目的部署路径
String path = request.getSession().getServletContext().getRealPath("/");
//定义文件的输出流
OutputStream out = new FileOutputStream(new File(path+"/upload/"+fileName+suffix));
out.write(bfile);
out.flush();
out.close();
return "jsp1/index";
}
拦截器
三层拦截
1配置拦截器,在springmvc.xml
<mvc:interceptors>
<mvc:interceptor>
<!-- /**拦截所有请求 -->
<mvc:mapping path="/**"/>
<bean class="cn.icast.springmvc.interceptor.myIn"></bean>
</mvc:interceptor>
</mvc:interceptors>
2java文件
package cn.icast.springmvc.interceptor;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
public class myIn implements HandlerInterceptor {
@Override
//最终拦截,执行时机,视图已经被解析完毕,只要做监控方面的工作,追踪错误 ,类似于finally
public void afterCompletion(HttpServletRequest arg0,
HttpServletResponse arg1, Object arg2, Exception ex)
throws Exception {
System.out.println("after");
// TODO Auto-generated method stub
}
//后置拦截,执行时机,controller之后,视图解析器没有把视图解析成界面
@Override
public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
Object arg2, ModelAndView mv) throws Exception {
//对视图做统一的修改
Map<String,Object> map = mv.getModel();
map.put("test","append something");
System.out.println("pothandle");
// TODO Auto-generated method stub
}
//前置拦截,执行时机,在这些controller之前来执行
//主要对权限进行拦截
@Override
public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1,
Object arg2) throws Exception {
// TODO Auto-generated method stub
System.out.println("preHandle");
return true;
}
}
Spting mvc - 4
标签:
原文地址:http://www.cnblogs.com/hitxx/p/4849640.html