使用REST模板和JSON响应格式在Spring MVC上返回的Http Status 500

阿林丹·达斯(Arindam Das)

我的项目由以下四个表组成:

  1. 问题-Question_id,问题文字
  2. 用户-用户ID,名称
  3. Question_Answer-用户ID,Question_ID,答案
  4. QuestionType -QuestionID,标签

我必须根据多个标签生成问题

或仅返回所有问题的列表(如果未提供标签)

或将用户提供的答案插入Question_Answer表中。

Controller类SpringServiceController.java(以JSON格式生成结果)如下:

package com.bargadss.SpringService.Controller;

import java.text.ParseException;
import java.util.List;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.bargadss.SpringService.DAO.QuestionService;
import com.bargadss.SpringService.Domain.*;


@RestController

@RequestMapping("/service/question/")
public class SpringServiceController {
  QuestionService questionService=new QuestionService();

 @RequestMapping(value = "/{tag1},{tag2},{tag3}", method =  RequestMethod.GET,headers="Accept=application/json")
 public List<Questions> getQuestions(@PathVariable("tag1") String tag1, @PathVariable("tag2") String tag2, @PathVariable("tag3") String tag3) {
  List<Questions> Qobj=questionService.getQuestionByTag(tag1, tag2, tag3);
  return Qobj;
 }

 @RequestMapping(method = RequestMethod.GET,headers="Accept=application/json")
 public List<Questions> getAllQuestions() {  
  List<Questions> Qobj=questionService.getAllQuestion();
  return Qobj;   
 }

 @RequestMapping(value="/insert/{user_id}/{question_id}/{answer}",method = RequestMethod.POST,headers="Accept=application/json")
  public List<Questions> addQuestions(@PathVariable int user_id,@PathVariable int question_id,@PathVariable String answer) throws ParseException { 
      Question_Answer qtnAns = new Question_Answer();
      qtnAns.setUser_id(user_id);
      qtnAns.setQuestion_id(question_id);
      qtnAns.setAnswer(answer);
      questionService.insertAnswer(qtnAns.getUser_id(), qtnAns.getQuestion_id(), qtnAns.getAnswer());
      return questionService.getAllQuestion();        
  }        
  }

ListQuestionController.java使用Spring REST temaplate(生成JSP页面)如下:

package com.bargadss.SpringService.Controller;

import java.util.LinkedHashMap;
import java.util.List;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.ModelAndView;

import com.bargadss.SpringService.Domain.*;

@Controller
public class ListQuestionController {

 @RequestMapping("/listQuestion/{tag1},{tag2},{tag3}")
    public ModelAndView listQuestions(@PathVariable("tag1") String Tag1, @PathVariable("tag2") String Tag2, @PathVariable("tag3") String Tag3) { 
        RestTemplate restTemplate = new RestTemplate();
        String url="http://localhost:8080/FetchQuestions/service/question/{tag1},{tag2},{tag3}";
        List<LinkedHashMap> Qobj=restTemplate.getForObject(url, List.class,Tag1,Tag2,Tag3);
        return new ModelAndView("listQuestion", "questions", Qobj);
    }

 @RequestMapping("/listAllQuestion/")
    public ModelAndView listAllQuestion() { 
        RestTemplate restTemplate = new RestTemplate();
        String url="http://localhost:8080/FetchQuestions/service/question/";
        List<LinkedHashMap> Qobj=restTemplate.getForObject(url, List.class);
        return new ModelAndView("listQuestion", "questions", Qobj);
    }

 @RequestMapping("/insertQuestionAnswer/{user_id}/{qtn_id}/{answer}")
    public ModelAndView insertQuestionAnswer(@PathVariable("user_id") String user_ID,
           @PathVariable("qtn_id") String qtn_ID, @PathVariable("answer") String answer) { 
        RestTemplate restTemplate = new RestTemplate();
        String url="http://localhost:8080/FetchQuestions/service/question/insert/{user_id}/{qtn_id}/{answer}";
        List<LinkedHashMap> Qobj=restTemplate.getForObject(url, List.class,user_ID,qtn_ID,answer);
        return new ModelAndView("listQuestion", "questions", Qobj);
    }

  }

所述QuestionService.java类执行DAO活性如下:

package com.bargadss.SpringService.DAO;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import com.bargadss.SpringService.Domain.*;
import com.bargadss.SpringService.Utility.DBUtility;


public class QuestionService {

private Connection connection;

 public QuestionService() {
  connection = DBUtility.getConnection();
 }

