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. 進入;入口;條目;登記;報關手續;對土地的侵佔*/
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章