练手的项目,没有学Spring,所以踩坑了。前端用Java Swing图形界面窗口来写的,后端用的Springboot。
- 出现的问题:写代码的时候发送的请求,后端总是返回请求失败。查了很久,没想到是请求方法不匹配造成的。
- 代码片段如下,主要功能就是:前端给删除按钮添加一个鼠标点击时间,发送请求后,后端把数据库的对应id的数据给删掉。 这里使用了自己写的(抄的)GetUtils工具类创建http请求,但注意这里使用的是Get方法。而导致上述问题的原因就是在后端的Controller层注解用的@DeleteMapping(“/deleteStudentById”),实际上应该用@GetMapping(“/deleteStudentById”),因为我的项目中还是要返回一个操作成功的信息给前端的。
deleteBtn.addActionListener(newActionListener(){@OverridepublicvoidactionPerformed(ActionEvent e){//获取选中的条目int selectedRow = table.getSelectedRow();//如果有选中的条目,则返回条目的行号,如果没有选中,那么返回-1if(selectedRow==-1){JOptionPane.showMessageDialog(jf,"请选择要删除的条目!");return;}//防止误操作int result =JOptionPane.showConfirmDialog(jf,"确认要删除选中的条目吗?","确认删除",JOptionPane.YES_NO_OPTION);if(result !=JOptionPane.YES_OPTION){return;}String id = tableModel.getValueAt(selectedRow,0).toString();//这里用的Get方法GetUtils.get("http://localhost:8080/test/deleteStudentById?id="+ id,newSuccessListener(){@Overridepublicvoidsuccess(String result){ResultInfo info =JsonUtils.parseResult(result);if(info.isFlag()){//删除成功JOptionPane.showMessageDialog(jf,"删除成功");requestData();}else{//删除失败JOptionPane.showMessageDialog(jf,info.getMessage());}}},newFailListener(){@Overridepublicvoidfail(){JOptionPane.showMessageDialog(jf,"网络异常,请稍后重试");}});}});
下面是我的Controller层的一些接口,这里@GetMapping(“/deleteStudentById”)的注解原本写成了@DeleteMapping(“/deleteStudentById”),所以前后端没有匹配上。
packagecom.guo.getscreen.controller;importcom.guo.getscreen.dao.ResultInfo;importcom.guo.getscreen.dao.Test;importcom.guo.getscreen.dto.TestDTO;importcom.guo.getscreen.service.TestService;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.web.bind.annotation.*;@RestController@RequestMapping("/test")publicclassTestController{@AutowiredprivateTestService testService;@GetMapping("/findStudentById")publicResultInfogetStudentById(@RequestParamlong id){// return Response.newSuccess(testService.getStudentById(id));returnnewResultInfo(true,testService.getStudentById(id),"查询成功");}@GetMapping("/deleteStudentById")publicResultInfodeleteStudentById(@RequestParamlong id){System.out.println("Request received to delete student with ID: "+ id);
testService.deleteStudentById(id);returnnewResultInfo(true,null,"删除成功");}@PutMapping("/updateStudent/{id}")publicResponse<TestDTO>updateStudent(@PathVariablelong id,@RequestParam(required =false)String name,@RequestParam(required =false)String email,@RequestParam(required =false)String password){returnResponse.newSuccess(testService.updateStudentById(id, name, email,password));}@GetMapping("/findAllStudents")publicResultInfofindAllStudents(){returnnewResultInfo(true,testService.findAll(),"查询成功");}@PostMapping("/addNewStudent")publicResultInfoaddNewStudent(Test test){
testService.addNewStudent(test);returnnewResultInfo(true,null,"添加成功");}}
其他注意事项:
前后端接口不匹配还有一些可能的原因,这里也作为搜集整理如下:
1.URL不匹配。前端URL上请求的接口写错了字母导致与后端不匹配,或者使用的注解不匹配
2. 后端没有启动,没有监听成功。
上面使用的GetUtils类的代码也附在下面:
packagecom.guo.getscreenui.net;importorg.apache.http.HttpEntity;importorg.apache.http.client.config.RequestConfig;importorg.apache.http.client.methods.CloseableHttpResponse;importorg.apache.http.client.methods.HttpGet;importorg.apache.http.impl.client.CloseableHttpClient;importorg.apache.http.impl.client.HttpClientBuilder;importorg.apache.http.util.EntityUtils;importjava.io.IOException;importjava.util.HashMap;importjava.util.Map;publicclassGetUtils{//无参方式publicstaticvoidget(String url,SuccessListener sListener,FailListener fListener){getWithParams(url,newHashMap<>(),sListener,fListener);}//有参方式publicstaticvoidgetWithParams(String url,Map<String,Object> params,SuccessListener sListener,FailListener fListener){CloseableHttpClient httpClient =HttpClientBuilder.create().setDefaultCookieStore(CookiesHolder.getCookieStore()).build();CloseableHttpResponse response =null;try{// 创建Get请求
url =joinParam(url, params);HttpGet httpGet =newHttpGet(url);RequestConfig requestConfig =RequestConfig.custom().setSocketTimeout(3000)//服务器响应超时时间.setConnectTimeout(3000)//连接服务器超时时间.build();
httpGet.setConfig(requestConfig);// 由客户端执行(发送)Get请求
response = httpClient.execute(httpGet);// 从响应模型中获取响应实体HttpEntity responseEntity = response.getEntity();if(responseEntity !=null){
sListener.success(EntityUtils.toString(responseEntity));}}catch(Exception e){
e.printStackTrace();
fListener.fail();}finally{try{// 释放资源if(httpClient !=null){
httpClient.close();}if(response !=null){
response.close();}}catch(IOException e){
e.printStackTrace();}}}privatestaticStringjoinParam(String url,Map<String,Object> params){if(params ==null|| params.size()==0){return url;}StringBuilder urlBuilder =newStringBuilder(url);
urlBuilder.append("?");int counter =0;for(Map.Entry<String,Object> entry : params.entrySet()){String key = entry.getKey();Object value = entry.getValue();if(key ==null){continue;}if(counter ==0){
urlBuilder.append(key).append("=").append(value);}else{
urlBuilder.append("&").append(key).append("=").append(value);}
counter++;}return urlBuilder.toString();}}
版权归原作者 ★梦之蓝★ 所有, 如有侵权,请联系我们删除。