SPRING IN ACTION 第4版笔记-第五章BUILDING SPRING WEB APPLICATIONS-003-示例项目用到的类及配置文件

一、配置文件

1.由于它继承AbstractAnnotationConfigDispatcherServletInitializer,Servlet容器会把它当做配置文件

 1 package spittr.config;
 2 
 3 import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
 4 
 5 import spittr.web.WebConfig;
 6 
 7 public class SpitterWebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
 8   
 9   @Override
10   protected Class<?>[] getRootConfigClasses() {
11     return new Class<?>[] { RootConfig.class };
12   }
13 
14   @Override
15   protected Class<?>[] getServletConfigClasses() {
16     //Specify configuration class
17     return new Class<?>[] { WebConfig.class };
18   }
19 
20   @Override
21   protected String[] getServletMappings() {
22     //Map DispatcherServlet to "/"
23     return new String[] { "/" };
24   }
25 
26 }

2.替代以前的web.xml

 1 package spittr.web;
 2 
 3 import org.springframework.context.annotation.Bean;
 4 import org.springframework.context.annotation.ComponentScan;
 5 import org.springframework.context.annotation.Configuration;
 6 import org.springframework.web.servlet.ViewResolver;
 7 import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
 8 import org.springframework.web.servlet.config.annotation.EnableWebMvc;
 9 import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
10 import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
11 import org.springframework.web.servlet.view.InternalResourceViewResolver;
12 
13 @Configuration
14 @EnableWebMvc
15 @ComponentScan("spittr.web")
16 public class WebConfig extends WebMvcConfigurerAdapter {
17 
18   @Bean
19   public ViewResolver viewResolver() {
20     InternalResourceViewResolver resolver = new InternalResourceViewResolver();
21     resolver.setPrefix("/WEB-INF/views/");
22     resolver.setSuffix(".jsp");
23     return resolver;
24   }
25   
26   @Override
27   public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
28     //Configure static content handling
29     configurer.enable();    
30     //configurer.enable();是you’re asking  DispatcherServlet to forward
31     //requests for static resources to the servlet container’s default servlet and not to try to
32     //handle them itself.
33   }
34   
35   @Override
36   public void addResourceHandlers(ResourceHandlerRegistry registry) {
37     // TODO Auto-generated method stub
38     super.addResourceHandlers(registry);
39   }
40 
41 }

3.

 1 package spittr.config;
 2 
 3 import java.util.regex.Pattern;
 4 
 5 import org.springframework.context.annotation.ComponentScan;
 6 import org.springframework.context.annotation.ComponentScan.Filter;
 7 import org.springframework.context.annotation.Configuration;
 8 import org.springframework.context.annotation.FilterType;
 9 import org.springframework.context.annotation.Import;
10 import org.springframework.core.type.filter.RegexPatternTypeFilter;
11 
12 import spittr.config.RootConfig.WebPackage;
13 
14 @Configuration
15 @Import(DataConfig.class)
16 @ComponentScan(basePackages={"spittr"}, 
17     excludeFilters={
18         @Filter(type=FilterType.CUSTOM, value=WebPackage.class)
19     })
20 public class RootConfig {
21   public static class WebPackage extends RegexPatternTypeFilter {
22     public WebPackage() {
23       super(Pattern.compile("spittr\.web"));
24     }    
25   }
26 }

4.数据源

 1 package spittr.config;
 2 
 3 import javax.sql.DataSource;
 4 
 5 import org.springframework.context.annotation.Bean;
 6 import org.springframework.context.annotation.Configuration;
 7 import org.springframework.context.annotation.ImportResource;
 8 import org.springframework.jdbc.core.JdbcOperations;
 9 import org.springframework.jdbc.core.JdbcTemplate;
10 import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
11 import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
12 
13 @Configuration
14 //@ImportResource("classpath:applicationContext.xml")
15 public class DataConfig {
16 
17   @Bean
18   public DataSource dataSource() {
19     return new EmbeddedDatabaseBuilder()
20             .setType(EmbeddedDatabaseType.H2)
21             .addScript("schema.sql")
22             .build();
23   }
24   
25   @Bean
26   public JdbcOperations jdbcTemplate(DataSource dataSource) {
27     return new JdbcTemplate(dataSource);
28   }
29 
30 }

二、dao

1.

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);

}

2.

 1 package spittr.data;
 2 
 3 import spittr.Spitter;
 4 
 5 public interface SpitterRepository {
 6 
 7   Spitter save(Spitter spitter);
 8   
 9   Spitter findByUsername(String username);
10 
11 }

