springmvc的web工程通用配置:
- 1.web.xml
- 2.applicationContext.xml(包含初始化调度器)
-
- 3.listener
-
- 4.filter
-
- SQL、JS脚本 注入攻击过滤器
- XSS 跨站请求攻击过滤器
- 5.springmvc-servlet.xml
1.web.xml
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<context-param>
<param-name>contextConfigLocationparam-name>
<param-value>
classpath:spring/applicationContext.xml
param-value>
context-param>
<context-param>
<param-name>sslparam-name>
<param-value>8443param-value>
context-param>
<context-param>
<param-name>httpparam-name>
<param-value>8080param-value>
context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
listener>
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListenerlistener-class>
listener>
<listener>
<listener-class>
com.huawei.ecommerce.common.base.utils.SpringBeanGetter
listener-class>
listener>
<filter>
<filter-name>corsfilterfilter-name>
<filter-class>com.huawei.ecsp.common.filter.CorsFilterfilter-class>
filter>
<filter-mapping>
<filter-name>corsfilterfilter-name>
<url-pattern>/*url-pattern>
<dispatcher>REQUESTdispatcher>
filter-mapping>
<filter>
<filter-name>characterEncodingFilterfilter-name>
<filter-class>
com.huawei.ecommerce.common.base.web.filter.CharacterEncodingFilter
filter-class>
<init-param>
<param-name>encodingparam-name>
<param-value>UTF-8param-value>
init-param>
filter>
<context-param>
<param-name>
weblogic.httpd.inputCharset./*
param-name>
<param-value>UTF-8param-value>
context-param>
<filter-mapping>
<filter-name>characterEncodingFilterfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
<filter>
<filter-name>xssFilterfilter-name>
<filter-class>com.huawei.esysadmin.common.filter.XssFilterfilter-class>
filter>
<filter-mapping>
<filter-name>xssFilterfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
<filter>
<filter-name>xssCsrfFilterfilter-name>
<filter-class>com.huawei.esysadmin.common.filter.XssCsrfFilterfilter-class>
filter>
<filter-mapping>
<filter-name>xssCsrfFilterfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
<servlet>
<servlet-name>springmvcservlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
<init-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:springmvc-servlet.xmlparam-value>
init-param>
servlet>
<servlet-mapping>
<servlet-name>springmvcservlet-name>
<url-pattern>/url-pattern>
servlet-mapping>
<servlet>
<servlet-name>freemarkerservlet-name>
<servlet-class>
freemarker.ext.servlet.FreemarkerServlet
servlet-class>
servlet>
<servlet-mapping>
<servlet-name>freemarkerservlet-name>
<url-pattern>*.ftlurl-pattern>
servlet-mapping>
<welcome-file-list>
<welcome-file>index.htmlwelcome-file>
welcome-file-list>
<session-config>
<session-timeout>30session-timeout>
session-config>
web-app>
2.applicationContext.xml(包含初始化调度器)
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd">
<aop:aspectj-autoproxy>
<aop:include name="xxxAspect" />
aop:aspectj-autoproxy>
<bean id="GlobalConfig"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:datasource.propertiesvalue>
list>
property>
bean>
<bean id="dataSource_config" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${xxx.jdbc.driverClassName}" />
<property name="url" value="${xxx.jdbc.url}" />
<property name="username" value="${xxx.jdbc.username}" />
<property name="password" value="${xxx.jdbc.password}" />
bean>
<bean id="sqlSessionFactoryConfig" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="configLocation" value="classpath:mybatis/sqlmap-config-config.xml">property>
<property name="dataSource" ref="dataSource_config">property>
bean>
<bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactoryConfig">constructor-arg>
bean>
<bean id="transactionManager_config"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource_config">property>
bean>
<tx:advice id="txAdvice_config" transaction-manager="transactionManager_config">
<tx:attributes>
<tx:method name="add*" propagation="REQUIRED" rollback-for="Throwable" />
<tx:method name="save*" propagation="REQUIRED" rollback-for="Throwable" />
<tx:method name="insert*" propagation="REQUIRED" rollback-for="Throwable" />
<tx:method name="edit*" propagation="REQUIRED" rollback-for="Throwable" />
<tx:method name="modify*" propagation="REQUIRED" rollback-for="Throwable" />
<tx:method name="update*" propagation="REQUIRED" rollback-for="Throwable" />
<tx:method name="commit*" propagation="REQUIRED" rollback-for="Throwable" />
<tx:method name="*Commit*" propagation="REQUIRED" rollback-for="Throwable" />
<tx:method name="remove*" propagation="REQUIRED" rollback-for="Throwable" />
<tx:method name="del*" propagation="REQUIRED" rollback-for="Throwable" />
<tx:method name="cancle*" propagation="REQUIRED" rollback-for="Throwable" />
<tx:method name="resumeJob*" propagation="REQUIRED" rollback-for="Throwable" />
tx:attributes>
tx:advice>
<aop:config>
<aop:pointcut id="shoppingAllMethod_config"
expression="execution(* *..service.impl.*.*(..))" />
<aop:advisor advice-ref="txAdvice_config" pointcut-ref="shoppingAllMethod_config" />
aop:config>
<bean id="Manager" class="com.xxx.Manager" factory-method="getInstance" init-method="init">bean>
<!加载本工程其他spring文件 -->
<import resource="classpath:spring/applicationContext_*.xml" />
beans>
创建调度器
public class Manager implements Runnable
{
private static final Logger logger = Logger.getLogger(Manager.class);
ScheduledExecutorService scheduleService = null;
private final static Manager loader = new Manager();
private Manager()
{
}
public static Manager getInstance()
{
return loader;
}
public void init()
{
scheduleService = Executors.newScheduledThreadPool(1);
scheduleService.scheduleAtFixedRate(this, 30, 180, TimeUnit.SECONDS);
}
@Override
public void run()
{
try
{
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
3.listener
SpringBeanGetter
public class SpringBeanGetter implements ServletContextListener {
private static ServletContext context = null;
private static final Logger logger = Logger.getLogger(SpringBeanGetter.class);
private static int errorCount = 0;
public void contextDestroyed(ServletContextEvent arg0) {
setContext(null);
}
public void contextInitialized(ServletContextEvent arg0) {
setContext(arg0.getServletContext());
}
private static final void setContext(ServletContext context)
{
SpringBeanGetter.context = context;
}
public final static <T> T getBean(String beanId) {
WebApplicationContext application = WebApplicationContextUtils
.getWebApplicationContext(context);
while (application == null && errorCount < 5) {
try {
Thread.currentThread().sleep(3000);
application = WebApplicationContextUtils
.getWebApplicationContext(context);
logger.error(" 未找到applicationContext 对象");
errorCount++;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if(null != application)
{
return (T) application.getBean(beanId);
}
return null;
}
}
4.filter
SQL、JS脚本 注入攻击过滤器
public class XssFilter extends BaseFilter implements Filter
{
private static final Log logger = LogFactory.getLog(XssFilter.class);
private String[] mustFilterUrlList = null;
private String[] notFilterUrlList = null;
private String[] filterWordList = null;
private String[] ignorWordList = null;
public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
throws IOException, ServletException
{
HttpServletRequest request = (HttpServletRequest)arg0;
HttpServletResponse response = (HttpServletResponse)arg1;
String url = request.getRequestURI();
if (this.ignoreUrlFromWeb(url.replaceAll(request.getContextPath(), "")))
{
arg2.doFilter(request, response);
return;
}
url = request.getRequestURI()+"?"+request.getQueryString();
if (this.isUrlMustFilter(url))
{
response.setStatus(404);
return;
}
if (this.isUrlNotFilter(url))
{
arg2.doFilter(arg0, arg1);
return;
}
String queryString = request.getQueryString();
if (containsIllegalWord(queryString))
{
throw new Exception("invalid request");
}
Enumeration<String> params = request.getParameterNames();
if (null != params)
{
String paramName = null;
String[] paramValues = null;
while (params.hasMoreElements())
{
paramName = params.nextElement();
paramValues = request.getParameterValues(paramName);
if (null == paramValues)
{
continue;
}
for (String value : paramValues)
{
if (this.containsIllegalWord(value))
{
throw new Exception("invalid request");
}
}
}
}
String type = request.getContentType();
if (StringUtils.isBlank(type) || !type.startsWith("application/json"))
{
arg2.doFilter(request, arg1);
return;
}
ServletRequest requestWrapper = null;
if (request instanceof HttpServletRequest)
{
requestWrapper = new ReaderReuseHttpServletRequestWrapper(request);
}
Reader reader = requestWrapper.getReader();
String payload = IOUtils.toString(reader);
if (StringUtils.isNotBlank(type) && type.startsWith("application/json"))
{
parseJSONString(payload, request, response);
}
else
{
Enumeration<String> params1 = request.getParameterNames();
if (null != params1)
{
String paramName = null;
String[] paramValues = null;
while (params1.hasMoreElements())
{
paramName = params1.nextElement();
paramValues = request.getParameterValues(paramName);
if (null == paramValues)
{
continue;
}
for (String value : paramValues)
{
if (this.containsIllegalWord(value))
{
throw new Exception("invalid request");
}
}
}
}
}
arg2.doFilter(requestWrapper, arg1);
}
private boolean isUrlMustFilter(String url)
{
}
private boolean isUrlNotFilter(String url)
{
url = url.toLowerCase(Locale.US);
return false;
}
private boolean containsIllegalWord(String s)
{
}
public static class ReaderReuseHttpServletRequestWrapper extends HttpServletRequestWrapper
{
private final byte[] body;
public ReaderReuseHttpServletRequestWrapper(HttpServletRequest request) throws IOException
{
super(request);
body = IOUtils.toString(request.getReader()).getBytes(Charset.forName("UTF-8"));
}
@Override
public BufferedReader getReader() throws IOException
{
return new BufferedReader(new InputStreamReader(getInputStream()));
}
@Override
public ServletInputStream getInputStream() throws IOException
{
final ByteArrayInputStream bais = new ByteArrayInputStream(body);
return new ServletInputStream()
{
@Override
public int read() throws IOException
{
return bais.read();
}
};
}
}
public Object parseJSONString(String jsonString, HttpServletRequest request, HttpServletResponse response)
{
JSONArray jsonArray = null;
JSONObject jsonObj = null;
System.out.println("入参:"+jsonString);
if (jsonString.startsWith("["))
{
jsonArray = JSONArray.parseArray(jsonString);
return parseJSONArr(jsonArray, request, response);
}
else
{
jsonObj = JSONObject.parseObject(jsonString);
return parseJSONObj(jsonObj, request, response);
}
}
public Map<String, Object> parseJSONObj(JSONObject jsonObj, HttpServletRequest request,
HttpServletResponse response)
{
Map<String, Object> paramMap = new HashMap<String, Object>();
if (null == jsonObj)
{
return paramMap;
}
String val = "";
Object obj = null;
for (Map.Entry<String, Object> entry : jsonObj.entrySet())
{
val = JSONObject.toJSONString(entry.getValue());
if (val.startsWith("{") || val.startsWith("["))
{
obj = parseJSONString(val, request, response);
paramMap.put(entry.getKey(), obj);
}
else
{
if (containsIllegalWord(String.valueOf(entry.getValue())))
{
logger.info("XssFilter filtered invalid input param \"" + entry.getKey() + "\" with values \""
+ entry.getValue() + "\", and will redirect to error page.");
throw new ESysAdminException("invalid request");
}
paramMap.put(entry.getKey(), entry.getValue());
}
}
return paramMap;
}
public List<Object> parseJSONArr(JSONArray jsonArray, HttpServletRequest request, HttpServletResponse response)
{
List<Object> paramList = new ArrayList<Object>();
if (null == jsonArray)
{
return paramList;
}
String val = "";
Object obj = null;
Iterator<Object> iterator = jsonArray.iterator();
while (iterator.hasNext())
{
obj = iterator.next();
val = JSONObject.toJSONString(obj);
if (val.startsWith("{") || val.startsWith("["))
{
paramList.add(parseJSONString(val, request, response));
}
else
{
if (containsIllegalWord(String.valueOf(obj)))
{
logger.error("XssFilter filtered invalid input param with values \"" + obj
+ "\", and will redirect to error page.");
throw new ESysAdminException("invalid request");
}
paramList.add(obj);
}
}
return paramList;
}
public void init(FilterConfig arg0) throws ServletException
{
String must = arg0.getInitParameter("mustFilterUrlList");
if (StringUtils.isNotBlank(must))
{
must = must.toLowerCase(Locale.US);
mustFilterUrlList = must.split(",");
logger.info("init XssFilter with must filter url:" + must);
}
String not = arg0.getInitParameter("notFilterUrlList");
if (StringUtils.isNotBlank(not))
{
not = not.toLowerCase(Locale.US);
notFilterUrlList = not.split(",");
logger.info("init XssFilter with not filter url:" + not);
}
String filterWords = arg0.getInitParameter("filterWords");
if (StringUtils.isNotBlank(filterWords))
{
filterWords = filterWords.trim().toLowerCase(Locale.US);
filterWordList = filterWords.split(",");
logger.info("init XssFilter with filter words:" + filterWords);
}
String ignorWords = arg0.getInitParameter("ignorWords");
if (StringUtils.isNotBlank(ignorWords))
{
ignorWords = ignorWords.trim().toLowerCase(Locale.US);
ignorWordList = ignorWords.split(",");
logger.info("init XssFilter with ignor words:" + ignorWords);
}
}
public void destroy()
{
this.mustFilterUrlList = null;
this.notFilterUrlList = null;
this.filterWordList = null;
this.ignorWordList = null;
}
}
XSS 跨站请求攻击过滤器
5.springmvc-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">
<mvc:annotation-driven />
<context:component-scan base-package="com.xxxx"/>
<mvc:default-servlet-handler />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
<!-- 前缀 -->
<property name="prefix" value="/WEB-INF/" />
<!-- 后缀 -->
<property name="suffix" value=".jsp" />
</bean>
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="20971520"></property>
</bean>
<!-- <mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/mvc/**"/>
<bean class="com.huawei.springmvc.interceptor.MyInterceptor"></bean>
</mvc:interceptor>
</mvc:interceptors> -->
</beans>