Source Code Link: http://download.csdn.net/download/poiuy1991719/10117665
This code is based on the operation of the database table, so please build the database table first
1. Build Bean Object
Packagespittr;Importjava.util.Date;ImportOrg.apache.commons.lang3.builder.EqualsBuilder;ImportOrg.apache.commons.lang3.builder.HashCodeBuilder;/*** Blog Information*/ Public classspittle {Private FinalLong ID; Private FinalString message; Private FinalDate time; PrivateDouble latitude; PrivateDouble longitude; Publicspittle (String message, Date time) { This(NULL, message, Time,NULL,NULL); } Publicspittle (Long ID, String message, Date time, double longitude, double latitude) { This. ID =ID; This. Message =message; This. Time =Time ; This. Longitude =longitude; This. Latitude =latitude; } Public LonggetId () {returnID; } PublicString getMessage () {returnmessage; } PublicDate GetTime () {returnTime ; } PublicDouble getlongitude () {returnlongitude; } PublicDouble getlatitude () {returnlatitude; } @Override Public Booleanequals (Object) {returnEqualsbuilder.reflectionequals ( This, that, "id", "Time"); } @Override Public inthashcode () {returnHashcodebuilder.reflectionhashcode ( This, "id", "Time"); } }
2. Write the Web configuration class:
PackageSpittr.config;ImportOrg.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;ImportSpittr.web.WebConfig;/*** * Container will find Abstractannotationconfigdispatcherservletinitializer this class (including extensions of this class) * And then use this class to configure the servlet context*/ Public classSpitterwebinitializerextendsAbstractannotationconfigdispatcherservletinitializer {@OverrideprotectedClass<?>[] Getrootconfigclasses () {//non-Web Components, classes with @configuration annotations to define the application context return NewClass<?>[] {rootconfig.class }; } @OverrideprotectedClass<?>[] Getservletconfigclasses () {//Specifies the configuration class that is used to define the application context with the @configuration annotation class return NewClass<?>[] {webconfig.class }; } @OverrideprotectedString[] Getservletmappings () {//map Dispatcherservlet to "/" return NewString[] {"/" }; }}
3. In the Web configuration class, use the Webconfig class:
Package Spittr.web;import Org.springframework.context.annotation.bean;import Org.springframework.context.annotation.componentscan;import Org.springframework.context.annotation.configuration;import Org.springframework.web.servlet.viewresolver;import Org.springframework.web.servlet.config.annotation.defaultservlethandlerconfigurer;import Org.springframework.web.servlet.config.annotation.enablewebmvc;import Org.springframework.web.servlet.config.annotation.resourcehandlerregistry;import Org.springframework.web.servlet.config.annotation.webmvcconfigureradapter;import org.springframework.web.servlet.view.internalresourceviewresolver;/*** * Config Web */@Configuration//Configuration class, Required annotations @enablewebmvc//enable spring Mvc@componentscan ("Spittr.web")//Enable component Scan, scan to controller public class Webconfig extends Webmvcconfigureradapter {@Beanpublic Viewresolver viewresolver () {//Configure JSP View Parser Internalresourceviewresolver Resolver = new Internalresourceviewresolver (); Resolver.setprefix ("/web-inf/views/");//before the request path, join the resource path RESOLVER.SEtsuffix (". jsp");//After the request path, add the resource name, such as/web-inf/views/home.jspresolver.setviewclass ( Org.springframework.web.servlet.view.JstlView.class); return resolver;} @Overridepublic void configuredefaultservlethandling (//Handling static resource Defaultservlethandlerconfigurer Configurer) { Configurer.enable ();} @Overridepublic void Addresourcehandlers (Resourcehandlerregistry registry) {Super.addresourcehandlers (registry);}}
4. The Web configuration class uses the root class to load other components:
Package Spittr.config;import Java.util.regex.pattern;import Org.springframework.context.annotation.ComponentScan; Import Org.springframework.context.annotation.componentscan.filter;import Org.springframework.context.annotation.configuration;import Org.springframework.context.annotation.FilterType; Import Org.springframework.context.annotation.import;import Org.springframework.core.type.filter.regexpatterntypefilter;import spittr.config.rootconfig.webpackage;/*** * The introduction of the database configuration class automatically scans the Spittr package, as well as the child package * /@Configuration//configuration class, the required annotation @import (dataconfig.class) @ComponentScan (basepackages = { "Spittr"}, Excludefilters = {@Filter (type = filtertype.custom, value = webpackage.class)}) public class RootConfig {Publ IC static class WebPackage extends Regexpatterntypefilter {public webpackage () {Super (Pattern.compile ("Spittr\\.web")) ;}}}
5. The root class is loaded with the database link class:
Package Spittr.config;import Javax.sql.datasource;import Org.springframework.context.annotation.bean;import Org.springframework.context.annotation.configuration;import Org.springframework.jdbc.core.jdbcoperations;import Org.springframework.jdbc.core.jdbctemplate;import org.springframework.jdbc.datasource.drivermanagerdatasource;@ Configurationpublic class Dataconfig {@Beanpublic DataSource DataSource () {Drivermanagerdatasource DataSource = new Drivermanagerdatasource ();d atasource.setdriverclassname ("Com.mysql.jdbc.Driver");d Atasource.seturl ("Jdbc:mysql :///spittle ");d atasource.setusername (" root ");d Atasource.setpassword (" root "); return dataSource;} @Beanpublic jdbcoperations JdbcTemplate (DataSource DataSource) {return new JdbcTemplate (DataSource);}}
6, data operation interface, data operation interface implementation:
Package Spittr.data;import Java.util.list;import spittr. Spittle;public interface Spittlerepository { list<spittle> findrecentspittles (); List<spittle> Findspittles (Long max, int count); Spittle FindOne (long id); void Save (Spittle spittle);}
Package Spittr.data;import Java.sql.resultset;import Java.sql.sqlexception;import java.util.list;import Org.springframework.beans.factory.annotation.autowired;import org.springframework.jdbc.core.JdbcOperations; Import Org.springframework.jdbc.core.rowmapper;import Org.springframework.stereotype.repository;import spittr. spittle; @Repository//The class of the data Access layer (DAO layer) is identified as Spring Beanpublic class Jdbcspittlerepository implements Spittlerepository {p Rivate jdbcoperations jdbc, @Autowiredpublic jdbcspittlerepository (jdbcoperations jdbc) {this.jdbc = jdbc;} Public list<spittle> findrecentspittles () {list<spittle> spittlelist=jdbc.query ("Select ID, message, Created_at, Latitude, longitude "+" from spittle "+" ORDER BY created_at desc LIMIT ", new Spittlerowmapper ());//system. OUT.PRINTLN ("---findrecentspittles is called---Returns the list of lists:" +spittlelist); return spittlelist;} Public list<spittle> findspittles (long max, int count) {list<spittle> spittlelist=jdbc.query ("SELECT ID, Message, createD_at, Latitude, longitude "+" from spittle "+" where ID <? " + "ORDER BY created_at desc LIMIT", new Spittlerowmapper (), Max),//SYSTEM.OUT.PRINTLN ("--- Findspittles is called---Returns the list of lists: "+spittlelist); return spittlelist;} Public spittle FindOne (long id) {spittle spittle=jdbc.queryforobject ("Select ID, message, created_at, Latitude, Longitude "+" from spittle "+" WHERE id =? ", new Spittlerowmapper (), id),//SYSTEM.OUT.PRINTLN ("---findone called---return spittle Object: "+spittle.getmessage ()); return spittle;} public void Save (spittle spittle) {//system.out.println ("---save is called---spittle object:" +spittle.getmessage ()); Jdbc.update ("INSERT into spittle (message, created_at, latitude, longitude)" + "VALUES (?,?,?,?)", Spittle.getmessage () , Spittle.gettime (), Spittle.getlatitude (), Spittle.getlongitude ());} private static class Spittlerowmapper implements rowmapper<spittle> {public spittle Maprow (ResultSet rs, int rowNum ) throws SQLException {return new spittle (Rs.getlong ("id"), rs.getstring ("message"), rs.getdAte ("Created_at"), Rs.getdouble ("longitude"), rs.getdouble ("latitude"));}}}
7. Write a form class that adds data:
Package Spittr.web.spittle;import Javax.validation.constraints.max;import Javax.validation.constraints.min;import Javax.validation.constraints.notnull;import javax.validation.constraints.size;/** * page form corresponding model */public class Spittleform { @NotNull @Size (min=1, max=140) private String message; @Min ( -180) @Max (longitude) private Double; @Min ( -90) @Max (+) private Double latitude; Public String GetMessage () { return message; } public void Setmessage (String message) { this.message = message; } Public Double Getlongitude () { return longitude; } public void Setlongitude (Double longitude) { this.longitude = longitude; } Public Double Getlatitude () { return latitude; } public void Setlatitude (Double latitude) { this.latitude = latitude; }}
8, write control class, to achieve page data reception, page jump, etc.
Package Spittr.web.spittle;import Java.util.date;import org.springframework.beans.factory.annotation.Autowired; Import Org.springframework.stereotype.controller;import Org.springframework.ui.model;import Org.springframework.web.bind.annotation.pathvariable;import Org.springframework.web.bind.annotation.requestmapping;import Org.springframework.web.bind.annotation.requestmethod;import Org.springframework.web.bind.annotation.requestparam;import spittr. Spittle;import spittr.data.SpittleRepository; @Controllerpublic class Spittlecontroller {private static final String max_long_as_string = "9223372036854775807";p rivate spittlerepository spittlerepository; @Autowiredpublic Spittlecontroller (Spittlerepository spittlerepository) {this.spittlerepository = spittlerepository;} /** * Page Output list * @param max * @param count * @param model * @return * http://localhost:8080/SpringInAction5_2_3/spittles */@ Requestmapping (value = "/spittles", method = requestmethod.get) public String spittles (@RequestParam (value = "Max", DefaultValue = max_long_as_string) LONG max, @RequestParam (value = "Count", DefaultValue = "$") int Count,model Model) {Model.addattribute ("Sp_list1", Spittlerepository.findspittles (Max, count));//page through SP_ List1 Get list System.out.println ("-------------------------output list"); return "Spittles";} /** * Receive page a parameter, * output a data * @param Spittleid * @param model * @return * http://localhost:8080/SpringInAction5_2_3/spittles/ 3 */@RequestMapping (value = "/spittle/{spittleid}", method = requestmethod.get) public String spittle (@PathVariable (" Spittleid ") long Spittleid, model model) {Model.addattribute (Spittlerepository.findone (Spittleid)); System.out.println ("-------------------------output single"); return "Spittle_show";} /** * Go to add page * @return */@RequestMapping (value = "/spittle/spittleadd", method = requestmethod.get) public String Spittlead D () {return "Spittle_add";} /** * Add a piece of data * @param form * @param model * @return * @throws Exception * Http://localhost:8080/SpringInAction5_2_3/spittl E/spittleadd */@RequestMaPping (value = "/spittle/spittleadd", method = requestmethod.post) public String savespittle (spittleform form, model model ) throws Exception {Spittlerepository.save (new spittle (NULL, Form.getmessage (), New Date (), Form.getlongitude (), Form.getlatitude ())); System.out.println ("-------------------------add List"); return "Spittle_add";}}
Spring4 in action-5.2.3-spring Web application-output list to page, receive parameters, receive form