3.

 1 package spittr.data;
 2 
 3 import java.sql.ResultSet;
 4 import java.sql.SQLException;
 5 import java.util.List;
 6 
 7 import org.springframework.beans.factory.annotation.Autowired;
 8 import org.springframework.jdbc.core.JdbcOperations;
 9 import org.springframework.jdbc.core.RowMapper;
10 import org.springframework.stereotype.Repository;
11 
12 import spittr.Spittle;
13 
14 @Repository
15 public class JdbcSpittleRepository implements SpittleRepository {
16 
17   private JdbcOperations jdbc;
18 
19   @Autowired
20   public JdbcSpittleRepository(JdbcOperations jdbc) {
21     this.jdbc = jdbc;
22   }
23 
24   public List<Spittle> findRecentSpittles() {
25     return jdbc.query(
26         "select id, message, created_at, latitude, longitude" +
27         " from Spittle" +
28         " order by created_at desc limit 20",
29         new SpittleRowMapper());
30   }
31 
32   public List<Spittle> findSpittles(long max, int count) {
33     return jdbc.query(
34         "select id, message, created_at, latitude, longitude" +
35         " from Spittle" +
36         " where id < ?" +
37         " order by created_at desc limit 20",
38         new SpittleRowMapper(), max);
39   }
40 
41   public Spittle findOne(long id) {
42     return jdbc.queryForObject(
43         "select id, message, created_at, latitude, longitude" +
44         " from Spittle" +
45         " where id = ?",
46         new SpittleRowMapper(), id);
47   }
48 
49   public void save(Spittle spittle) {
50     jdbc.update(
51         "insert into Spittle (message, created_at, latitude, longitude)" +
52         " values (?, ?, ?, ?)",
53         spittle.getMessage(),
54         spittle.getTime(),
55         spittle.getLatitude(),
56         spittle.getLongitude());
57   }
58 
59   private static class SpittleRowMapper implements RowMapper<Spittle> {
60     public Spittle mapRow(ResultSet rs, int rowNum) throws SQLException {
61       return new Spittle(
62           rs.getLong("id"),
63           rs.getString("message"), 
64           rs.getDate("created_at"), 
65           rs.getDouble("longitude"), 
66           rs.getDouble("latitude"));
67     }
68   }
69   
70 }

4.

 1 package spittr.data;
 2 
 3 import java.sql.ResultSet;
 4 import java.sql.SQLException;
 5 
 6 import org.springframework.beans.factory.annotation.Autowired;
 7 import org.springframework.jdbc.core.JdbcOperations;
 8 import org.springframework.jdbc.core.RowMapper;
 9 import org.springframework.stereotype.Repository;
10 
11 import spittr.Spitter;
12 
13 @Repository
14 public class JdbcSpitterRepository implements SpitterRepository {
15   
16   private JdbcOperations jdbc;
17 
18   @Autowired
19   public JdbcSpitterRepository(JdbcOperations jdbc) {
20     this.jdbc = jdbc;
21   }
22 
23   public Spitter save(Spitter spitter) {
24     jdbc.update(
25         "insert into Spitter (username, password, first_name, last_name, email)" +
26         " values (?, ?, ?, ?, ?)",
27         spitter.getUsername(),
28         spitter.getPassword(),
29         spitter.getFirstName(),
30         spitter.getLastName(),
31         spitter.getEmail());
32     return spitter; // TODO: Determine value for id
33   }
34 
35   public Spitter findByUsername(String username) {
36     return jdbc.queryForObject(
37         "select id, username, null, first_name, last_name, email from Spitter where username=?", 
38         new SpitterRowMapper(), 
39         username);
40   }
41   
42   private static class SpitterRowMapper implements RowMapper<Spitter> {
43     public Spitter mapRow(ResultSet rs, int rowNum) throws SQLException {
44       return new Spitter(
45           rs.getLong("id"),
46           rs.getString("username"),
47           null,
48           rs.getString("first_name"),
49           rs.getString("last_name"),
50           rs.getString("email"));
51     }
52   }
53 
54 }

5.

create table Spittle (
    id identity,
    message varchar(140) not null,
    created_at timestamp not null,
    latitude double,
    longitude double
);

create table Spitter (
    id identity,
    username varchar(20) unique not null,
    password varchar(20) not null,
    first_name varchar(30) not null,
    last_name varchar(30) not null,
    email varchar(30) not null
);

