源代码链接:http://download.csdn.net/download/poiuy1991719/10117665
本代码是基于数据库表的操作,所以请先建立数据库表
1、建立Bean对象
package spittr; import java.util.Date; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; /** * 博客信息 */ public class Spittle { private final Long id; private final String message; private final Date time; private Double latitude; private Double longitude; public Spittle(String message, Date time) { this(null, message, time, null, null); } public Spittle(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 long getId() { return id; } public String getMessage() { return message; } public Date getTime() { return time; } public Double getLongitude() { return longitude; } public Double getLatitude() { return latitude; } @Override public boolean equals(Object that) { return EqualsBuilder.reflectionEquals(this, that, "id", "time"); } @Override public int hashCode() { return HashCodeBuilder.reflectionHashCode(this, "id", "time"); } }
2、编写Web配置类:
package spittr.config; import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; import spittr.web.WebConfig; /*** * 容器会找到AbstractAnnotationConfigDispatcherServletInitializer这个类(包括这个类的扩展) * 然后用这个类来配置Servlet上下文 */ public class SpitterWebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { @Override protected Class<?>[] getRootConfigClasses() {//非Web组件,带有@Configuration注解的类用来定义应用上下文 return new Class<?>[] { RootConfig.class }; } @Override protected Class<?>[] getServletConfigClasses() {//指定配置类,带有@Configuration注解的类用来定义应用上下文 return new Class<?>[] { WebConfig.class }; } @Override protected String[] getServletMappings() {// 将DispatcherServlet映射到"/" return new String[] { "/" }; } }
3、Web配置类中,用到WebConfig类:
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; /*** * 配置web */ @Configuration //配置类,需要的注解 @EnableWebMvc //启用Spring MVC @ComponentScan("spittr.web") //启用组件扫描,就会扫描到控制器 public class WebConfig extends WebMvcConfigurerAdapter { @Bean public ViewResolver viewResolver() {//配置JSP视图解析器 InternalResourceViewResolver resolver = new InternalResourceViewResolver(); resolver.setPrefix("/WEB-INF/views/");//在请求路径前,加入资源路径 resolver.setSuffix(".jsp");//在请求路径后,加入资源名称,比如/WEB-INF/views/home.jsp resolver.setViewClass(org.springframework.web.servlet.view.JstlView.class); return resolver; } @Override public void configureDefaultServletHandling( //处理静态资源 DefaultServletHandlerConfigurer configurer) { configurer.enable(); } @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { super.addResourceHandlers(registry); } }
4、Web配置类用到Root类,用来加载其它组件:
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; /*** * 引入数据库配置类 自动扫描spittr包,以及子包 */ @Configuration // 配置类,需要的注解 @Import(DataConfig.class) @ComponentScan(basePackages = { "spittr" }, excludeFilters = { @Filter(type = FilterType.CUSTOM, value = WebPackage.class) }) public class RootConfig { public static class WebPackage extends RegexPatternTypeFilter { public WebPackage() { super(Pattern.compile("spittr\.web")); } } }
5、Root类中加载了数据库链接类:
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; @Configuration public class DataConfig { @Bean public DataSource dataSource() { DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName("com.mysql.jdbc.Driver"); dataSource.setUrl("jdbc:mysql:///spittle"); dataSource.setUsername("root"); dataSource.setPassword("root"); return dataSource; } @Bean public JdbcOperations jdbcTemplate(DataSource dataSource) { return new JdbcTemplate(dataSource); } }
6、数据操作接口、数据操作接口实现:
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 //将数据访问层 (DAO 层 ) 的类标识为 Spring Bean public class JdbcSpittleRepository implements SpittleRepository { private JdbcOperations jdbc; @Autowired public 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 20", new SpittleRowMapper()); // System.out.println("---findRecentSpittles被调用---返回List列表:"+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 20", new SpittleRowMapper(), max); // System.out.println("---findSpittles被调用---返回List列表:"+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被调用---返回Spittle对象:"+spittle.getMessage()); return spittle; } public void save(Spittle spittle) { // System.out.println("---save被调用---Spittle对象:"+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、编写添加数据的表单类:
package spittr.web.spittle; import javax.validation.constraints.Max; import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; /** * 页面表单对应模型 */ public class SpittleForm { @NotNull @Size(min=1, max=140) private String message; @Min(-180) @Max(180) private Double longitude; @Min(-90) @Max(90) 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、编写控制类,实现页面数据接收、页面跳转等
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; @Controller public class SpittleController { private static final String MAX_LONG_AS_STRING = "9223372036854775807"; private SpittleRepository spittleRepository; @Autowired public SpittleController(SpittleRepository spittleRepository) { this.spittleRepository = spittleRepository; } /** * 页面输出列表 * @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 = "20") int count, Model model) { model.addAttribute("sp_list1", spittleRepository.findSpittles(max, count));//页面通过sp_list1取得列表 System.out.println("-------------------------输出列表"); return "spittles"; } /** * 接收页面一个参数, * 输出一条数据 * @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("-------------------------输出单个"); return "spittle_show"; } /** * 进入添加页面 * @return */ @RequestMapping(value = "/spittle/spittleadd",method = RequestMethod.GET) public String spittleAdd(){ return "spittle_add"; } /** * 添加一条数据 * @param form * @param model * @return * @throws Exception * http://localhost:8080/SpringInAction5_2_3/spittle/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("-------------------------添加列表"); return "spittle_add"; } }