You have a form as shown below:
<form action="/test/dbOperation" method="POST"> <input type="text" id="title" name="title"> <input type="text" id="description" name="description"> <input type="text" id="likes" name="likes"> <input type="text" id="url" name="url"> <input type="text" id="by" name="by"> <button type="submit" value="Submit"> </form>
Now in Spring, you can use annotation to make the class as a Controller, where you need to process the request
@Controller @RequestMapping("/test") public class formCntrl { @RequestMapping(value = "/dbOperation", method = RequestMethod.POST) public @ResponseBody String (HttpServletResponse resp, @RequestParam("title") String title, @RequestParam("description") String description, @RequestParam("likes") int likes, @RequestParam("url") String url, @RequestParam("by") String by) { try{ // To connect to mongodb server MongoClient mongoClient = new MongoClient( "localhost" , 27017 ); // Now connect to your databases DB db = mongoClient.getDB( "cms" ); System.out.println("Connect to database successfully"); boolean auth = db.authenticate(myUserName, myPassword); System.out.println("Authentication: "+auth); DBCollection school = db.getCollection("school"); System.out.println("Collection mycol selected successfully"); BasicDBObject doc = new BasicDBObject("title", title). append("description", description). append("likes", likes). append("url", url). append("by", by); school.insert(doc); System.out.println("Document inserted successfully"); }catch(Exception e){ System.err.println( e.getClass().getName() + ": " + e.getMessage() ); } } }
Generally, it is not very good to mix the database logic in the controller. Use Spring MVC, where you can have a DAO layer that separates the database logic from the business logic.
Hope this helps.
source share