6.log4j.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration PUBLIC "-//APACHE//DTD LOG4J 1.2//EN" "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">

    <!-- Appenders -->
    <appender name="console" class="org.apache.log4j.ConsoleAppender">
        <param name="Target" value="System.out" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%-5p: %c - %m%n" />
        </layout>
    </appender>
    
    <!-- Application Loggers -->
    <logger name="spittr">
        <level value="info" />
    </logger>
    
    <!-- 3rdparty Loggers -->
    <logger name="org.springframework.core">
        <level value="info" />
    </logger>
    
    <logger name="org.springframework.beans">
        <level value="info" />
    </logger>
    
    <logger name="org.springframework.context">
        <level value="info" />
    </logger>

    <logger name="org.springframework.web">
        <level value="info" />
    </logger>

    <!-- Root Logger -->
    <root>
        <priority value="warn" />
        <appender-ref ref="console" />
    </root>
    
</log4j:configuration>

三、实体类

1.

 1 package spittr;
 2 
 3 import java.util.Date;
 4 
 5 import org.apache.commons.lang3.builder.EqualsBuilder;
 6 import org.apache.commons.lang3.builder.HashCodeBuilder;
 7 
 8 public class Spittle {
 9 
10   private final Long id;
11   private final String message;
12   private final Date time;
13   private Double latitude;
14   private Double longitude;
15 
16   public Spittle(String message, Date time) {
17     this(null, message, time, null, null);
18   }
19   
20   public Spittle(Long id, String message, Date time, Double longitude, Double latitude) {
21     this.id = id;
22     this.message = message;
23     this.time = time;
24     this.longitude = longitude;
25     this.latitude = latitude;
26   }
27 
28   public long getId() {
29     return id;
30   }
31 
32   public String getMessage() {
33     return message;
34   }
35 
36   public Date getTime() {
37     return time;
38   }
39   
40   public Double getLongitude() {
41     return longitude;
42   }
43   
44   public Double getLatitude() {
45     return latitude;
46   }
47   
48   @Override
49   public boolean equals(Object that) {
50     return EqualsBuilder.reflectionEquals(this, that, "id", "time");
51   }
52   
53   @Override
54   public int hashCode() {
55     return HashCodeBuilder.reflectionHashCode(this, "id", "time");
56   }
57   
58 }

2.

  1 package spittr;
  2 
  3 import javax.validation.constraints.NotNull;
  4 import javax.validation.constraints.Size;
  5 
  6 import org.apache.commons.lang3.builder.EqualsBuilder;
  7 import org.apache.commons.lang3.builder.HashCodeBuilder;
  8 import org.hibernate.validator.constraints.Email;
  9 
 10 public class Spitter {
 11 
 12   private Long id;
 13   
 14   @NotNull
 15   @Size(min=5, max=16)
 16   private String username;
 17 
 18   @NotNull
 19   @Size(min=5, max=25)
 20   private String password;
 21   
 22   @NotNull
 23   @Size(min=2, max=30)
 24   private String firstName;
 25 
 26   @NotNull
 27   @Size(min=2, max=30)
 28   private String lastName;
 29   
 30   @NotNull
 31   @Email
 32   private String email;
 33 
 34   public Spitter() {}
 35   
 36   public Spitter(String username, String password, String firstName, String lastName, String email) {
 37     this(null, username, password, firstName, lastName, email);
 38   }
 39 
 40   public Spitter(Long id, String username, String password, String firstName, String lastName, String email) {
 41     this.id = id;
 42     this.username = username;
 43     this.password = password;
 44     this.firstName = firstName;
 45     this.lastName = lastName;
 46     this.email = email;
 47   }
 48 
 49   public String getUsername() {
 50     return username;
 51   }
 52 
 53   public void setUsername(String username) {
 54     this.username = username;
 55   }
 56 
 57   public String getPassword() {
 58     return password;
 59   }
 60 
 61   public void setPassword(String password) {
 62     this.password = password;
 63   }
 64 
 65   public Long getId() {
 66     return id;
 67   }
 68 
 69   public void setId(Long id) {
 70     this.id = id;
 71   }
 72 
 73   public String getFirstName() {
 74     return firstName;
 75   }
 76 
 77   public void setFirstName(String firstName) {
 78     this.firstName = firstName;
 79   }
 80 
 81   public String getLastName() {
 82     return lastName;
 83   }
 84 
 85   public void setLastName(String lastName) {
 86     this.lastName = lastName;
 87   }
 88   
 89   public String getEmail() {
 90     return email;
 91   }
 92   
 93   public void setEmail(String email) {
 94     this.email = email;
 95   }
 96 
 97   @Override
 98   public boolean equals(Object that) {
 99     return EqualsBuilder.reflectionEquals(this, that, "firstName", "lastName", "username", "password", "email");
100   }
101   
102   @Override
103   public int hashCode() {
104     return HashCodeBuilder.reflectionHashCode(this, "firstName", "lastName", "username", "password", "email");
105   }
106 
107 }

四、