您的位置:首页 > 移动开发

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

2016-03-04 15:15 525 查看
一、配置文件

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

}


四、
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: