In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains "what are the advantages of Restful framework". The content of the explanation is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "what are the advantages of Restful framework".
Have the concise design of activerecord like jfinal/activejdbc, and use a simpler restful framework.
Restful's api design is used as the choice of restful server * * (use scenario: client and server are decoupled to provide server-side api interface for static html clients (mvvm, etc.), ios,andriod, etc.)
First, unique advantages:
1. Minimalist route design:
@ GET ("/ users/:name") / / Custom parsed parameters in the path if there are other matches, you can also use / users/ {name} / / the parameter name is the method variable name the parameter other than the path parameter can also be passed in the method parameter user= {json string} public Map find (String name,User user) {/ / return Lister.of (name) Return Maper.of ("K1", "v1jue name:" + name, "K2", "v2"); / / return what data is directly return, fully integrated into the common method}
two。 Minimalist activerecord design, data operation only needs a short row, and supports batch saving of objects
/ batch save User U1 = new User (). Set ("username", "test"). Set ("providername", "test"). Set ("password", "123456"); User U2 = new User (). Set ("username", "test"). Set ("providername", "test"). Set ("password", "123456"); User.dao.save (U1Query U2) / / normal save User u = new User (). Set ("username", "test"). Set ("providername", "test"). Set ("password", "123456"); u.save (); / / update u.update (); / / conditional update User.dao.updateBy (where,paras); User.dao.updateAll (columns,where,paras); / / delete u.deleted () / / conditional deletion of User.dao.deleteBy (where,paras); User.dao.deleteAll (); / / query User.dao.findById (id); User.dao.findBy (where,paras); User.dao.findAll (); / / paging User.dao.paginateBy (pageNumber,pageSize,where,paras); User.dao.paginateAll (pageNumber,pageSize)
3. Minimalist client design, support for various requests, file upload and file download (continue upload at breakpoint)
Client client=null;// creates a client object / / starts the resty-example project, and you can test the client String apiUrl = "http://localhost:8081/api/v1.0"; / / if you do not need to use an account to log in / / client= new Client (apiUrl); / / if you have account permission restrictions, you need to log in to client= new Client (apiUrl," / tests/login "," u "," 123 ") / / the request must be logged in before accessing 401Unauthenticated ClientRequest authRequest = new ClientRequest ("/ users", HttpMethod.GET); ResponseData authResult = client.build (authRequest) .ask (); System.out.println (authResult.getData ()); / / get ClientRequest getRequest = new ClientRequest ("/ tests", HttpMethod.GET); ResponseData getResult = client.build (getRequest) .ask (); System.out.println (getResult.getData ()) / / post ClientRequest postRequest = new ClientRequest ("/ tests", HttpMethod.POST); postRequest.addParameter ("test", Jsoner.toJSONString (Maper.of ("a", "Ginger")); ResponseData postResult = client.build (postRequest). Ask (); System.out.println (postResult.getData ()); / / put ClientRequest putRequest = new ClientRequest ("/ tests/x", HttpMethod.PUT); ResponseData putResult = client.build (putRequest). Ask () System.out.println (putResult.getData ()); / / delete ClientRequest deleteRequest = new ClientRequest ("/ tests/a", HttpMethod.DELETE); ResponseData deleteResult = client.build (deleteRequest). Ask (); System.out.println (deleteResult.getData ()); / / upload ClientRequest uploadRequest = new ClientRequest ("/ tests/resty", HttpMethod.POST); uploadRequest.addUploadFiles ("resty", ClientTest.class.getResource ("/ resty.jar"). GetFile ()) UploadRequest.addParameter ("des", "test file paras test pen"); ResponseData uploadResult = client.build (uploadRequest). Ask (); System.out.println (uploadResult.getData ()); / / download supports breakpoint continuation ClientRequest downloadRequest = new ClientRequest ("/ tests/file", HttpMethod.GET); downloadRequest.setDownloadFile (ClientTest.class.getResource ("/ resty.jar"). GetFile (). Replace (".jar", "x.jar")) ResponseData downloadResult = client.build (downloadRequest). Ask (); System.out.println (downloadResult.getData ())
4. Support multiple data sources and nested transactions (use scenarios: applications that need to access multiple databases, or provide data access api to clients as internal data middleware, etc.) 5. Minimalist permission design, you only need to implement a simple interface and add an interceptor to achieve url-based permission design.
/ / using transactions in resource, that is, in controller, rest's world thinks that all requests represent resources, so it is called resource @ GET ("/ users") @ Transaction (name = {DS.DEFAULT_DS_NAME, "demo"}) / / transactions of multiple data sources If you have only one database directly @ Transaction does not need the parameter public User transaction () {/ / TODO to perform database operations with model, as long as an operation throws an exception, both data sources will be rolled back, although it is not a distributed transaction to ensure the security of code block data execution} / / if you need to implement a transaction in service, through the java dynamic proxy (you must use the interface This is how jdk is designed) public interface UserService {@ Transaction (name = {DS.DEFAULT_DS_NAME, "demo"}) / / service adds multiple data source transactions, if you have only one database directly @ Transaction does not need the parameter public User save (User u) } / / Notes on transactions using the service layer in resource / / @ Transaction (name = {DS.DEFAULT_DS_NAME, "demo"}) need to be written on the interface of service / / Note that the automatic proxy of java must exist interface / / TransactionAspect is a transaction aspect, you can also implement your own aspects such as log Aspect Implement Aspect interface / / re-private UserService userService = AspectFactory.newInstance (new UserServiceImpl (), new TransactionAspect (), new LogAspect ()) Private UserService userService = AspectFactory.newInstance (new UserServiceImpl (), new TransactionAspect ())
5. Minimalist permission design, you only need to implement a simple interface and add an interceptor to achieve url-based permission design.
Public void configInterceptor (InterceptorLoader interceptorLoader) {/ / permission interceptor is placed in * * bit * * time to avoid executing unnecessary code interceptorLoader.add (new SecurityInterceptor (new MyAuthenticateService ();} / / the interface public class MyAuthenticateService implements AuthenticateService {/ / obtains the user's password and permission information through name when logging in. Public Principal findByName (String name) {DefaultPasswordService defaultPasswordService = new DefaultPasswordService () Principal principal = new Principal (name, defaultPasswordService.hash), new HashSet () {{add ("api");}}); return principal;} / / basic permission summary table all url permissions are put here. You can set all permissions public Set loadAllPermissions () {Set permissions = new HashSet () through a file or database or direct code. Permissions.add (new Permission ("GET", "/ api/transactions**", "api"); return permissions;}}
6. Minimalist cache design, scalable, very simple to enable model automatic caching function 7. To download files, you only need to return file directly.
Public void configConstant (ConstantLoader constantLoader) {/ / enable cache and turn on cache @ Table (name = "sec_user", cached = true) constantLoader.setCacheEnable (true) on the model where cache is to be used automatically;} @ Table (name = "sec_user", cached = true) public class User extends Model {public static User dao = new User ();}
7. To download files, you only need to return file directly.
@ GET ("/ files") public File file () {return new File (path);}
8. Upload files and write them to the server via getFiles,getFile
@ POST ("/ files") public UploadedFile file () {/ / Hashtable uploadedFiles=getFiles (); return getFile (name);}
9. Of course, it also supports traditional web development. You can implement data parsing yourself and add custom parsing templates to config.
Public void configConstant (ConstantLoader constantLoader) {/ / return different data types by suffix you can customize your own render such as: FreemarkerRender / / constantLoader.addRender ("json", new JsonRender ()); / / support for json and text has been added by default, you only need to set the custom Render add}
2. Run the example example:
1. Run pom.xml- > install in the root directory (install the relevant plug-ins locally, and you don't need to publish them to maven after the functionality is complete)
two。 Create a demo,example database in the local mysql database, corresponding to the database configuration of application.properties
3. Run pom.xml- > flyway-maven-plugin:migration under resty-example to automatically generate database table structure from database files under db directory under resources.
4. Run pom.xml- > tomcat7-maven-plugin:run under resty-example to start the example program
Reminder: idea is recommended as the development ide, using sub-module multi-module development.
Thank you for your reading, the above is the "what are the advantages of the Restful framework" content, after the study of this article, I believe you have a deeper understanding of the advantages of the Restful framework, the specific use of the need for you to practice and verify. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.