我想在java中创建一个Web应用程序,用户根据数据需要的条件选择过滤条件,例如为特定服务的特定位置/订单下达的一段时间/订单下的订单从数据库中提取。我可以创建后端java类文件来从DB中提取数据,但不知道如何从前端jsp / servlets传递过滤条件。任何人都可以提供一个如何实现这个目标的例子吗?
答案 0 :(得分:0)
使用Spring Boot和hibernate(它是Spring中的标准对象关系映射工具)实现具有数据库连接的(在这种情况下为REST)Web服务的最简单方法。只需在@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);
}
}
需要服务界面以便&#34;真实&#34;服务类可以由spring自动装配:
public interface UpdateService {
Response process(String var1, String var2);
}
ServiceImpl将是&#34;真正的&#34;类。它必须是事务性的才能进行数据库连接。我只会使用一个名为&#34; Entity&#34;的数据库实体。 (我有多有创意,对吗?)
@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)
}
你应该可以打电话给&#34; http://yourHostname:yourPort/insertTheUrlYouWantToUse?var1=someValue&var2=someOtherValue&#34; 我不会在这里编写类Response ...因为它非常依赖于你如何设计它。当构造函数使用您的自定义Response返回ResponseEntity时,响应中的所有变量将在客户端收到时转换为xml。如果您使用Spring实现客户端,则可以使其期望相同的Reponse对象并继续在客户端使用它。希望我能以某种方式回答你的问题。如果你不想使用Spring Boot,那么我确信有相同的库/框架可以以类似的方式工作。