我想用java创建一个Web应用程序,用户根据需要从数据库中提取数据的条件,选择过滤条件,例如一段时间内的订单/特定位置的订单/特定服务的订单。我可以创建后端java类文件来从数据库中提取数据,但不知道如何从前端jsp/servlet传递过滤条件。谁能给我一个如何实现这一目标的例子?
最佳答案
使用数据库连接实现(在本例中为 REST)Web 服务的最简单方法可能是使用 Spring Boot和 hibernate(它是 Spring 中的标准对象关系映射工具)。只需在 @RestController 中使用所需的变量处理请求,然后在事务性 @Service 类中处理它们,如下所示(在本示例中,我将使用媒体类型 application/x-www-form-urlencoded 作为客户端发送的变量):
Controller :
@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);
}
}
需要 Service 接口(interface),以便 Spring Autowiring “真正的”服务类:
public interface UpdateService {
Response process(String var1, String var2);
}
ServiceImpl 将是“真正的”类。它必须是事务性的才能建立数据库连接。我只会使用一个名为“Entity”的数据库实体(我很有创意,对吧?)
@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 ” 我不打算在这里编写 Response 类...因为它很大程度上取决于您如何设计它。当构造函数返回一个带有自定义Response的ResponseEntity时,当客户端收到它时,Response中的所有变量都将被转换为xml。如果您也使用 Spring 实现客户端,则可以使其期望相同的 Reponse 对象并继续在客户端使用它。希望我能以某种方式回答你的问题。如果您不想使用 Spring Boot,那么我确信有等效的库/框架,它们将以某种类似的方式工作。
关于javascript - Java应用程序根据用户过滤条件从数据库中提取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45100479/