2014-10-28 23 views
1

我的項目包括那些四個表如下:Http狀態500返回上Spring MVC的使用REST模板和JSON響應格式

  1. 問題 - Question_id,問題文本
  2. 用戶 - USER_ID,名稱
  3. Question_Answer - 用戶名,Question_ID,答案
  4. QuestionType - QuestionID,標籤

我有一個基於多標籤

或者乾脆返回所有問題的列表(當沒有標籤提供)

或插入由用戶提供的到答案的生成問題問題_答案表。

控制器類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狀態500

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

而且當我執行它產生以下網址HTTP狀態405 - 不支持請求方法'GET'

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

我做錯了什麼?我錯過了什麼嗎?

堆棧跟蹤HTTP狀態500是如下:

重度:Servlet.service()進行的servlet [其餘]與路徑上下文[/ FetchQuestions]拋出異常[請求處理失敗;嵌套異常是org.springframework.web.client.HttpClientErrorException:405方法不允許]與根本原因 org.springframework.web.client.HttpClientErrorException:405方法不允許 at org.springframework.web.client.DefaultResponseErrorHandler.handleError( DefaultResponseErrorHandler.java:91) 在org.springframework.web.client.RestTemplate.handleResponseError(RestTemplate.java:576) 在org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:532) 的組織。 springframework.web.client.RestTemplate.execute(RestTemplate。java:489) at org.springframework.web.client.RestTemplate.getForObject(RestTemplate.java:226) at com.bargadss.SpringService.Controller.ListQuestionController.insertQuestionAnswer(ListQuestionController.java:47) at sun.reflect。 NativeMethodAccessorImpl.invoke0(本機方法) 在sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) 在sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 在java.lang.reflect.Method.invoke (Method.java:606) at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:214) at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132 ) 在org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104) 在org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java: 748) 在org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689) 在org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java: 83) 在org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:945) 在org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:876) 在org.springframework.web。 servlet.FrameworkServlet.processR eQUEST的(FrameworkServlet.java:931) 在org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:822) 在javax.servlet.http.HttpServlet.service(HttpServlet.java:621) 在有機springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:807) at javax.servlet.http.HttpServlet.service(HttpServlet.java:722) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain。的java:304) 在org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) 在org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240) 在org.apache。 catalina.core.StandardContextValve.invoke(StandardContextValve.java:164) a噸org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:462) 在org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164) 在org.apache.catalina.valves.ErrorReportValve .invoke(ErrorReportValve.java:100) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:562) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118) 在org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:395) 在org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:250) 在org.apache.coyote.http11.Http11Protocol $ Http11ConnectionHandler.process(Http11Protocol.java:188) at org.apache.coyote.http11.Http11Protocol $ Http11ConnectionHandler .process(Http11Protocol.java:166) at org.apache.tomcat.util.net.JIoEndpoint $ SocketProcessor.run(JIoEndpoint.java:302) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145 ) at java.util.concurrent.ThreadPoolExecutor $ Worker.run(ThreadPoolExecutor.java:615) at java.lang.Thread.run(Thread。Java的:745)

+0

您是否使用斷點進行調試? – Sreek521 2014-10-28 11:32:49

+0

是的,我打破了守則並測試了它。 – 2014-10-28 11:33:44

+0

請問您可以添加堆棧跟蹤 – Sreek521 2014-10-28 11:50:29

回答

2

而且當我執行它生成HTTP狀態405以下網址 - 請求方法 'GET' 不支持

變化從POSTGETSpringServiceController.SpringServiceController方法的請求方法。它應該可以解決你的問題。

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