在获取数据之前先说下注解,注解的功能大家都知道,不再多说,这里说下如何使用
首先,我们需要在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>