我的意图是创建一个 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 提供者,以便我可以处理它并将字符串从 REST 提供者返回给客户端。
每次我调试这个时,当我到达提供者时,我都会得到空值。
我知道我错过了很多东西,我已经阅读了一些,但我看到的大部分都是来自提供者的直接请求,而不是对象。
此外,我应该将任何必需的 bean 放在我的 servlet-context.xml 中吗?