我尝试将数据插入数据库但得到内部服务器错误java.lang.NullPointerException
我创建自己的spring MVC可能与其他
不同我认为发生错误是因为模型没有从正文中获取数据,因此在调用save方法时会发生空指针异常错误
这里是代码
CONTROLLER
@RestController
public class SellerController {
@Autowired
SellerService service;
@RequestMapping(method = RequestMethod.POST, path = "sellers/register",
consumes = "application/json", produces = "application/json")
public ResponsePost postSellerRegister(@RequestBody SellerPost model){
ResponsePost response = new ResponsePost();
model.getSlrNim();
model.getStdId();
model.getSlrName();
model.getSlrPass();
model.getSlrEmail();
model.getSlrContact();
model.getSlrGender();
try{
service.connectToDatabase();
Result<Integer> result = service.save(model);
response.setStatus(result.getStatus());
response.setId(result.getModel());
service.closeConnection();
}catch(SQLException e) {
response.setStatus(StateCons.SQL_EXCEPTION);
}
return response;
}
}
服务
@Service
public class SellerService extends BaseService implements BaseDao<SellerPost, SellerGet, SellerGet> {
public SellerService(){
}
@Override
public Result<Integer> save(SellerPost model){
Result<Integer> result = new Result();
if(getDatabase().getResult() == StateCons.SUCCESS){
try{
String sql = "INSERT INTO seller (slr_nim, slr_name, std_id, slr_gender, slr_email, slr_contact, slr_pass) VALUES ('"+ model.getSlrNim() +"', '"+ model.getSlrName() + "', '"+ model.getStdId() +"', "+ model.getSlrGender() +", '"+ model.getSlrEmail() +"', '" + model.getSlrContact() +"', '"+ model.getSlrPass() +"')";
setResultSet(getDatabase().executeQuery(sql));
if(getResultSet().next()) {
result.setModel(new Integer(getResultSet().getInt("slr_nim")));
result.setStatus(StateCons.SUCCESS);
}else{
result.setStatus(StateCons.FAILED);
}
getResultSet().close();
}catch(SQLException e) {
result.setStatus(StateCons.NO_RECORD);
}
}else{
result.setStatus(StateCons.FAILED);
}
return result;
}
}
DAO
package id.ceban.dao;
import java.util.List;
import id.ceban.model.Result;
public interface BaseDao<P, G, GD> {
public Result<Integer> save(P model);
public Result<Boolean> delete(int modelId);
public Result<Boolean> update(P model, int modelId);
public Result<GD> get(int modelId);
public Result<List<G> > getList(String search_query, String field, String sort, int page, int limit);
public Result<Integer> count(int modelId);
}
错误
答案 0 :(得分:0)
在控制器中,您不应该使用SellerService
的新实例,而应使用@Autowired
。您可以尝试替换它:
SellerService service = new SellerService();
为此:
@Autowired
SellerService service;
SellerService
类应该在类定义之前有@Service
注释:
@Service
public class SellerService extends BaseService implements BaseDao<SellerPost, SellerGet, SellerGet> {
//...
}