SpringMVC獲取前端資料的四種方法
阿新 • • 發佈:2018-11-09
在獲取資料之前先說下註解,註解的功能大家都知道,不再多說,這裡說下如何使用
首先,我們需要在springmvc-servlet.xml檔案中新增
<!--開啟註解掃描功能-->
<mvc:annotation-driven/>
<!--定義註解掃描的包-->
<context:component-scan base-package="com.jie.controller"/>
下面介紹獲取前端資料的幾種方法
1.req.getParameter()
這個和servlet中的使用一樣
@RequestMapping("/login") public ModelAndView login(HttpServletRequest req, HttpServletResponse resp){ String userName=req.getParameter("n"); String userPwd=req.getParameter("p"); UserService service=new UserService(); boolean r=service.isLogin(userName,userPwd); ModelAndView mv=null; if (r) { System.out.println("登入成功!"); mv=new ModelAndView("list"); mv.addObject("msg","登入成功"); }else { System.out.println("登入失敗!"); mv=new ModelAndView("index"); mv.addObject("msg","登入失敗"); } return mv; }
service類
package com.jie.service;
public class UserService {
//登入
public boolean isLogin(String userName,String userPwd){
if (userName.equals("jie")&&userPwd.equals("123123"))
return true;
return false;
}
}
user類
package com.jie.dao; public class User { private int userId; private String userName; private String userPwd; public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getUserPwd() { return userPwd; } public void setUserPwd(String userPwd) { this.userPwd = userPwd; } public int getUserId() { return userId; } public void setUserId(int userId) { this.userId = userId; } public User() { } public User(String userName, String userPwd) { this.userName = userName; this.userPwd = userPwd; } }
前端的jsp頁面直接使用el表示式接受資料就行,這裡不再寫
2.通過形參直接接收
@RequestMapping("/login1")
public ModelAndView login1(int userId,String userName,String userPwd){
System.out.println(userId+" "+userName+" "+userPwd);
return new ModelAndView("list");
}
如果遇到前後端傳值不同時使用@RequestParam(),例如:
@RequestMapping("/login11")
public ModelAndView login11(@RequestParam("id") int userId, String userName, String userPwd){
System.out.println(userId+" "+userName+" "+userPwd);
return new ModelAndView("list");
}
3.通過物件接收
@RequestMapping("/login2")
public ModelAndView login2(User user){
ModelAndView mv=new ModelAndView("index");
mv.addObject("user",user);
return mv;
}
4.位址列傳參 restful
@RequestMapping("/delete/{id}")
public ModelAndView delete(@PathVariable("id") int userId){
System.out.println(userId);
return new ModelAndView("list");
}
最後:解決中文亂碼
在web.xml檔案中配置過濾器
<!--filter過濾器 解決中文亂碼問題-->
<filter>
<filter-name>characterEncoding</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>characterEncoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>