1. 程式人生 > >SpringMVC中的一些註解

SpringMVC中的一些註解

gmv pub pan else bsp break () 獲取參數 false

@Controller:表明該類是一個Controller;

@RequestMapping(參數) :為類或者方法定義一個url

@RequestParam(value = "id" ):獲取請求中的參數

package com.hongcong.controller;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; import com.hongcong.model.StudentModel; @Controller
//訪問這個controller時,需要在url中加入/student @RequestMapping(
"/student") public class StudentController { private static List<StudentModel> studentList = new
ArrayList<StudentModel>(); private int id =3; static{ studentList.add(new StudentModel(1,"張三",11)); studentList.add(new StudentModel(2,"李六",13)); studentList.add(new StudentModel(3,"王五",14)); }
  //訪問這個方法時,url為../student/studentList @RequestMapping(
"/studentList")
public ModelAndView studentList(){
     //ModelAndView的作用是傳遞參數和頁面跳轉 ModelAndView mav
= new ModelAndView();
     //跳轉到student目錄下的studentList.jsp頁面 註:lib目錄下的頁面無法直接訪問 mav.setViewName(
"student/studentList");
     //傳遞參數 頁面可以通過jstl表達式等方法獲取參數 mav.addObject(
"studentList", studentList); return mav; } @RequestMapping("/preSave")
   //@RequestParam(value = "otype",required = false) String otype 是獲取請求中的參數並且賦值給otype這個變量,其中參數required = true時,那這個請求必須要有otype參數,不然會報錯
public ModelAndView preSave(@RequestParam(value = "id" ) int id, @RequestParam(value = "otype",required = false) String otype){ ModelAndView mav = new ModelAndView(); StudentModel studentModel = new StudentModel(); if("update".equals(otype)){ for (StudentModel model : studentList) { if(model.getId() == id){ studentModel = model; break; } } } mav.addObject("studentModel", studentModel); mav.setViewName("student/StudentUpdate"); return mav; } @RequestMapping("/Save") public String Save(StudentModel studentModel){ if(studentModel.getId() == 0){ this.id++; studentModel.setId(this.id); }else{ for (StudentModel model : studentList) { if(id == model.getId()){ studentList.remove(model); break; } } studentModel.setId(id); } studentList.add(studentModel);
     //重定向
return "redirect:/student/studentList.do"; } }

SpringMVC中的一些註解