我是Java新手。试图创建简单的CRUD应用程序。但是在DB中添加记录时遇到问题,获取request.getParameter()null。我正在使用针对RESTful Web服务的jersey和针对json数据使用Gson。
见下面的代码。
爪哇
let obj = {
['name']: 'Your Name',
};
let myName = 'name';
let anotherObj = {
[myName]: 'Your Name ',
};
console.log(obj.name); // Your Name
console.log(anotherObj.name); // Your Name
AngularJS
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
System.out.println(request.getParameterMap());
if (request.getParameterMap().containsKey("id")) {
String id = request.getParameter("id");
System.out.println(id);
}
String firstname = request.getParameter("firstname");
int id = Integer.parseInt(request.getParameter("id"));
String lastname = request.getParameter("lastname");
int phone = Integer.parseInt(request.getParameter("phone"));
String jobId = request.getParameter("jobId");
Double salary = Double.parseDouble(request.getParameter("salary"));
Employee e = new Employee();
e.setFirstname(firstname);
e.setId(id);
e.setLastname(lastname);
e.setPhone(phone);
e.setJobId(jobId);
e.setSalary(salary);
int status=EmployeeDao.add(e);
if(status > 0){
System.out.println("Record added successfully!");
}else{
System.out.println("Unable to add record");
}
out.close();
}
答案 0 :(得分:1)
修改
@Santosh,正如我在评论中提到的,你可以用两种方式做到这一点。方法1 ::在JS中单独发送参数。
$http({
method : 'POST',
url : 'AddResource',
data: 'id=' + id + 'firstname=' + firstname,
headers: { 'Content-Type': 'text/plain' }
}).then(function successCallback(response) {
if(response.data){
$scope.getEmployee();
}
}, function errorCallback(response) {
console.log("Data not coming");
});
然后你可以用Java提取它们
request.getParameter('id');
request.getParameter('firstname');
方法2 ::作为对象发送并在Java中分割
$http({
method : 'POST',
url : 'AddResource',
data: 'empObj=' + empObj,
headers: { 'Content-Type': 'text/plain' }
}).then(function successCallback(response) {
if(response.data){
$scope.getEmployee();
}
}, function errorCallback(response) {
console.log("Data not coming");
});
然后你可以用Java提取对象
String JSON = request.getParameter('empObj');
使用像Gson这样的解析器来解析这个JSON。
Gson gson = new Gson();
Employee empObj = gson.fromJson(JSON, Employee.class);
答案 1 :(得分:1)
您正在将内容类型设置为application/json
。 ServletRequest.getParameter()州的文档
以String形式返回请求参数的值,如果是,则返回null 参数不存在。请求参数是额外信息 随请求发送。对于HTTP servlet,参数包含在 查询字符串或发布的表单数据。
尝试省略Content-Type参数以使用getParameter(),或者获取请求正文并从那里解析JSON字符串。
//编辑:显然,angular默认为application / json,因此省略content-type将无效。要对数据进行表单编码,请参阅此问题:How do I POST urlencoded form data with $http?
答案 2 :(得分:1)
如果您使用的是json数据流,则不能使用request.getParameter("firstname");
来获取json参数,您需要读取原始数据。
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
StringBuffer strJson = new StringBuffer();
String line = null;
try {
BufferedReader reader = request.getReader();
while ((line = reader.readLine()) != null) {
strJson.append(line);
}
Employee employee = new GsonBuilder().create().fromJson(strJson.toString(), Employee.class);
int status=EmployeeDao.add(employee);
if(status > 0){
System.out.println("Record added successfully!");
}else{
System.out.println("Unable to add record");
}
out.close();
} catch(Exception ex) {
}
}
答案 3 :(得分:0)
修改使用angular生成的请求,将对象作为json字符串传递给正文,如:
employer="{id:1,\"firstname\":\"John\",....}"
在servlet中:
String jsonString = request.getParameter("employer");
Gson gson = new Gson();
Employee empObj = gson.fromJson(jsonString, Employee.class);
您也可以使用pojo或EJB并将其作为Web服务公开,在我看来这是一个更简单灵活的解决方案
@Stateless
@Path(value = "employer")
@PermitAll
public class EmployerController {
... some object or injections
@Path(value = "insert")
@Consumes("application/x-www-form-urlencoded")
@Produces(MediaType.APPLICATION_JSON)
@POST
public T create(@FormParam("employer")String entity)throws ValidationException, Exception{
ObjectMapper mapper = new ObjectMapper();
ObjectNode j;
try {
j = (ObjectNode) mapper.readTree(entity);
Employer myemp = mapper.readValue(j, Employer.class);
...do what you need...
return myemp;
} catch(Exception e){
LOG.log(Level.SEVERE,"Error",e);
throw e;
}
}
}
或者以一种更奇特的方式,你可以实现一个方法" fromString(String json)"像这样
public static MyEmpl fromString(String jsonString) throws IOException{
ObjectMapper mapper = new ObjectMapper();
MyEmpl object = mapper.readValue(jsonString, MyEmpl.class);
return object;
}
然后将以前的方法定义为:
public T create(@FormParam("employer")MyEmpl entity)throws Exception{
和反序列化器(例如,jacklf in wildlfy)做了神奇的事情