SpringMVC中的一些注解

@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"; } }
原文地址:https://www.cnblogs.com/hongcong/p/7586624.html