逐个接收:参数名与形参名相同,按名称对象接收参数
参数类型最好是包装类型
package com.mumu.config;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class HelloSpringMvc {
@RequestMapping(value = "/some")
public ModelAndView doSome(String id,String name){
ModelAndView mv=new ModelAndView();
// 添加数据
mv.addObject("msg",name);
mv.addObject("fun",id);
//指定要执行的视图的完整路劲
mv.setViewName("show");
return mv;
}
}
出现乱码问题 用字符集过滤器解决
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
当形参名与参数名不符时 则使用注解RequestParam 它里面有两个属性 一个是value 表示传递过来的参数的名字,required 表示允不允许用户传递空值过来 默认不允许true
package com.mumu.config;
import org.springframework.context.annotation.Bean;
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;
@Controller
public class HelloSpringMvc {
@RequestMapping(value = "/some")
public ModelAndView doSome(@RequestParam(value = "myid") String id,
@RequestParam(value = "myname",required = true) Integer name){
ModelAndView mv=new ModelAndView();
// 添加数据
mv.addObject("msg",name);
mv.addObject("fun",id);
//指定要执行的视图的完整路劲
mv.setViewName("show");
return mv;
}
}
对象传值
@RequestMapping("/test")
public ModelAndView two(User user){
ModelAndView mdv=new ModelAndView();
mdv.addObject("myname",user.getName());
mdv.addObject("myage",user.getAge());
mdv.setViewName("show");
return mdv;
}
}
springmvc返回值
ModelAndView;即跳转资源 也可以传递参数
String ; 跳转到指定的视图文件名
@PostMapping("/login")
public String index(User user, HttpSession session, Model model){
if (StringUtils.hasLength(user.getUsername()) && StringUtils.hasLength(user.getPasswrod())){
//把登录成功的用户保存起来
session.setAttribute("loginuser",user);
//重定项 意思是登录成功 重定项到index.html
return "redirect:/index.html";
}else{
model.addAttribute("msg","账号或密码错误");
return "login";
}
}
/**
* 去index页面
* @return
*/
@GetMapping("/index.html")
public String indexPage(HttpSession session,Model model){
//如果登录框和密码框不为空 则允许登录
Object obj=session.getAttribute("loginuser");
if (obj!=null){
return "index";
}else {
model.addAttribute("msg","账号或密码错误");
return "login";
}
// if ()
}
返回类型对象Object 可以是List 对象 Map String Integer…
这些都是数据,而ajax需要的就是数据