我的意图是创建一个Spring 3 MVC web客户端和Spring MVC REST提供程序。
这是我的REST提供者的代码:
@RequestMapping("employee")
public class EmployeeController {
@Autowired
EmployeeDAO empDao;
@RequestMapping(value = "authenticateUser", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public String authenticateUser(HttpServletRequest request, @RequestParam Employee employee) {
String username = employee.getEmpCode();
String password = employee.getPassword();
String notExisting = "notExisting";
String successLogin = "successLogin";
String wrongPassword = "wrongPassword";
Employee retrievedEmployee = empDao.getById(username);
if(retrievedEmployee == null) {
return notExisting;
} else {
if(retrievedEmployee.getPassword().equals(password)) {
return successLogin;
} else {
return wrongPassword;
}
}
}
}
这里是我的网络客户端的代码:
@Controller
public class UserAuthenticationController {
private final static String SERVICEURL = "http://localhost:8080/cimweb";
/**
* Simply selects the home view to render by returning its name.
*/
@RequestMapping(value = "/userAuthentication", method = RequestMethod.POST)
public @ResponseBody String userAuthentication(Locale locale, Model model, HttpServletRequest request) {
Employee employee = new Employee();
String username = request.getParameter("username");
String password = request.getParameter("password");
employee.setEmpCode(username);
employee.setPassword(password);
// Prepare acceptable media type
List<MediaType> acceptableMediaTypes = new ArrayList<MediaType>();
acceptableMediaTypes.add(MediaType.APPLICATION_JSON);
HttpHeaders headers = new HttpHeaders();
headers.setAccept(acceptableMediaTypes);
HttpEntity<Employee> entity = new HttpEntity<Employee>(employee, headers);
RestTemplate restTemplate = new RestTemplate();
String url = SERVICEURL + "/employee/authenticateUser";
try {
ResponseEntity<Employee> result = restTemplate.exchange(url, HttpMethod.POST, entity, Employee.class);
} catch(Exception e) {
e.printStackTrace();
}
return "home";
}
}
我只想将对象Employee传递给REST提供程序,这样我就可以处理它,并将String从REST提供程序返回给客户端。
每次调试时,当我到达提供程序时,我都会得到null。
我知道我错过了很多东西,也读过一些,但我看到的大多是来自提供者的直接请求,而不是对象。
此外,我应该将任何必需的bean放在servlet-context.xml中吗?
问题的原因:
-
如果您想通过
@RequestParam
接受控制器中的数据,那么请求应该包含数据作为请求参数。想想包含?empCode=xyz&password=abc
的url。或在请求正文中作为empCode=xyz&password=abc
-
按照在客户端代码中发送
Employee
对象的方式,该对象将被序列化到请求体中。使用您提供的代码,客户端将发出一个请求,其中employee对象在请求体中转换为其JSON表示。您的控制器方法无法读取某些内容。(假设类路径中有映射jackson-jars)
可能的解决方案:
-
更改控制器方法签名,而不是
@RequestParam
,使用@RequestBody
,它告诉Spring从请求体中提取Employee
对象的值。它将检测到这是一个json请求,它将在上下文中查找一个jsonHttp消息转换器,并创建您的员工对象。 -
第二种选择是保留控制器签名,但更改发出请求的方式。在客户端中,实例化
RestTemplate
实例后,将Form Http Message转换器设置为其converters属性。这将告诉客户端像表单提交一样对数据进行POST。您的@RequestParam
带注释的控制器方法参数可以读取该参数。
希望这能有所帮助。