平时写项目很多的在后台遇见request.getAttribute(),偶然在看一个项目的时候,看到了这个EL表达式(jsp注释处是我自己改写的试了试)
<div><spring:message code="Message"></spring:message><font color="purple" size="12">${requestScope.okok}<%--此处这么写为先加载出NULL=request.getAttribute("okok")--%></font></div>
后台相关代码如下
@RequestMapping("/Upload")
public void Upload(HttpServletRequest request,
HttpServletResponse response)throws Exception {
InputStream is = null;
String tempDir = null;
request.setCharacterEncoding("utf-8");
//String filename=request.getParameter("pdf");
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
//3 解析request
List<FileItem> list = null;
try {
list = upload.parseRequest(request);
} catch (FileUploadException e) {
e.printStackTrace();
throw new RuntimeException("您操作有误!");
}
//4 遍历FileItem
if(list!=null){
for(FileItem item : list){
if(!item.isFormField()){
//是文件上传
// 将文件保存到 项目根目录下的upload文件夹中
// 获得upload文件夹路径
String uploadPath ="D:\\SSM上传下载\\Upload\\";
// 生成名称
String filename=new File(item.getName()).getName();
int f=filename.lastIndexOf('.');
filename=filename.substring(0, f);
System.out.println(filename);
is = item.getInputStream();
FileOutputStream os = new FileOutputStream(uploadPath+filename+".pdf",true);
IOUtils.copy(is, os);
tempDir = uploadPath+filename+".pdf";
System.out.println(filename);
System.out.println(tempDir);
//InputStreamToString ists = new InputStreamToString();
//checkSexImgb64 = ists.GetImageStrI(is);
//System.out.println("is" + is);
//System.out.println("checkSexImgb64" + checkSexImgb64);
//5 保存访问路径到Product对象中
//p.setImgurl("/uploadImgSex"+datePath+filename); // /upload/2015/08/25/xxxxxxxxx
//删除临时文件
is.close();
os.close();
item.delete();
}
else{
//是普通表单项
String idid = item.getString();
if("pdf_name".equals(item.getFieldName())) {
idid = item.getString();}
System.out.println(idid);
System.out.println(tempDir);
try {
teachService.Upload(idid,tempDir);
request.setAttribute("okok", "上传成功");
} catch (Exception e) {
request.setAttribute("okok", "上传失败");
e.printStackTrace();
}
}
}
}
后来发现,改成<%=request.getAttribute("okok")%>在未执行后台方法的时候会显示一个NULL(也很好理解,页面加载的时候JSP代码就已经执行,“okok”还没有内容)。
当然这只是我所见识到的一种差异。
关于它们用法的区别,也找了一些比较优秀的理解:
在我们平常开发中经常会碰到需要把后台数据库中查询到的数据源展现到界面上,这时候我们就会用到EL表达式中的requestScope标签。首先关于requestscope的定义是:是EL表达式的隐藏对象,包含request作用域内变量的Map。
例如:使用<jsp:useBean id="person" class="bean.Person"/>声明了person对象后,使用${requestScope.person.age}将输出person的age属性。
关于requestscope和request.getParameter()
requestscope主要用于数据的展示,从request隐藏对象中取出对象或者变量来显示。而request中的对象或变量是通过request.setAttribute方法放入request对象中的。
request.getParameter则更多的应用于后台方法中,它的参数是由表单接受用户输入的之后提交请求时被放入到request对象中。