 public void insertAnswer(int userId,int qtnId,String answer){
    //Question_Answer objQA = new Question_Answer();
    PreparedStatement preparedStatement = null;
    try{
         preparedStatement = connection.prepareStatement("insert into question_answer values (?,?,?)");
         preparedStatement.setInt(1, userId);
         preparedStatement.setInt(2, qtnId);
         preparedStatement.setString(3, answer);
         int result = preparedStatement.executeUpdate();
         if(result == 0)
            System.out.println("INSERTION OF DATA FAILED");
    } catch (SQLException e){
         e.printStackTrace();
    }
    finally{
        try { if (preparedStatement != null) preparedStatement.close(); } catch (Exception e) {System.out.println("Exception Closing The Prepared Statement");e.printStackTrace();};
    }
 }

 public List<Questions> getAllQuestion(){
     Questions objQ = new Questions();
     ResultSet rs = null;
     PreparedStatement preparedStatement = null;
     List<Questions> qtns = new ArrayList<Questions>();
     try {
           preparedStatement = connection.prepareStatement("select * from questions");             
           rs = preparedStatement.executeQuery();

           while(rs.next()) {
            objQ.setQuestion_id(Integer.parseInt( rs.getString("Question_id") ) );
            objQ.setQuestion_text(rs.getString("Question_Text"));
            qtns.add(objQ);   
           }
     } catch (SQLException e) {
           e.printStackTrace();
       }    
       finally{
           try { if (rs != null) rs.close(); } catch (Exception e) {System.out.println("Exception Closing The result Set");e.printStackTrace();};
           try { if (preparedStatement != null) preparedStatement.close(); } catch (Exception e) {System.out.println("Exception Closing The Prepared Statement");e.printStackTrace();};
           /*try { if (connection != null) connection.close(); } catch (Exception e) {System.out.println("Exception Closing The Connection");e.printStackTrace();};*/
       }
    return qtns;
 }

 public List<Questions> getQuestionByTag(String Tag1,String Tag2,String Tag3){       
     Questions objQ = new Questions();
     ResultSet rs = null;
     PreparedStatement preparedStatement = null;
     List<Questions> qtns = new ArrayList<Questions>();
     try {
           preparedStatement = connection.
           prepareStatement("select questions.Question_id,questions.Question_Text from questions,questiontype " +
                            "where questions.Question_id=questiontype.Question_id " +
                            "and questiontype.Tag in (?,?,?)");
           preparedStatement.setString(1, Tag1);
           preparedStatement.setString(2, Tag2);
           preparedStatement.setString(3, Tag3);
           rs = preparedStatement.executeQuery();

           while(rs.next()) {
            objQ.setQuestion_id(Integer.parseInt( rs.getString("Question_id") ) );
            objQ.setQuestion_text(rs.getString("Question_Text"));
            qtns.add(objQ);   
           }
     } catch (SQLException e) {
           e.printStackTrace();
       }    
       finally{
           try { if (rs != null) rs.close(); } catch (Exception e) {System.out.println("Exception Closing The result Set");e.printStackTrace();};
           try { if (preparedStatement != null) preparedStatement.close(); } catch (Exception e) {System.out.println("Exception Closing The Prepared Statement");e.printStackTrace();};
           /*try { if (connection != null) connection.close(); } catch (Exception e) {System.out.println("Exception Closing The Connection");e.printStackTrace();};*/
       }
    return qtns;
}

}

在执行具有以下URL的项目(Apache Tomcat 7.0.12)时,它将生成HTTP STATUS 500

http://localhost:8080/FetchQuestions/insertQuestionAnswer/3/9/True

同样,当我执行以下URL时,它也会生成HTTP状态405-不支持请求方法“ GET”

http://localhost:8080/FetchQuestions/service/question/insert/3/9/True

我究竟做错了什么 ?我想念什么吗?

HTTP状态500的堆栈跟踪如下:

严重:路径为[/ FetchQuestions]的上下文中的servlet [rest]的Servlet.service()抛出异常[请求处理失败;嵌套的异常是org.springframework.web.client.HttpClientErrorException:“ 405方法不允许”,根本原因是org.springframework.web.client.HttpClientErrorException:405.org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler。 org.springframework.web.client.RestTemplate.handleResponseError(RestTemplate.java:576)的org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:532)的org.springframework.web.client的java:91) org.springframework.web.client.RestTemplate.getForObject(RestTemplate.java:226)上的.RestTemplate.execute(RestTemplate.java:489)在com.bargadss.SpringService.Controller.ListQuestionController上。

希希尔·库马尔(Shishir Kumar)

同样,当我执行以下URL时,它也会生成HTTP状态405-不支持请求方法“ GET”

将方法的请求SpringServiceController.SpringServiceController方法从更改POSTGET它应该可以解决您的问题。

@RequestMapping(value="/insert/{user_id}/{question_id}/{answer}",method = RequestMethod.GET,headers="Accept=application/json")

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

使用REST模板和JSON响应格式在Spring MVC上返回的Http Status 500

来自分类Dev

ASP.NET MVC 操作在无效的 JSON 上返回 500

