SPRING IN ACTION 第4版笔记-第五章BUILDING SPRING WEB APPLICATIONS-003-示例项目用到的类及配置文件
一、配置文件
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
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-示例项目用到的类及配置文件的更多相关文章
- SPRING IN ACTION 第4版笔记-第五章Building Spring web applications-001-SpringMVC介绍
一. 二.用Java文件配置web application 1. package spittr.config; import org.springframework.web.servlet.suppo ...
- 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 ...
- 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 ...
- 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 ...
- SPRING IN ACTION 第4版笔记-第五章BUILDING SPRING WEB APPLICATIONS-002-Controller的requestMapping、model
一.RequestMapping 1.可以写在方法上或类上,且值可以是数组 package spittr.web; import static org.springframework.web.bind ...
- SPRING IN ACTION 第4版笔记-第五章BUILDING SPRING WEB APPLICATIONS-006-处理表单数据(注册、显示用户资料)
一.显示注册表单 1.访问资源 @Test public void shouldShowRegistration() throws Exception { SpitterRepository mock ...
- 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 ...
- 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 ...
- SPRING IN ACTION 第4版笔记-第七章Advanced Spring MVC-002- 在xml中引用Java配置文件,声明DispatcherServlet、ContextLoaderListener
一.所有声明都用xml 1. <?xml version="1.0" encoding="UTF-8"?> <web-app version= ...
随机推荐
- 将秒格式化为时分秒的JS函数
//时间格式化 function GetDateTime(time) { if (time >= 60 && time <= 3600) { time = parseInt ...
- ASP实现用年月日时分秒和两位随机数字来作为上传文件名的函数
Public Function GetNewFileName() dim ranNum dim dtNow dtNow=Now() randomize ranNum=int(90*rnd)+10 Ge ...
- JNI的一些使用
1.简介 Java Native Interface(JNI) 有时候我们必须要调用本地代码c/c++来克服java中的内存管理和性能限制.java支持通过Java Native Interface( ...
- HW-IP合法性_Java
描述 现在IPV4下用一个32位无符号整数来表示,一般用点分方式来显示,点将IP地址分成4个部分,每个部分为8位,表示成一个无符号整数(因此不需要用正号出现),如10.137.17.1,是我们非常熟悉 ...
- while循环语句
while(循环条件,返回布尔类型) { 代码执行的操作,或者打印输出. } do whilw循环 do { ...
- SVN-钩子
先说说钩子是干什么的吧,,简单的说,svn钩子就是在提交svn时前后所要触发的事件,于是我们可以用钩子做一些提交时的限制,及提交后的操作.最常用的一般有两个,pre-commit,post-commi ...
- C++例题练习(1)
环境:Dev-C++( Version:5.6.1) 一.求2个或3个正整数中的最大数,用带有默认参数的函数实现 代码实现: #include <iostream> using names ...
- [.Net MVC] 用户角色权限管理_使用CLK.AspNet.Identity
项目:后台管理平台 意义:一个完整的管理平台需要提供用户注册.登录等功能,以及认证和授权功能. 一.为何使用CLK.AspNet.Identity 首先简要说明所采取的权限控制方式.这里采用了基于角色 ...
- HDU 1069 Monkey and Banana(动态规划)
Monkey and Banana Problem Description A group of researchers are designing an experiment to test the ...
- springmvc学习(五)——处理模型数据
Spring MVC 提供了以下几种途径输出模型数据: ModelAndView: 处理方法返回值类型为 ModelAndView 时, 方法体即可通过该对象添加模型数据Map 及 Model: 入参 ...