2017-07-14 21 views
1

我想在java中創建一個Web應用程序,其中用戶選擇過濾條件,如訂單放置一段時間/訂單放置在特定位置/訂單放置對於特定的服務,基於數據需要從數據庫中提取數據的條件。我可以創建後端Java類文件以從數據庫提取數據,但不知道如何從前端jsp/servlet傳遞過濾條件。任何人都可以提供一個如何實現這個目標的例子嗎?Java應用程序根據用戶過濾條件從數據庫中提取數據

+0

沒有難過的朋友,但這不是這個問題的正確地方。 – Arvind

回答

0

通過使用Spring Boot和hibernate(這是Spring中的標準對象 - 關係映射工具)實現(在本例中爲REST)帶有數據庫連接的webservice最簡單的方法。只需在@RestController中使用所需的變量處理請求,並像這樣在事務性的@Service類中處理它們(我將在此示例中使用媒體類型application/x-www-form-urlencoded來處理客戶端發送的變量) :

控制器:

@RestController 
public class Controller { 

    @Autowired 
    Service service; //Service needs to be an interface in order to be autowired 

    @RequestMapping(method = RequestMethod.GET, value = "/insertTheUrlYouWantToUse", 
      consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE) 
    public ResponseEntity<Response> yourMethod(@RequestParam String var1, 
      @RequestParam String var2){ 
     //Your code here 
     //Example code: 
     Response r = service.process(var1, var2); //Response would be your custom class. 
                //Of course you can use any other 
                //existing class if it fits your needs 
     return new ResponseEntity<Response>(r, HttpStatus.OK); 
    } 
} 

需要的服務界面,使 「真正的」 服務類可以通過彈簧被裝配:

public interface UpdateService { 

    Response process(String var1, String var2); 
} 

ServiceImpl將是 「真正的」 類。它必須是事務性的才能夠建立數據庫連接。我只打算用所謂的「實體」一個數據庫實體工作(?我是多麼有創意,右)

@Service 
@Repository 
@Transactional 
public class ServiceImpl implements Service{ 

    @PersistenceContext 
    private EntityManager em; //needed for all the database related stuff 

    public Response process(String var1, String var2){ 
     try{ 
      Entity entity = em 
      .createQuery("FROM Entity WHERE var1=:var1 AND var2=:var2", Entity.class) 
      .setParameter("var1", var1).setParameter("var2", var2).getSingleResult(); 
     }catch(NoResultException e){ 
      //whatever you want to do if no entity is available 
     } 
     return new Response(Entity); //return the result to the Controller, depending on 
            //you Response you can obviously add messages, links 
            //and other stuff if you like 
    } 
} 

要完成這一點,實體應該是這樣的:

@Entity 
@Table(name="TableNameInDatabase") 
public class Entity implements Serializable{ 

    @Id 
    @Column(name="ID", unique = true, nullable = false) 
    private String var1; 

    @Column(name="someValue") 
    private String var2; 

    //add getter, setter and constructor (too lazy for that) 
} 

你應該能夠打電話給我「http://yourHostname:yourPort/insertTheUrlYouWantToUse?var1=someValue&var2=someOtherValue」 我不打算寫這個類的響應在這裏...因爲它幾乎取決於你如何設計它。當構造函數返回ResponseEntity與您的自定義響應時,Response中的所有變量將在客戶端接收到時轉換爲xml。如果您也使用Spring來實現您的客戶端,則可以使其期望相同的Reponse對象並在客戶端繼續使用它。希望我能以某種方式回答你的問題。如果你不想使用Spring Boot,那麼我肯定有相當的庫/框架,它們的工作方式有點類似。

+1

我剛剛看到這個標記爲Javascript,如果我有點錯過了這裏的觀點,也許它仍然有幫助^^ – Naeramarth

相關問題