一、配置文件

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

 package spittr.config;

 import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

 import spittr.web.WebConfig;

 public class SpitterWebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

   @Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[] { RootConfig.class };
} @Override
protected Class<?>[] getServletConfigClasses() {
//Specify configuration class
return new Class<?>[] { WebConfig.class };
} @Override
protected String[] getServletMappings() {
//Map DispatcherServlet to "/"
return new String[] { "/" };
} }

2.替代以前的web.xml

 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; @Configuration
@EnableWebMvc
@ComponentScan("spittr.web")
public class WebConfig extends WebMvcConfigurerAdapter { @Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
return resolver;
} @Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
//Configure static content handling
configurer.enable();
//configurer.enable();是you’re asking DispatcherServlet to forward
//requests for static resources to the servlet container’s default servlet and not to try to
//handle them itself.
} @Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
// TODO Auto-generated method stub
super.addResourceHandlers(registry);
} }

3.

 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; @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"));
}
}
}

4.数据源

 package spittr.config;

 import javax.sql.DataSource;

 import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.jdbc.core.JdbcOperations;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; @Configuration
//@ImportResource("classpath:applicationContext.xml")
public class DataConfig { @Bean
public DataSource dataSource() {
return new EmbeddedDatabaseBuilder()
.setType(EmbeddedDatabaseType.H2)
.addScript("schema.sql")
.build();
} @Bean
public JdbcOperations jdbcTemplate(DataSource dataSource) {
return new JdbcTemplate(dataSource);
} }

二、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.

 package spittr.data;

 import spittr.Spitter;

 public interface SpitterRepository {

   Spitter save(Spitter spitter);

   Spitter findByUsername(String username);

 }

3.

 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
public class JdbcSpittleRepository implements SpittleRepository { private JdbcOperations jdbc; @Autowired
public JdbcSpittleRepository(JdbcOperations jdbc) {
this.jdbc = jdbc;
} public List<Spittle> findRecentSpittles() {
return jdbc.query(
"select id, message, created_at, latitude, longitude" +
" from Spittle" +
" order by created_at desc limit 20",
new SpittleRowMapper());
} public List<Spittle> findSpittles(long max, int count) {
return jdbc.query(
"select id, message, created_at, latitude, longitude" +
" from Spittle" +
" where id < ?" +
" order by created_at desc limit 20",
new SpittleRowMapper(), max);
} public Spittle findOne(long id) {
return jdbc.queryForObject(
"select id, message, created_at, latitude, longitude" +
" from Spittle" +
" where id = ?",
new SpittleRowMapper(), id);
} public void save(Spittle spittle) {
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"));
}
} }

4.

 package spittr.data;

 import java.sql.ResultSet;
import java.sql.SQLException; 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.Spitter; @Repository
public class JdbcSpitterRepository implements SpitterRepository { private JdbcOperations jdbc; @Autowired
public JdbcSpitterRepository(JdbcOperations jdbc) {
this.jdbc = jdbc;
} public Spitter save(Spitter spitter) {
jdbc.update(
"insert into Spitter (username, password, first_name, last_name, email)" +
" values (?, ?, ?, ?, ?)",
spitter.getUsername(),
spitter.getPassword(),
spitter.getFirstName(),
spitter.getLastName(),
spitter.getEmail());
return spitter; // TODO: Determine value for id
} public Spitter findByUsername(String username) {
return jdbc.queryForObject(
"select id, username, null, first_name, last_name, email from Spitter where username=?",
new SpitterRowMapper(),
username);
} private static class SpitterRowMapper implements RowMapper<Spitter> {
public Spitter mapRow(ResultSet rs, int rowNum) throws SQLException {
return new Spitter(
rs.getLong("id"),
rs.getString("username"),
null,
rs.getString("first_name"),
rs.getString("last_name"),
rs.getString("email"));
}
} }

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.

 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.

 package spittr;

 import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size; import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.hibernate.validator.constraints.Email; public class Spitter { private Long id; @NotNull
@Size(min=5, max=16)
private String username; @NotNull
@Size(min=5, max=25)
private String password; @NotNull
@Size(min=2, max=30)
private String firstName; @NotNull
@Size(min=2, max=30)
private String lastName; @NotNull
@Email
private String email; public Spitter() {} public Spitter(String username, String password, String firstName, String lastName, String email) {
this(null, username, password, firstName, lastName, email);
} public Spitter(Long id, String username, String password, String firstName, String lastName, String email) {
this.id = id;
this.username = username;
this.password = password;
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
} public String getUsername() {
return username;
} public void setUsername(String username) {
this.username = username;
} public String getPassword() {
return password;
} public void setPassword(String password) {
this.password = password;
} public Long getId() {
return id;
} public void setId(Long id) {
this.id = id;
} public String getFirstName() {
return firstName;
} public void setFirstName(String firstName) {
this.firstName = firstName;
} public String getLastName() {
return lastName;
} public void setLastName(String lastName) {
this.lastName = lastName;
} public String getEmail() {
return email;
} public void setEmail(String email) {
this.email = email;
} @Override
public boolean equals(Object that) {
return EqualsBuilder.reflectionEquals(this, that, "firstName", "lastName", "username", "password", "email");
} @Override
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this, "firstName", "lastName", "username", "password", "email");
} }

