package cn.itcast_01_springmvc.controller;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.Map;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.tomcat.util.codec.binary.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import com.google.gson.Gson;
import cn.itcast_01_springmvc.dao.UserDao;
import cn.itcast_01_springmvc.exception.LackParamException;
import cn.itcast_01_springmvc.pojo.User;
//Controller 负责处理由DispatcherServlet 分发的请求,它把用户请求的
//数据经过业务处理层处理之后封装成一个Model ,然后再把该Model 返回给对应的View
//进行展示。在SpringMVC 中提供了一个非常简便的定义Controller 的方法,然后
//使用@RequestMapping 和@RequestParam 等一些注解用以定义URL请求和Controller 方法之间的映射,这样的Controller 就能被外界访问到。
@Controller
// 这里将user的信息存入session,只将字符存入session,当然可以放在方法上面
// @SessionAttributes(value = { "user" }, types = { String.class })
public class UserController {
@Autowired
private UserDao userDao;
// @RequestMapping(value = "/form")
// public String test() {
// return "user/form";
// }
//
// @RequestMapping(value = "/save1")
// public String save1(User user) {
// System.out.println(user.toString());
// return "home";
// }
//
// // 将数据传到前台ModelAndView
// @RequestMapping(value = "/edit1")
// public ModelAndView edit1() {
// User user = new User();
// user.setUser("Bob");
// user.setPass("123");
// user.setAge(12);
// user.setEmail("123@qq.com");
// Address address = new Address();
// address.setCity("成都");
// address.setProvince("四川");
// user.setAddress(address);
// ModelAndView mv = new ModelAndView();
// mv.setViewName("user/form");
// mv.addObject("user", user);
// return mv;
// }
//
// // 将数据传到前台Map
// @RequestMapping(value = "/edit2")
// public String edit2(Map<String, Object> map) {
// User user = new User();
// user.setUser("Lisa");
// user.setPass("123");
// user.setAge(12);
// user.setEmail("123@qq.com");
// Address address = new Address();
// address.setCity("成都");
// address.setProvince("四川");
// user.setAddress(address);
// map.put("user", user);
// return "user/form";
// }
//
// // 将数据传到前台Model
// @RequestMapping(value = "/edit3")
// public String edit3(Model model) {
// User user = new User();
// user.setUser("Lucy");
// user.setPass("123");
// user.setAge(12);
// user.setEmail("123@qq.com");
// Address address = new Address();
// address.setCity("成都");
// address.setProvince("四川");
// user.setAddress(address);
// model.addAttribute("user", user);
//
// model.addAttribute("str1", "session1");
// model.addAttribute("str2", "session2");
// return "user/form";
// }
/////////////// RESTful///////////////
@RequestMapping(value = "/users", method = RequestMethod.GET)
public String list(Model model) {
Collection<User> userList = userDao.getAll();
model.addAttribute("userList", userList);
System.out.println("users");
//int a=Integer.parseInt("as");
//int b=2/0;
// 显示列表页
return "user/list";
}
// 保持restful风格,获取资源
@RequestMapping(value = "/user", method = RequestMethod.GET)
public String add() {
// 打开增加页
return "user/add";
}
// 保持restful风格,新建资源
@RequestMapping(value = "/user", method = RequestMethod.POST)
public String save(User user) {
userDao.save(user);
// 执行插入
System.out.println(user);
return "redirect:/users";
}
@RequestMapping(value = "/user/{id}", method = RequestMethod.DELETE)
public String delete(@PathVariable(value = "id") Integer id) throws LackParamException {
// 执行删除
userDao.delete(id);
return "redirect:/users";
}
@RequestMapping(value = "/user/{id}", method = RequestMethod.GET)
public String edit(@PathVariable(value = "id") Integer id, Model model){
User users = userDao.get(id);
model.addAttribute("users", users);
// 打开回显页
return "/user/edit";
}
@RequestMapping(value = "/user/{id}", method = RequestMethod.PUT)
public String update(@PathVariable(value = "id") Integer id, User users) {
users.setId(id);
userDao.save(users);
// 执行更新
return "redirect:/users";
}
@RequestMapping(value = "/saveuser", method = RequestMethod.POST)
public String saveUser(User users) {
System.out.println(users);
userDao.save(users);
return "redirect:/users";
}
/////////////// json与jsonp///////////////
// @responseBody注解的作用是将controller的方法返回
// 的对象通过适当的转换器转换为指定的格式之后,写入到response对象的body区
@ResponseBody
@RequestMapping(value = "/users-json", method = RequestMethod.GET)
public Collection<User> listJson() {
return userDao.getAll();
}
@RequestMapping(value = "/users-jsonp", method = RequestMethod.GET)
public void listJsonp(String callback, HttpServletResponse response) throws IOException {
Collection<User> list = userDao.getAll();
Gson gson = new Gson();
String json = gson.toJson(list);
response.getWriter().println(callback + "(" + json + ")");
}
// 通过@requestBody可以将请求体中的JSON字符串绑定到相应的bean上
@RequestMapping(value = "/savejson", method = RequestMethod.POST)
public String saveJsonp(@RequestBody User users) throws IOException {
System.out.println(users);
userDao.save(users);
return "redirect:/users";
}
/////////////// 异常处理///////////////
//括号内容表示只处理数据转换异常,可以不写则为处理全部异常
//@ExceptionHandler(NumberFormatException.class)
//自定义类异常
@ExceptionHandler(LackParamException.class)
public ModelAndView handleException(Exception e){
System.out.println(e);
ModelAndView mv=new ModelAndView();
mv.setViewName("error");
mv.addObject("exception",e);
return mv;
}
//自定义异常测试
@RequestMapping(value = "/test_exception")
public String testException(String str) throws LackParamException {
if (org.springframework.util.StringUtils.isEmpty(str)) {
throw new LackParamException();
}
return "home";
}
/////////////// 文件上传///////////////
@RequestMapping(value = "/fileupload")
public String fileupload(String desc,MultipartFile file,Model model) throws IllegalStateException, IOException {
System.out.println(desc);
System.out.println(file);
System.out.println(file.getOriginalFilename());
if(file!=null&&file.getOriginalFilename()!=null&&file.getOriginalFilename().length()>0){
String filepath="D:/Project resources/springMVC/";
String origName=file.getOriginalFilename();
//扩展名
String extendsName=origName.substring(origName.lastIndexOf("."));
//文件名
String newFileName=UUID.randomUUID().toString()+extendsName;
//文件
File uploadFile=new File(filepath+newFileName);
file.transferTo(uploadFile);
model.addAttribute("filepath","/file/"+newFileName);
}
return "success";
}
}