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 }

四、

时间: 2024-10-28 12:25:12

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

SPRING IN ACTION 第4版笔记-第五章BUILDING SPRING WEB APPLICATIONS-002-Controller的requestMapping、model

一.RequestMapping 1.可以写在方法上或类上,且值可以是数组 1 package spittr.web; 2 3 import static org.springframework.web.bind.annotation.RequestMethod.*; 4 5 import org.springframework.stereotype.Controller; 6 import org.springframework.ui.Model; 7 import org.springfra

SPRING IN ACTION 第4版笔记-第七章Advanced Spring MVC-006- 如何保持重定向的request数据(用model、占位符、RedirectAttributes)

一.redirect为什么会丢数据? when a handler method completes, any model data specified in the method is copied into the request as request attributes, and the request is forwarded to the view for rendering. Because it’s the same request that’s handled by both

SPRING IN ACTION 第4版笔记-第七章Advanced Spring MVC-001- DispatcherServlet的高级配置(ServletRegistration.Dynamic、WebApplicationInitializer)

一. 1.如想在DispatcherServlet在Servlet容器中注册后自定义一些操作,如开启文件上传功能,则可重写通过AbstractAnnotationConfigDispatcherServletInitializer 的customizeRegistration() 来实现 1 // After AbstractAnnotation ConfigDispatcherServletInitializer registers DispatcherServlet with the ser

SPRING IN ACTION 第4版笔记-第四章ASPECT-ORIENTED SPRING-010-Introduction为类增加新方法

一. 1.Introduction的作用是给类动态的增加方法 When Spring discovers a bean annotated with @Aspect , it will automatically create a proxy that delegates calls to either the proxied bean or to the introduction implementation, depending on whether the method called be

SPRING IN ACTION 第4版笔记-第六章RENDERING WEB VIEWS-003- SPRING的GENERAL TAG LIBRARY简介及用&lt;s:message&gt;和ReloadableResourceBundleMessageSource实现国际化

一. SPRING支持的GENERAL TAG LIBRARY 1. 二.用<s:message>和ReloadableResourceBundleMessageSource实现国际化 1.配置ReloadableResourceBundleMessageSource,它能it has the ability to reload message properties without recompiling or restarting the application. 1 package spi

SPRING IN ACTION 第4版笔记-第六章Rendering web views-001- Spring支持的View Resolver、InternalResourceViewResolver、JstlView

一.Spring支持的View Resolver 二.InternalResourceViewResolver Spring supports JSP views in two ways:? InternalResourceViewResolver ? Spring provides two JSP tag libraries, one for form-to-model binding and one providing general utility features. 1.在java中定义

SPRING IN ACTION 第4版笔记-第十一章Persisting data with object-relational mapping-006Spring-Data的运行规则(@EnableJpaRepositories、&lt;jpa:repositories&gt;)

一.JpaRepository 1.要使Spring自动生成实现类的步骤 (1)配置文件xml 1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xm

SPRING IN ACTION 第4版笔记-第三章ADVANCING WIRING-006-给bean运行时注入值(Environment,Property文件)

一. 直观的给bean注入值如下: @Bean public CompactDisc sgtPeppers() { return new BlankDisc( "Sgt. Pepper's Lonely Hearts Club Band", "The Beatles"); } < bean id = "sgtPeppers" class = "soundsystem.BlankDisc" c: _title = &quo

SPRING IN ACTION 第4版笔记-第三章ADVANCING WIRING-005-Bean的作用域@Scope、ProxyMode

一. Spring的bean默认是单例的 But sometimes you may find yourself working with a mutable class that does main-tain some state and therefore isn’t safe for reuse. In that case, declaring the class as asingleton bean probably isn’t a good idea because that obje