四、

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

  1. SPRING IN ACTION 第4版笔记-第五章Building Spring web applications-001-SpringMVC介绍

    一. 二.用Java文件配置web application 1. package spittr.config; import org.springframework.web.servlet.suppo ...

  2. SPRING IN ACTION 第4版笔记-第五章BUILDING SPRING WEB APPLICATIONS-004-以query parameters的形式给action传参数(@RequestParam、defaultValue)

    一. 1.Spring MVC provides several ways that a client can pass data into a controller’s handler method ...

  3. SPRING IN ACTION 第4版笔记-第五章BUILDING SPRING WEB APPLICATIONS-007-表单验证@Valid、Error

    一. Starting with Spring 3.0, Spring supports the Java Validation API in Spring MVC . No extra config ...

  4. SPRING IN ACTION 第4版笔记-第五章BUILDING SPRING WEB APPLICATIONS-005-以path parameters的形式给action传参数(value=“{}”、@PathVariable)

    一 1.以path parameters的形式给action传参数 @Test public void testSpittle() throws Exception { Spittle expecte ...

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

    一.RequestMapping 1.可以写在方法上或类上,且值可以是数组 package spittr.web; import static org.springframework.web.bind ...

  6. SPRING IN ACTION 第4版笔记-第五章BUILDING SPRING WEB APPLICATIONS-006-处理表单数据(注册、显示用户资料)

    一.显示注册表单 1.访问资源 @Test public void shouldShowRegistration() throws Exception { SpitterRepository mock ...

  7. SPRING IN ACTION 第4版笔记-第七章Advanced Spring MVC-005- 异常处理@ResponseStatus、@ExceptionHandler、@ControllerAdvice

    No matter what happens, good or bad, the outcome of a servlet request is a servlet response. If an e ...

  8. SPRING IN ACTION 第4版笔记-第七章Advanced Spring MVC-003- 上传文件multipart,配置StandardServletMultipartResolver、CommonsMultipartResolver

    一.什么是multipart The Spittr application calls for file uploads in two places. When a new user register ...

  9. SPRING IN ACTION 第4版笔记-第七章Advanced Spring MVC-002- 在xml中引用Java配置文件,声明DispatcherServlet、ContextLoaderListener

    一.所有声明都用xml 1. <?xml version="1.0" encoding="UTF-8"?> <web-app version= ...

随机推荐

  1. Android的自动对焦

    1,什么是自动对焦? ---安卓的自动对焦的概念是指能够在指定的位置计算出准确的焦点位置. 这个就好像是传统意义上的手动对焦.但是google是这个意思. 2.什么是追焦? ----安卓的追焦是指FO ...

  2. 我的MFC学习之路(一)

    因为项目需求,我开始应用MFC写程序.具体接触MFC的时间大概也有两个月了.现在的水平算是刚刚踏入了MFC大门的半只脚.目前能基本使用MFC Class Wizard,可以根据实例仿照完成需求,小范围 ...

  3. 关于sql row_number,rank,dense_rank,ntile函数

    row_number排序最好用它,它依次排名,不出现相同名次,如:1,2,3,4,5 rank出现相同排名,且跳过相同的排名号排下一名,如:1,1,3,4,5, dense_rank出现相同排名,不跳 ...

  4. web开发常用图片格式

    web开发常用图片格式有:gif   jpg/jpeg    png gif:图片压缩率高,可以显示动画,但是只能显示256色,可能造成颜色丢失. jpg:图片压缩率高(有损压缩),可以用小文件来显示 ...

  5. UITableViewCell和UITableViewHeaderFooterView的重用

    不管是系统自带的还是自定义的UITableViewCell,对于它们合理的使用都是决定一个UITableView的性能的关键因素.应该确保以下三条: UITableViewCell的重复利用:首先对象 ...

  6. php json_encode()和json_decode()

    json_encode()和json_decode()分别是编译和反编译过程 注意json只接受utf-8编码的字符,所以json_encode()的参数必须是utf-8编码,否则会得到空字符或者nu ...

  7. iis7.5 aspx,ashx的mime类型

    映射aspx: 打开IIS管理器,找到“处理程序映射”,在列表右击选择“添加脚本映射”即可.eg:*.aspx,将该类型的页面的处理程序映射为“%windir%\Microsoft.NET\Frame ...

  8. position:absolute,绝对定位和相对定位,JQ隐藏和显示

    需要在指定位置,用绝对定位. 如果直接写position:absolute,top:0;left:0,那就是以浏览器的左上角为参照了 现在需要在某一个指定位置用绝对定位 解决方法 在需要用绝对定位(p ...

  9. php判断手机浏览还是web浏览,并执行相应的动作

    正好需要,在网上找了好久,记录一下 function isMobile(){ $useragent=isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTT ...

  10. PHP中如何设置error_reporting错误报告级别

    错误报告级别:指定了在什么情况下,脚本代码中的错误(这里的错误是广义的错误,包括E_NOTICE注意.E_WARNING警告.E_ERROR致命错误等)会以错误报告的形式输出.   设置错误报告级别的 ...