来自分类Dev

使用 MediaType.APPLICATION_XML 时 Jersey 2.25.1 HTTP STATUS 500 错误

来自分类Dev

Spring MVC返回视图抛出500错误

来自分类Dev

在运行tomcat时获取HTTP Status 500

来自分类Dev

Django,当我返回 status_code 404 或 500 时自定义 404/500

来自分类Dev

从服务器返回的错误 HTTP 响应。代码 500

来自分类Dev

在http-POST上改造SocketTimeoutException(和/或http 500错误)

来自分类Dev

使用数据访问表时,Spring Data Rest返回http 500

来自分类Dev

Tomcat上的WebSocket握手返回意外响应代码500

来自分类Dev

当Mockjax返回status:500(或400或...)时,jQuery不会触发$ .ajax.fail()。

来自分类Dev

当Mockjax返回status:500(或400或...)时,jQuery不会触发$ .ajax.fail()。

来自分类Dev

如何获取URL参数中的值?xmlhttp.status返回500

来自分类Dev

如何修复HTTP错误获取URL。检索时Java中的Status = 500?

来自分类Dev

是否有一个网站返回500(和其他)HTTP响应代码以进行测试?

来自分类Dev

Zuul Ribbon异常始终返回500响应

来自分类Dev

NSURLConnection响应返回500状态代码

来自分类Dev

Django HTTP响应码500错误

来自分类Dev

Thrift等同于http 500响应?

来自分类Dev

Django HTTP响应码500错误

来自分类Dev

Spring Boot-Jackson EntityNotFoundException返回200而不是500响应

来自分类Dev

如果出现 500 错误,如何返回 JSON 响应?

来自分类Dev

Spring Mvc 提交后获取HTTP Status [404] – [Not Found]

来自分类Dev

Spring Mvc App get - HTTP Status [404] – [Not Found]

来自分类Dev

为 HTTP 200 和 500 状态代码验证 Alamofire 响应

来自分类Dev

使用@RequestBody List <?>的Spring MVC REST在语法上返回HTTP 400错误

来自分类Dev

JAX-RS上的JAXB-具有关系的JPA实体在日志上不返回JSON HTTP 500时没有错误(Glassfish)

来自分类Dev

Spring redis 返回 500 stackoverflow 错误

来自分类Dev

Spring MVC“请求处理失败” 500错误

Related 相关文章

  1. 1

    使用REST模板和JSON响应格式在Spring MVC上返回的Http Status 500

  2. 2

    ASP.NET MVC 操作在无效的 JSON 上返回 500

  3. 3

    使用 MediaType.APPLICATION_XML 时 Jersey 2.25.1 HTTP STATUS 500 错误

  4. 4

    Spring MVC返回视图抛出500错误

  5. 5

    在运行tomcat时获取HTTP Status 500

  6. 6

    Django,当我返回 status_code 404 或 500 时自定义 404/500

  7. 7

    从服务器返回的错误 HTTP 响应。代码 500

  8. 8

    在http-POST上改造SocketTimeoutException(和/或http 500错误)

  9. 9

    使用数据访问表时,Spring Data Rest返回http 500

  10. 10

    Tomcat上的WebSocket握手返回意外响应代码500

  11. 11

    当Mockjax返回status:500(或400或...)时,jQuery不会触发$ .ajax.fail()。

  12. 12

    当Mockjax返回status:500(或400或...)时,jQuery不会触发$ .ajax.fail()。

  13. 13

    如何获取URL参数中的值?xmlhttp.status返回500

  14. 14

    如何修复HTTP错误获取URL。检索时Java中的Status = 500?

  15. 15

    是否有一个网站返回500(和其他)HTTP响应代码以进行测试?

  16. 16

    Zuul Ribbon异常始终返回500响应

  17. 17

    NSURLConnection响应返回500状态代码

  18. 18

    Django HTTP响应码500错误

  19. 19

    Thrift等同于http 500响应?

  20. 20

    Django HTTP响应码500错误

  21. 21

    Spring Boot-Jackson EntityNotFoundException返回200而不是500响应

  22. 22

    如果出现 500 错误,如何返回 JSON 响应?

  23. 23

    Spring Mvc 提交后获取HTTP Status [404] – [Not Found]

  24. 24

    Spring Mvc App get - HTTP Status [404] – [Not Found]

  25. 25

    为 HTTP 200 和 500 状态代码验证 Alamofire 响应

  26. 26

    使用@RequestBody List <?>的Spring MVC REST在语法上返回HTTP 400错误

  27. 27

    JAX-RS上的JAXB-具有关系的JPA实体在日志上不返回JSON HTTP 500时没有错误(Glassfish)

  28. 28

    Spring redis 返回 500 stackoverflow 错误

  29. 29

    Spring MVC“请求处理失败” 500错误

热门标签

归档