目标
记录spring 基础开发框架的搭建过程,这样在开始一个新项目的时候能节省很多时间。
步骤
一:开始一个新项目
通过spring template创建一个spring mvc项目,填入project name和top level package名称即可。
编译使用maven install即可,运行使用run on server,如果没有配置启动web server则配置下,这些步骤都很简单
如果运行成功无误,这一步就算通过了。
二:spring framework
这一步是选择frame的最新版本,写入pom.xml即可,重新编译运行
三:i18n
这一步的关键是要引入一个插件,用地址http://propedit.sourceforge.jp/eclipse/updates/安装
spring的servlet-context.xml文件需要加入以下内容:
<!-- i18n starts -->
<beans:bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<beans:property name="basename" value="classpath:messages" />
<beans:property name="defaultEncoding" value="UTF-8" />
</beans:bean>
<beans:bean id="localeChangeInterceptor"
class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<beans:property name="paramName" value="lang" />
</beans:bean>
<beans:bean id="localeResolver"
class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
<beans:property name="defaultLocale" value="cn" />
</beans:bean>
<beans:bean id="handlerMapping"
class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
<beans:property name="interceptors">
<beans:ref bean="localeChangeInterceptor" />
</beans:property>
</beans:bean>
<!-- i18n ends -->
利用刚才安装的插件在src/main/resources编辑messages_cn.properties文件,输入如下内容:
test.title=测试
在jsp页面中如下方式使用:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@ page session="false" %>
<html>
<head>
<title><spring:message code="test.title" /></title>
</head>
<body>
<h1>
Hello world!
</h1>
<P> The time on the server is ${serverTime}. </P>
</body>
</html>
重点是
<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<title><spring:message code="test.title" /></title>
至此i18n完成
四:apache tiles
在servlet中添加:
<!-- tiles -->
<beans:bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<beans:property name="viewClass">
<beans:value>
org.springframework.web.servlet.view.tiles2.TilesView
</beans:value>
</beans:property>
</beans:bean>
<beans:bean id="tilesConfigurer"
class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
<beans:property name="definitions">
<beans:list>
<beans:value>/WEB-INF/spring/appServlet/tiles.xml</beans:value>
</beans:list>
</beans:property>
</beans:bean>
在pom.xml中添加
<!-- tiles -->
<dependency>
<groupId>org.apache.tiles</groupId>
<artifactId>tiles-extras</artifactId>
<version>2.2.2</version>
</dependency>
注意版本不要选成3.0以上的,目前spring还支持的不好
最后是要创建/WEB-INF/spring/appServlet/tiles.xml文件,否则启动时候会报异常
五:mybatis
首先/src/main/resources添加Mysql.properties:
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/dbname?user=dbuser&password=dbpassword&useUnicode=true&characterEncoding=UTF-8
需要在pom.xml添加如下依赖:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<!-- mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.2.0</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.2.1</version>
</dependency>
<!-- mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.24</version>
</dependency>
root-contex.xml添加数据源
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/yourdbname" />
<property name="username" value="yourusername" />
<property name="password" value="yourpassword" />
</bean>
在servlet-context.xml添加:
<!-- mybatis starts -->
<context:property-placeholder location="classpath:Mysql.properties" />
<beans:bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<beans:property name="driverClassName" value="${jdbc.driverClassName}" />
<beans:property name="url" value="${jdbc.url}" />
</beans:bean>
<!-- define the SqlSessionFactory -->
<beans:bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<beans:property name="dataSource" ref="dataSource" />
<beans:property name="typeAliasesPackage" value="com.yourcorp.domain" />
</beans:bean>
<!-- scan for mappers and let them be autowired -->
<beans:bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<beans:property name="basePackage" value="com.yourcorp.mybatis.persistence" />
</beans:bean>
<!-- mybatis ends -->
在servletc-context.xml中还要添加:
<context:component-scan base-package="com.yourcorp.mybatis.service" />
最后要在对应的目录生成一个domain类,mapper.xml,对应的persistence类和serverce类,这个可以拷贝原来的实现,有一点要注意,在mapper.xml中:
<mapper namespace="com.yourcorp.mybatis.persistence.TestMapper">
<cache />
<insert id="insertName" >
INSERT INTO test
(name)
VALUES
("test success!")
</insert>
</mapper>
namespace一定要写对,否则程序无法启动成功
六:spring security
首先添加pom.xml
<spring-security.version>3.1.0.RELEASE</spring-security.version>
<!-- security begin -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>${spring-security.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>${spring-security.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>${spring-security.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
<version>${spring-security.version}</version>
</dependency>
<!-- security end -->
web.xml
<!-- SpringSecurity filter starts -->
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- SpringSecurity filter ends -->
在root-context.xml引入spring security配置文件:
<!-- springsecurity -->
<import resource="application-security.xml" />
在root-context.xml配置jdbcUserService
<bean class="org.springframework.security.authentication.encoding.ShaPasswordEncoder" id="passwordEncoder">
</bean>
<bean id="jdbcUserService" class="com.***.xxx.security.CustomJdbcDaoImpl">
<property name="dataSource" ref="dataSource" />
<property name="enableGroups" value="true" />
<property name="enableAuthorities" value="false" />
<property name="authenticationManager" ref="authenticationManager" />
<property name="usersByUsernameQuery">
<value>select username,password,enabled,nickname from users where username = ?</value>
</property>
</bean>
创建IChangePassword接口:
public interface IChangePassword extends UserDetailsService {
/**
* Changes the user's password. Note that a secure implementation would require
* the user to supply their existing password prior to changing it.
*
* @param username the username
* @param password the new password
*/
void changePassword(String username, String password);
}
创建AdUser类:
public class AdUser extends User implements UserDetails {
/**
*
*/
private static final long serialVersionUID = -4629529152422294513L;
private String salt;
public AdUser(String username, String password, boolean enabled,
boolean accountNonExpired, boolean credentialsNonExpired,
boolean accountNonLocked, List<GrantedAuthority> authorities, String salt) {
super(username, password, enabled, accountNonExpired, credentialsNonExpired,
accountNonLocked, authorities);
this.setSalt(salt);
}
/**
* @return the salt
*/
public String getSalt() {
return salt;
}
/**
* @param salt the salt to set
*/
public void setSalt(String salt) {
this.salt = salt;
}
}
创建CustomJdbcDaoImpl类:
public class CustomJdbcDaoImpl extends JdbcUserDetailsManager implements IChangePassword {
@Override
protected List<UserDetails> loadUsersByUsername(String username) {
return getJdbcTemplate().query(getUsersByUsernameQuery(), new String[] {username}, new RowMapper<UserDetails>() {
public UserDetails mapRow(ResultSet rs, int rowNum) throws SQLException {
String username = rs.getString(1);
String password = rs.getString(2);
boolean enabled = rs.getBoolean(3);
String nickname = rs.getString(4);
return new AdUser(username, password, enabled, true, true, true, AuthorityUtils.NO_AUTHORITIES, nickname);
}
});
}
@Override
public AdUser loadUserByUsername(String username){
final User user = (User)super.loadUserByUsername(username);
List<AdUser> sUsers = getJdbcTemplate().query(getUsersByUsernameQuery(), new String[] {username}, new RowMapper<AdUser>() {
public AdUser mapRow(ResultSet rs, int rowNum) throws SQLException {
String nickname = rs.getString(4);
return new AdUser(user.getUsername(),user.getPassword(),user.isEnabled()
,user.isAccountNonExpired(),user.isCredentialsNonExpired(),user.isAccountNonLocked()
,new ArrayList<GrantedAuthority>(user.getAuthorities()), nickname);
}
});
return sUsers.get(0);
/* SaltedUser saltedUser = new SaltedUser(user.getUsername(),user.getPassword(),user.isEnabled()
,user.isAccountNonExpired(),user.isCredentialsNonExpired(),user.isAccountNonLocked()
,new ArrayList<GrantedAuthority>(user.getAuthorities()),"sss");
return saltedUser;*/
}
public void updateNickname( String username, String nickname )
{
getJdbcTemplate().update(
"UPDATE users SET NICKNAME = ? WHERE USERNAME = ?",
nickname, username);
}
}
最后是创建
application-security.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:s="http://www.springframework.org/schema/security" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd"
default-lazy-init="true">
<s:authentication-manager alias="authenticationManager">
<s:authentication-provider user-service-ref="jdbcUserService">
<s:password-encoder ref="passwordEncoder"/>
</s:authentication-provider>
</s:authentication-manager>
<!-- 导入自定义的springsecurity国际化文件 -->
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:messages_zh_CN" />
</bean>
<bean id="localeResolver"
class="org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver" />
<s:http auto-config="true" use-expressions="true">
<s:form-login login-page="/index/login" authentication-failure-url="/index/login?error=true" default-target-url="/index" always-use-default-target="true" />
<s:logout logout-success-url="/index/login" invalidate-session="true" delete-cookies="JSESSIONID"/>
<s:intercept-url pattern="/admin/**" access="hasAnyRole('ROLE_SUPERADMIN')"/>
<s:intercept-url pattern="/vendoradmin/**" access="hasAnyRole('ROLE_ADMIN')"/>
</s:http>
<!-- 启动annotation -->
<s:global-method-security secured-annotations="enabled" />
</beans>