星空网 > 软件开发 > Java

SpringMVC(三)

1.视图和视图解析器

请求处理方法执行完成后,最终返回一个 ModelAndView 对象

对于那些返回 String,View 或 ModeMap 等类型的处理方法,SpringMVC 也会在内部将它们装配成一个 ModelAndView 对象,它包含了逻辑名和模型对象的视图

Spring MVC 借助视图解析器(ViewResolver)得到最终的视图对象(View),最终的视图可以是 JSP ,也可能是 Excel、JFreeChart等各种表现形式的视图

SpringMVC(三)

【自定义视图】:一般不需要

1).自定义视图,实现view接口或者继承AbstractView抽象类,并加入到IOC容器中。

@Componentpublic class MyView implements View{  @Override  public String getContentType() {   return "text/html";  }  @Override  public void render(Map<String, ?> arg0, HttpServletRequest request, HttpServletResponse response) throws Exception {   response.getWriter().println("12345678");   response.setContentType("text/html;charset=utf8");   System.out.println("1234");  }}

 

@Componentpublic class MyView extends AbstractView{  @Override  protected void renderMergedOutputModel(Map<String, Object> arg0, HttpServletRequest request, HttpServletResponse response)     throws Exception {   // TODO Auto-generated method stub   response.getWriter().println("12345678");   response.setContentType("text/html;charset=utf8");   System.out.println("1234");  }}

 2).在springmvc配置文件中配置BeanNameViewResolver视图解析器。

<bean >	<property name="order" value="100"></property></bean>

 3).注意:每个视图解析器都实现了 Ordered 接口并开放出一个 order 属性,可 以通过 order 属性指定解析器的优先顺序,order 越小优先级越高。SpringMVC 会按视图解析器顺序的优先顺序对逻辑视图名进行解析,直到解析成功并返回视图对象,否则将抛出 ServletException 异常

 

2.数据格式化标签

1) 在SpringMVC配置文件中配置<mvc:annotation-driven/>2) 在目标POJO对象的属性上加上@NumberFormat 或者 @DateTimeFormat 注解!     @DateTimeFormat        –    pattern 属性:类型为字符串。指定解析/格式化字段数据的模式, 如:”yyyy-MM-dd hh:mm:ss”     @NumberFormat        –pattern:类型为 String,自定义样式, 如patter="#,###";   规定输入格式
@DateTimeFormat(pattern="yyyy-MM-dd")private Date birth;@NumberFormat(pattern="#,###")private Integer salary;

 

3.Spring的表单标签

     通过 SpringMVC 的表单标签可以实现将模型数据 中的属性和 HTML 表单元素相绑定,以实现表单数据更便捷编辑和表单值的回显。
    
     一般情况下,通过 GET 请求获取表单页面,而通过 POST 请求提交表单页面,因此获取表单页面和提交表单 页面的 URL 是相同的。只要满足该最佳条件的契 约,<form:form> 标签就无需通过 action 属性指定表单 提交的 URL

     可以通过 modelAttribute 属性指定绑定的模型属性,若没有指定该属性,则默认从 request 域对象中读取 command 的表单 bean,如果该属性值也不存在,则会 发生错误
   
     SpringMVC 提供了多个表单组件标签,如<form:input/>、<form:select/> 等,用以绑定表单字段的属性值,它们的共有属性如下:          – path:表单字段,对应 html 元素的 name 属性,支持级联属性     form:input、form:password、form:hidden、form:textarea:对应 HTML 表单的 text、password、hidden、textarea标签     form:radiobutton:单选框组件标签,当表单 bean 对应的 属性值和 value 值相等时,单选框被选中     form:radiobuttons:单选框组标签,用于构造多个单选框          –items:可以是一个 List、String[] 或 Map
          –itemValue:指定 radio 的 value 值。可以是集合中 bean 的一个属性值
          –itemLabel:指定 radio 的 label 值
          –delimiter:多个单选框可以通过 delimiter 指定分隔符
              表单标签               form:checkbox:复选框组件。用于构造单个复选框               form:checkboxs:用于构造多个复选框。使用方式同 form:radiobuttons 标签               form:select:用于构造下拉框组件。使用方式同 form:radiobuttons 标签               form:option:下拉框选项组件标签。使用方式同 form:radiobuttons 标签               form:errors:显示表单组件或数据校验所对应的错误          – <form:errors path= “ *” /> :显示表单所有的错误          – <form:errors path= “ user*” /> :显示所有以 user 为前缀的属性对应的错误          – <form:errors path= “ username” /> :显示特定表单对象属性的错误       
     当需要表单回显或者使用下拉列表的时候,就使用form表单标签,而如果使用遍历的标签就使用JSTL标签【导包】!

 

