前端使用vue或者axios发送post请求,服务器使用springMVC框架,使用HttpServletRequest.getParameter()获取参数一直为null.
照着网上在前端框架设置axios请求头如下,但是并不起作用,谷歌浏览器中还是application/json.
//设置全局的
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
var instance = axios.create({}) // 这样创建出来的 只需要:
instance.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
1,在springmvc-servlet.xml文件中新增代码
<!-- 文件上传,id必须设置为multipartResolver -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 设置文件上传大小 5M -->
<property name="maxUploadSize" value="5000000" />
</bean>
2.pom.xml中新增依赖
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
3,前端代码也定义为POST请求,很多地方说要修改前端的Content-Type.但是谷歌浏览器并不起作用,还是Content-Type=application/json.所以修改Content-Type并不可取
4,Controller文件中定义为POST请求方式,也就是@RequestMapping(value = "/login", method = RequestMethod.POST)
使用@RequestBody接收参数.这里请注意,要使用Employee employee这样的参数体.不能使用单个参数体
比如:public Map<String,Object> doLogin(@RequestBody String login_name) .
//登录根据用户名和密码登录
@ResponseBody
@RequestMapping(value = "/login", method = RequestMethod.POST)
//public Map<String,Object> doLogin(@RequestBody String login_name,@RequestBody String password) { //这样会导致前端访问404.
public Map<String,Object> doLogin(@RequestBody Employee employee) {
Map<String, Object> rspinfo = new HashMap<String, Object>();
String login_name=employee.getLogin_name();//获取login_name
String password=employee.getPassword();//获取password
System.out.println("login_name="+login_name);
System.out.println("password="+password);
if (login_name == null || password == null) {
rspinfo.put("code", 10001);
rspinfo.put("msg", "login_name或者password不能为空");
return rspinfo;
}
Employee findEmployee = new Employee();
findEmployee.setLogin_name(login_name);
findEmployee.setPassword(password);
findEmployee.setStatus(status);
findEmployee.setIs_deleted(is_deleted);
Employee rspEmployee = employeeService.getSearchOne(findEmployee);
//System.out.println(books);
if (rspEmployee == null) {
rspinfo.put("code", 1001);
rspinfo.put("msg", "账号密码不正确");
} else {
rspinfo.put("code", 200);
rspinfo.put("msg", "登录成功");
rspinfo.put("data", rspEmployee);
}
return rspinfo;
}
5,如果使用postman测试工具,选择POST请求格式,Body请求体中的raw,并传递JSON格式

完成上面的配置,springMVC就可以接收到前端传的参数了.
网友评论