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)