4.数据类型转换以及数据格式化标签

     数据类型转换【了解】      1). 自定义类型转换器实现Converter<S,T>接口并加入到SpringMVC的IOC容器中
@Componentpublic class MyConverter implements Converter<String,Student>{	@Override	public Student convert(String source) {		System.out.println(source);		if(source != null){			String[] spilt = source.split("-");			if(spilt != null && spilt.length ==2){				String name = spilt[0];				Integer gender = Integer.parseInt(spilt[1]);				Student student = new Student();				student.setName(name);				student.setGender(gender);				return student;			}		}		return null;	}}

       2).配置自定义转换器到FormattingConversionServiceFactoryBean工厂中!

<!-- 配置ConversionService --><bean id="conversionService" >	<property name="converters">		<set>			<ref bean="myConverter"/>		</set>	</property></bean><!-- 将ConversionService再作为annotation-driven的一个属性存在! --><mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven>

 

5.SpringMVC如何处理JSON数据

     1).加入json的3个jar包          jackson-annotations-2.1.5.jar          jackson-core-2.1.5.jar          jackson-databind-2.1.5.jar    2). 编写目标方法,使其返回 JSON 对应的对象或集合    3). 在方法上添加 @ResponseBody 注解
@RequestMapping(value="/testJson",method=RequestMethod.POST)@ResponseBodypublic List<Student> getList(){	List<Student> stu = new ArrayList<Student>();	stu.add(new Student("aa", 1, null, null));	stu.add(new Student("bb", 2, null, null));	stu.add(new Student("cc", 3, null, null));	return stu;}

 

<script type="text/javascript" src='/images/loading.gif' data-original="${pageContext.request.contextPath }/script/jquery-1.9.1.min.js"></script><script type="text/javascript">	$(function(){		$("#btn").click(function(){			var url = "${pageContext.request.contextPath }/testJson";			var data = {};			function callback(data1){				for(var i=0;i<data1.length;i++){					alert(data1[i].id+"---"+data1[i].name);				}			}			$.post(url,data,callback);		});	});</script>

 

6.文件上传

Spring MVC 上下文中默认没有为文件上传提供了直接的支持,因此默认情况下不能处理文件的上传工作,如果想使用 Spring 的文件上传功能,需现在上下文中配置 CommonsMultipartResovler:    1).加入jar包:        commons-fileupload-1.3.1.jar        commons-io-2.4.jar     2).在SpringMVC配置文件中配置CommonsMultipartResovler      
<!-- 配置CommonsMultipartResolver --><bean id="multipartResolver" >	<property name="defaultEncoding" value="utf-8"></property>	<property name="maxUploadSize" value="510000"></property></bean>

     3).表单:POST请求,file类型,enctype="multipart/form-data"

<form action="${pageContext.request.contextPath }/testUpload" method="post" enctype="multipart/form-data">	file:<input type="file" name="photo"/><br/>	desc:<input type="text" name="desc"/><br/>	<input type="submit" value="Submit"/></form>

 

@RequestMapping(value="/testUpload")public String testUpload(@RequestParam(value="desc") String desc,@RequestParam("photo") CommonsMultipartFile file,HttpServletRequest request) throws Exception{	System.out.println(desc);	System.out.println(file.getOriginalFilename());			ServletContext servletContext = request.getServletContext();  String realPath = servletContext.getRealPath("/upload");  File file1 = new File(realPath);  if(!file1.exists()){   file1.mkdir();  }  OutputStream out;  InputStream in;  //uuid_name.jpg  String prefix = UUID.randomUUID().toString();  prefix = prefix.replace("-","");  String fileName = prefix+"_"+file.getOriginalFilename();  System.out.println(fileName);  out = new FileOutputStream(new File(realPath+"\\"+fileName));  in = file.getInputStream();  IOUtils.copy(in, out);  out.close();  in.close();  return "success";}

 

原标题:SpringMVC(三)

关键词:Spring

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流