`
TRAMP_ZZY
  • 浏览: 132280 次
社区版块
存档分类
最新评论

Spring 3.x Web MVC 实例

阅读更多
package cn.tramp.iblog.web;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.DateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import javax.xml.transform.stream.StreamResult;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.oxm.Marshaller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.util.FileCopyUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.WebUtils;

import cn.tramp.iblog.domain.FormatUser;
import cn.tramp.iblog.domain.User;
import cn.tramp.iblog.service.BlogService;
import cn.tramp.iblog.service.UserService;
import cn.tramp.iblog.utils.Page;

import com.google.gson.Gson;

/**
 * Handles requests for the application home page.
 */
@Controller
@SessionAttributes("user")
public class HomeController {
	
	private static final Log logger  = LogFactory.getLog(HomeController.class);
	private Gson gson = new Gson();
	
	@Autowired
	private UserService userService;
	@Autowired
	private BlogService blogService;
	@Autowired
	private Marshaller marshaller;
	
	/**
	 * Simply selects the home view to render by returning its name.
	 */
	@RequestMapping(value = "/index", method = RequestMethod.GET)
	public String home(Locale locale, Model model) {
		logger.info("Welcome home! The client locale is " +locale+ ".");
		
		Date date = new Date();
		DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
		
		String formattedDate = dateFormat.format(date);
		
		Page<User> page = new Page<User>();
		page.setTotalRecord(1);
		page.setCurrentPage(1);
		page.setPageSize(10);
		
		User user = userService.getUserById(8);
		
		try {
			
			FileOutputStream os = new 
					FileOutputStream("e:/test/xxxx.xml");
			
			this.marshaller.marshal(user, new StreamResult(os));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		System.out.println(user.toString());
		
		userService.getUserByPage(page);

		List<User> list = page.getDatas();
		
		//userService.addUser(null);
		
		model.addAttribute("serverTime", formattedDate );
		model.addAttribute("USER", user);
		model.addAttribute("LIST", list);
		
		return "home";
		
	}
	
	@RequestMapping("/userlistexcel")
	public String showUserListInExcel(ModelMap mm) {
		Page<User> page = new Page<User>();
		page.setTotalRecord(1);
		page.setCurrentPage(1);
		page.setPageSize(10);
		userService.getUserByPage(page);
		List<User> list = page.getDatas();
		mm.addAttribute("LIST", list);
		return "userListExcel";
	}
	
	@RequestMapping("/userlistpdf")
	public String showUserListInPdf(ModelMap mm) {
		Page<User> page = new Page<User>();
		page.setTotalRecord(1);
		page.setCurrentPage(1);
		page.setPageSize(10);
		userService.getUserByPage(page);
		List<User> list = page.getDatas();
		mm.addAttribute("LIST", list);
		return "userListPdf";
	}
	
	// WEB MVC
	@RequestMapping(value = "/handle1", method = RequestMethod.GET, headers = "content-type=text/*",params = {"param1=value1", "params"})
	public String handle1(@RequestParam(value = "userName", required = false, defaultValue = "zhang") String userName,
					@RequestParam("age") int age) {
		
		return null;
	}
	
	// CookieValue 获取Cookie的值
	@RequestMapping("handle2")
	public String handle2(
				@CookieValue(value = "sessionId", required = false) String sessionId,
				@RequestParam("age") int age) {
		return null;
	}
	
	// RequestHEader 获取header 的内容
	public String handle3(
				@RequestHeader("Accept-Encoding") String encoding,
				@RequestHeader("Keep-Alive") long keepAlive) {
		return null;
	}
	
	// 支持级联的属性名 adpt.id adpt.address.id
	@RequestMapping(value = "handle4")
	public String handle4(User user) {
		return null;
	}
	
	@RequestMapping("/handle5")
	public void handle5(HttpServletRequest request, HttpServletResponse response) {
		String userName = WebUtils.findParameterValue(request, "userName");
		response.addCookie(new Cookie("userName", userName));
	}
	
	@RequestMapping("/value6")
	public ModelAndView handle6(HttpServletRequest request) {
		String name = WebUtils.findParameterValue(request, "name");
		ModelAndView view = new ModelAndView("result");
		view.addObject("name", name);
		return view;
	}
	
	@RequestMapping("/value7")
	public String handle7(HttpSession session,
				@RequestParam("userId") int userId) {
		return null;
	}
	
	// 提供代理类可以访问请求对象的任何信息
	@RequestMapping("/value8")
	public String handle8(WebRequest request) {
		return null;
	}
	
	@RequestMapping("/handle9")
	public void handler9(OutputStream os) throws IOException {
		Resource res = new ClassPathResource("/image/1.jpg");
		FileCopyUtils.copy(res.getInputStream(), os);
	}
	
	// 使用 HttpMessageConverter<T> 将请求信息转化被绑定到处理方法的入参中
	// 1 @RequestBody @ResponseBody 对处理方法标注
	// 2 HttpEntity<T> ResponseEntity<T> 作为入参或返回值
	@RequestMapping("/handle10")
	public String handle10(@RequestBody String requestBody) {
		// 将请求报文体转化为字符串绑定到 requestBody
		System.out.println(requestBody);
		return null;
	}
	
	@ResponseBody
	@RequestMapping("/handle11/{imageId}")
	public byte[] handle11(@PathVariable("imageId") String imageId) throws IOException {
		// 读取一张图片 客户端将显示这张图片
		Resource resource = new ClassPathResource("image/" + imageId);
		byte[] fileData = FileCopyUtils.copyToByteArray(resource.getInputStream());
		// 将文件保存
		Resource outFile = new FileSystemResource("E://test//001.jpg");
		FileCopyUtils.copy(resource.getFile(), outFile.getFile());
		return fileData;
	}
	
	// Spring MVC 根据HttpEntity泛型的类型调用对应的HttpMessageConverter
	@RequestMapping("/handle12")
	public String handle12(HttpEntity<String> httpEntity) {
		HttpHeaders header = httpEntity.getHeaders();
		long contentLength = httpEntity.getHeaders().getContentLength();
		System.out.println(httpEntity.getBody());
		return null;
	}
	
	public ResponseEntity<byte[]> handle13(
					@PathVariable("imageId") String imageId) throws IOException {
		Resource res = new ClassPathResource("/image/001.jpg");
		byte[] fileData = FileCopyUtils.copyToByteArray(res.getInputStream());
		ResponseEntity<byte[]> responseEntity = 
				new ResponseEntity<byte[]>(fileData, HttpStatus.OK);
		return responseEntity;		
	}
	/*
	 * 当控制器处理方法使用上述注解或类型时,Spring 首先根据请求头或响应头的Accept 属性选择匹配的
	 * HttpMessageConverter,进而根据参数类型或泛型类型的过滤得到匹配的Converter。找不到,报异常。
	 */
	
	// 处理XML 和 JSON
	/*
	 * 只需要在Spring Web 容器中为AnnotationMEthodHandlerAdapter 装配好相应的处理XML JSON 的Converter
	 * 并在交互过程中通过Accept指定MIME Spring MVC 就可以是服务端的处理方法和客户端透明地通过XML或JSON格式
	 * 的消息进行通信
	 */
	
	// 根据Accept处理JSON XML
	// 根据Content-type 确定请求数据的格式 根据Accept 确定相应的消息格式
	@RequestMapping("/handler14")
	public ResponseEntity<User> handler14(HttpEntity<User> requestEntity) {
		User user = requestEntity.getBody();
		user.setUser_id(100);
		return new ResponseEntity<User>(user, HttpStatus.OK);
	}
	
	/*
	 * @ModelAttribute 方法入参标注该注解后,入参的对象就会放到数据模型中
	 * 入参为 Map Model 或 ModelMap时,处理完毕后,数据自动添加到模型中
	 * 在方法体中可以通过上述Model 访问到模型中的所属数据
	 * @SessionAttribute 将模型中的某个属性暂时放到HttpSession 中,多个
	 * 请求之间可以共享该属性。 
	 * Spring MVC 会将模型数据转储到ServletRequest 的属性列表中
	 * 
	 */
	
	@RequestMapping("/handler15")
	public String handler15(@ModelAttribute("user") User user) {
		return null;
	}
	
	@ModelAttribute("user")
	public User getUSer() {
		return new User();
	}
	
	@RequestMapping("/handler16")
	public String handler16(ModelMap model) {
		model.addAttribute("attr", "zhang");
		User user = (User) model.get("user");
		return null;
	}
	
	public String handler17(ModelMap modelMap, SessionStatus sessionStatus) {
		User user = (User) modelMap.get("user");
		if (user != null) {
			// Spring MVC 清除本处理器对应的Session属性
			sessionStatus.setComplete();
		}
		
		return null;
	}
	
	/*
	 * 需要导入annotation 和hibernate 注解包
	 * Spring 是通过对处理方法签名的规约来保存校验结果的。前一个表单/命令对象的
	 * 校验结果保存在其后的入参中,这个保存校验结果的入参必须是BindingResult 或
	 * Errors 类型 。 成对出现的。
	 * 校验结果会保存到隐含模型中,即使入参中没有对应的结果对象,校验结果也不会丢失。
	 * 
	 */
	@RequestMapping("/handler18")
	public String hander18(@Valid @ModelAttribute("user") FormatUser user,
						BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return "error";
		}
		return "success";
	}
	
	
}

分享到:
评论

相关推荐

    Spring MVC 入门实例

    9 import org.springframework.web.servlet.mvc.Controller; 10 import org.springframework.web.servlet.ModelAndView; 11 12 import javax.servlet.http.HttpServletRequest; 13 import javax.servlet....

    Spring.3.x企业应用开发实战(完整版).part2

    16.7.3 使用Spring RestTemplate测试 16.7.4 使用Selenium测试 16.8 小结 第17章 实战案例开发 17.1 论坛案例概述 17.1.1 论坛整体功能结构 17.1.2 论坛用例描述 17.1.3 主要功能流程描述 17.2 系统设计 17.2.1 技术...

    springweb3.0MVC注解(附实例)

    web.xml 中定义了一个名为 annomvc 的 Spring MVC 模块,按照 Spring MVC 的契约,需要在 WEB-INF/annomvc-servlet.xml 配置文件中定义 Spring MVC 模块的具体配置。annomvc-servlet.xml 的配置内容如下所示: ...

    Spring+3.x企业应用开发实战光盘源码(全)

     第3章:讲解Spring IoC容器的知识,通过具体的实例详细地讲解IoC概念。同时,对Spring框架的三个最重要的框架级接口进行了剖析,并对Bean的生命周期进行讲解。  第4章:讲解如何在Spring配置文件中使用Spring 3.0...

    Spring3.x企业应用开发实战(完整版) part1

    16.7.3 使用Spring RestTemplate测试 16.7.4 使用Selenium测试 16.8 小结 第17章 实战案例开发 17.1 论坛案例概述 17.1.1 论坛整体功能结构 17.1.2 论坛用例描述 17.1.3 主要功能流程描述 17.2 系统设计 17.2.1 技术...

    Spring Boot 2.X 实战教程.pdf

    本课程内容包括Spring简介、Spring Boot简介、安装JDK、安装Maven、第一...Web MVC框架(安装Postman、自定义欢迎页面、Icon、错误页面)、安装MySQL数据库和客户端、配置数据源、Spring Data JPA代码、Spring Data ...

    一个简单的spring mvc实例.docx

    如果你手上有一本《Spring in Action》, 那么你最好从第三部分"Spring 在 Web 层的应用--建立 Web 层"开始看, 否则那将是一场恶梦! 首先, 我需要在你心里建立起 Spring MVC 的基本概念. 基于 Spring 的 Web 应用...

    Spring MVC框架实例

    基于spring2.5的采用XML配置的spring MVC项目

    springmvc的一个简单实例

    spring的mvc应用的简单实例 package com.spring.mvc.controller; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype....

    Spring MVC 框架应用实例

    org.springframework.web.context.ContextLoaderListener &lt;filter-name&gt;encodingFilter org.springframework.web.filter.CharacterEncodingFilter &lt;param-name&gt;encoding ...

    spring_mvc搭建实例

    一个动态的java web 工程,使用了spring_mvc框架搭建了一个小小的实例,愿和大家一起共享之,谢谢。希望能帮助到搭建,最近也在打算再次使用spring_mvc框架,却发现网上却少有实例可以提供参考,故而得空自己写了一...

    Spring 2.5 jar 所有开发包及完整文档及项目开发实例

    另外,对Struts 1.x的支持被独立成 'spring-webmvc-struts.jar'。 注意:经常被使用的的Spring的DispatcherServlet也是Spring Web MVC框架中的一部分。因此,就算你只是为了远程访问(例如,暴露Hessian或者 HTTP...

    陈开雄 Spring+3.x企业应用开发实战光盘源码.zip

    陈开雄 Spring+3.x企业应用开发实战光盘源码 !!!!压缩包的jar包太多,太大无法上传,请谅解,需要的可以联系我 QQ:349721489 第1章:对Spring框架进行宏观性的概述,力图使读者建立起对Spring整体性的认识。 ...

    webspring-mvc.rar

    webspring-mvc源码实例,实现了注解,拦截器等实例

    spring3.1中文参考文档

    第二部分 Spring 3的新特性............................................................................................................................. 22 第2章 Spring 3.0的新特性和增强 ..................

    spring web mvc + mybatis

    spring web mvc + mybatis + mysql简单实例,很简单,希望能帮到大家

    Java Web开发实例大全

    Java Web开发实例大全(提高卷)筛选、汇集了Java Web开发从基础知识到高级应用各个层面的大量实例及源代码,共有600个左右,每个实例及源代码按实例说明、关键技术、设计过程、详尽注释、秘笈心法的顺序进行了分析...

    Spring 2.0 开发参考手册

    13.1.2. Spring Web MVC框架的特点 13.2. DispatcherServlet 13.3. 控制器 13.3.1. AbstractController 和 WebContentGenerator 13.3.2. 其它的简单控制器 13.3.3. MultiActionController 13.3.4. 命令控制器 ...

    spring-hibernate-dwr实例

    webmvc.jar spring-portlet.jar struts.jar commons-fileupload.jar commons-httpclient.jar freemarker.jar jasperreports-1.3.3.jar commons-io.jar portlet-api.jar jxl.jar itext...

    spring_mvc代码_spring_mvc代码实例_

    SpringMVC 是一种基于 Java 的实现 MVC 设计模型的请求驱动类型的轻量级 Web 框架,属于SpringFrameWork的后续产品,已经融合在 Spring Web Flow 中

Global site tag (gtag.js) - Google Analytics