SpringMVC-提高篇-UerController

package net.jbit.controller;


import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;


import net.jbit.entity.User;
import net.jbit.entity.UserException;


import org.apache.commons.io.FileUtils;
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.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.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;


/*只要打上@Controller扫描器就自动会扫描到她*/
@Controller
public class UerController {

private Map<String, User> map = new HashMap<String, User>();


/*无参的构造方法,创建Controller时自动执行了。*/
public UerController() {
User user1 = new User("Tom", "1234");
User user2 = new User("Jim", "1234");
User user3 = new User("Lily", "1234");
map.put(user1.getUserName(), user1);
map.put(user2.getUserName(), user2);
map.put(user3.getUserName(), user3);
}

/*============================================*/



/*查多*/
@RequestMapping(value = "/cha")
public ModelAndView cha(){
/*如果返回结果是ModelAndView那就必须先创建一个ModelAndView*/
/*注意:ModelAndView有两个包,一定要导org.springframework.web.servlet.ModelAndView;*/
ModelAndView mv = new ModelAndView();
/*循环迭代的时候是迭代HashMap的值集合*/
mv.addObject("key", map.values());
mv.setViewName("list");
return mv;
}

/*返回一个json对象*/
/*加上params就是说同样输入cha,有参数的进入这个方法,没参数的进入上一个方法*/
/*@RequestMapping(value = "/cha", method = RequestMethod.GET, params = "json" )
如果向往页面反对象必须加上@ResponseBody
做ajax的时候经常用@ResponseBody返回结果写入到http response body的数据区内
@ResponseBody
public User chaByJson(){
XXXX
从前台往后台传json(传过来一个字符串,变成json)
得到一个json对象
JSONObject jo = JSONObject.formObject(string);  
把json对象转化成User对象

}*/



/*========================================================================*/
/*跳转到增加的页面*/
@RequestMapping(value = "/ab")
/*如果用第二种方法,进入页面之前要确认一下User是有值的。要先实例化一下*/
/*Model就相当于request和response,可以往里面传参*/
public String addBefore(Model model){
model.addAttribute(new User());
return "add";
}



/*增加1*/
/*通过传统的servlet来接收页面传过来的值*/
/*前台用的是普通的from表单控件*/
/*也支持session*/
/*@RequestMapping(value = "/add")
public String save(HttpServletRequest request, HttpSession session){
String userName = request.getParameter("userName");
String password = request.getParameter("password");
取完之后封装到user里面
User user = new User(userName, password);
map.put(user.getUserName(), user);
跳回到查询方法里,从而进入查询页面
return "redirect:/cha";
}*/


/*zzzzzzzzzzzzzzzzzzzzzzzz*/



/*单文件上传*/
/*增加2*/
/*页面数据直接绑定实体类的属性*/
/*method表示这个方法要干什么*/
/*GET:查询*/
/*POST:增加*/
/*DELETE:删除*/
/*PUT:修改*/
/*@RequestMapping(value = "/add", method = RequestMethod.POST)
上传的文件会自动绑定到MultipartFile里
通过HttpServletRequest得到文件上传路径
public String save(User user, MultipartFile attach, HttpServletRequest request){
指定上传位置
String uploadFilePath = request.getSession().getServletContext().getRealPath("/statics/upload");
System.out.println(attach.getOriginalFilename());
System.out.println(attach.getContentType());
System.out.println(attach.getName());

上传
try {
if (!attach.isEmpty()) {
建一个saveFile空文件
File.separator代替“/”自动识别是windows还是linux等
File saveFile = new File(uploadFilePath + "/" + attach.getOriginalFilename());
FileUtils.copyInputStreamToFile(attach.getInputStream(), saveFile);
}

catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


增加
map.put(user.getUserName(), user);
跳回到查询方法里,从而进入查询页面
return "redirect:/cha";
}*/


/*zzzzzzzzzzzzzzzzzzzzzzzz*/



/*多文件上传*/
/*增加2*/
/*页面数据直接绑定实体类的属性*/
/*method表示这个方法要干什么*/
/*GET:查询*/
/*POST:增加*/
/*DELETE:删除*/
/*PUT:修改*/
@RequestMapping(value = "/add", method = RequestMethod.POST)
/*上传的文件会自动绑定到MultipartFile[]数组里*/
/*通过HttpServletRequest得到文件上传路径*/
/*多文件上传必须加@RequestParam*/

public String save(User user, @RequestParam MultipartFile[] attachs, HttpServletRequest request){
/*指定上传位置*/
String uploadFilePath = request.getSession().getServletContext().getRealPath("/statics/upload");


/*上传*/
try {
for (MultipartFile attach : attachs) {

if (!attach.isEmpty()) {
/*建一个saveFile空文件*/
/*File.separator代替“/”自动识别是windows还是linux等*/
File saveFile = new File(uploadFilePath + File.separator + attach.getOriginalFilename());
FileUtils.copyInputStreamToFile(attach.getInputStream(), saveFile);
}
}


catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


/*增加*/
map.put(user.getUserName(), user);
/*跳回到查询方法里,从而进入查询页面*/
return "redirect:/cha";
}
/*========================================================================*/



/*删除*/
/*用rest风格接收前台传过来的参数*/
@RequestMapping(value = "del/{myname}", method = RequestMethod.DELETE)
/*@PathVariable是路径参数*/
public String del(@PathVariable(value = "myname") String myname){
map.remove(myname);
return "redirect:/cha";



/*========================================================================*/


/*修改*/

/*查单条*/
@RequestMapping(value = "one/{name}", method = RequestMethod.GET)
/*如果要往页面传值的话要借助Model*/
/*Model的作用域和request是一样的*/
public String one(@PathVariable(value = "name") String name, Model model){
User user = map.get(name);
model.addAttribute(user);
return "update";
}


/*改*/
@RequestMapping(value = "/one/{name}", method = RequestMethod.POST )
public String update(@PathVariable(value="name") String name,User user){
map.put(name, user);
return "redirect:/cha";
}

/*======================================================*/
/*登陆*/
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String login(@RequestParam String userName, @RequestParam String password, HttpSession session){

/*比对(输入的和原有的进行比对)*/
/*遍历map*/
/*如果登录不成功要抛出一个异常*/
boolean flag = false;

/*方式1:map.values();*/
for (User user : map.values()) {
if(userName.equals(user.getUserName()) && password.equals(user.getPassword())){
System.out.println("登录成功!!!");
session.setAttribute("loginUser", user);
flag = true;
break;
}
}
/*自定义一个异常类*/
if(flag == false){
throw new UserException("用户名或密码不正确,请从新输入!");
}




/*方式2:map.keySet()*/
/*for(String key : map.keySet()){
System.out.println("key:" + key + " value:" + map.get(key).getUserName());
}*/




/*方式3:map.entrySet() iterator*/
/*大数据量推荐使用iterrator*/
/*Iterator<Map.Entry<String, User>> it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, User> entry= it.next();
System.out.println("key:" + entry.getKey() + " value:" + entry.getValue().getUserName());
}*/





/*方式4:map.entrySet()*/
/*for (Map.Entry<String, User> entry : map.entrySet()) {
System.out.println("key:" + entry.getKey() + " value:" + entry.getValue().getUserName());
}*/



/*还有forward:*/
return "redirect:/cha";

}



/*=========================*/

/*局部异常处理:只针对某一个controller*/
/*value里面是个数组,可以写好几个异常*/
/*注意:有了全局异常就不能有局部异常的代码了*/


/*@ExceptionHandler(value = {UserException.class})
要在页面上输出异常信息还需要有一个Request对象
public String handlerException(UserException e, HttpServletRequest request){
request.setAttribute("e", e);
return "error";
}*/

}




 /*============================================================*/
/*单词*/
/*entry[ˈɒntreɪ]n. 进入;入口;条目;登记;报关手续;对土地的侵占*/
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章