1.applicationContext.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:p="http://www.springframework.org/schema/p" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 扫描的包 --> <!-- <context:component-scan base-package="app04"/> --> <!-- 使用转换器 --> <!--<mvc:annotation-driven conversion-service="conversionService"/>--> <!-- 使用格式化 --> <!-- conversionService2 --> <!-- <mvc:annotation-driven conversion-service="conversionService2"/> --> <!-- 使用注册器替代格式化 --> <!-- <mvc:annotation-driven />意思是开启使用注释的功能--> <!-- conversionService3是格式化或者转换器 --> <!-- <mvc:annotation-driven conversion-service="conversionService3"/> --> <!-- 扫描的包 --> <context:component-scan base-package="sfk.bbs.test.testSpringMVCConfig.action"/> <!-- 这个的作用是让DispatcherServlet不将下列路径理解为一个request请求, 在项目中,这个是必须的,如果没有加这些就可能造成上述问题 --> <mvc:annotation-driven /> <mvc:resources mapping="/css/**" location="/css/"/> <mvc:resources mapping="/js/**" location="/js/"/> <mvc:resources mapping="/*.html" location="/"/> <!-- 视图解析器 --> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/pages/"/> <property name="suffix" value=".jsp"/> </bean> <!-- 读取配置文件信息,在Spring的配置文件中使用EL表达式填充值 --> <context:property-placeholder location="classpath:jdbc.properties"/> <!-- 配置数据库连接池 --> <bean id="dataSourceLocal" name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <!-- 指定连接数据库的驱动--> <property name="driverClass" value="${jdbc.driverClassName}"/> <!-- 指定连接数据库的URL--> <property name="jdbcUrl" value="${jdbc.url}"/> <!-- 指定连接数据库的用户名--> <property name="user" value="${jdbc.username}"/> <!-- 指定连接数据库的密码--> <property name="password" value="${jdbc.password}"/> <!-- 指定连接池中保留的最大连接数. Default:15--> <property name="maxPoolSize" value="${jdbc.maxPoolSize}"/> <!-- 指定连接池中保留的最小连接数--> <property name="minPoolSize" value="${jdbc.minPoolSize}"/> <!-- 指定连接池的初始化连接数 取值应在minPoolSize 与 maxPoolSize 之间.Default:3--> <property name="initialPoolSize" value="${jdbc.initialPoolSize}"/> <!-- 最大空闲时间,60秒内未使用则连接被丢弃。若为0则永不丢弃。 Default:0--> <property name="maxIdleTime" value="${jdbc.maxIdleTime}"/> <!-- 当连接池中的连接耗尽的时候c3p0一次同时获取的连接数. Default:3--> <property name="acquireIncrement" value="${jdbc.acquireIncrement}"/> <!-- JDBC的标准,用以控制数据源内加载的PreparedStatements数量。 但由于预缓存的statements属于单个connection而不是整个连接池所以设置这个参数需要考虑到多方面的因数.如果maxStatements与maxStatementsPerConnection均为0,则缓存被关闭。Default:0--> <property name="maxStatements" value="${jdbc.maxStatements}"/> <!-- 每60秒检查所有连接池中的空闲连接.Default:0 --> <property name="idleConnectionTestPeriod" value="${jdbc.idleConnectionTestPeriod}"/> </bean> <!-- <bean id="dataSourceLocal" name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> 制定连接数据库的驱动 <property name="driverClass" value="${jdbc.driverClassName}" /> 制定连接数据库的URL <property name="jdbcUrl" value="${jdbc.url}" /> 指定连接数据库的用户名 <property name="user" value="${jdbc.username}" /> 指定数据库的密码 <property name="password" value="${jdbc.password}"/> 指定连接池中保留的最大连接数 default:15 <property name="maxPoolSize" value="${jdbc.maxPoolSize}"/> 指定连接池中保留的最小连接数 <property name="minPoolSize" value="${jdbc.minPoolSize}" /> 指定连接池的初始化连接数 取值应在minPoolSize 与MaxPoolSize之间,Default:3 <property name="initialPoolSize" value="${jdbc.initialPoolSize}"/> 最大空闲时间,60秒内未使用连接被丢弃,若为0则永不丢弃,Default:0 <property name="maxIdleTime" value="${jdbc.maxIdleTime}"/> 当连接池中的连接耗尽的时候c3p0一次同时获取的连接数. default: 3 <property name="acquireIncrement" value="${jdbc.acquireIncrement}" /> JDBC的标准,用以控制数据源内加载的prepareedStatement数量.但是由于预缓存的statements 属于单个connection而不是整个连接池所以色绘制这个参数需要考虑到多方面的因素,如果maxStatements 与maxStatementsPerConnection均为0,则缓存被关闭,Default:0 <property name="maxStatements" value="${jdbc.maxStatements}"/> 每60秒检查所有连接池中的空闲连接default:0 <property name="idleConnectionTestPeriod" value="${jdbc.idleConnectionTestPeriod}" /> </bean> --> <!-- 错误提示信息配置,用配置文件管理错误信息 --> <!-- <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource"> <property name="basename" value="/WEB-INF/resource/messages" /> </bean> --> <!-- org.springframework.context.support.ConversionServiceFactoryBean.class --> <!-- 使用转换器的bean --> <!-- <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean"> <property name="converters"> <list> <bean class="app06a.converter.StringToDateConverter" > <constructor-arg type="java.lang.String" value="MM-dd-yyyy"/> </bean> </list> </property> </bean> --> <!-- 使用Formatter的格式化 --> <!-- <bean id="conversionService2" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"> <property name="formatters"> <set> /springMVC/src/app06a/formatter/DateFormatter.java <bean class="app06a.formatter.DateFormatter"> <constructor-arg type="java.lang.String" value="MM-dd-yyyy"/> </bean> </set> </property> </bean> --> <!-- 使用注册器替代Formatter的格式化 --> <!-- <bean id="conversionService3" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"> <property name="formatterRegistrars"> <set> /springMVC/src/app06a/formatter/DateFormatter.java <bean class="app06a.formatter.MyFormatterRigistrar"> <constructor-arg type="java.lang.String" value="MM-dd-yyyy"/> </bean> </set> </property> </bean> --> </beans>
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1"> <display-name>sfk_BBS02</display-name> <!-- <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> --> <!-- <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/resource/applicationContext.xml</param-value> </context-param> --> <!-- config log4j first Part --> <context-param> <param-name>log4jConfigLocation</param-name> <param-value>classpath:log4j.properties</param-value> </context-param> <!-- /WEB-INF/classes/applicationContext-*.xml --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/classes/applicationContext.xml</param-value> </context-param> <!-- Srping监听器 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- config log4j second Part --> <!-- 加载log4j配置文件 --> <listener> <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class> </listener> <servlet> <servlet-name>springMVC</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <!-- 有的项目中这里写的是.do,这样分发器只会分发带有.do的请求, 就可以规避将js.css,.png等文件的路径当作一个请求,当前没有写.do,就要用到 <mvc:annotation-driven /> <mvc:resources mapping="/css/**" location="/css/"/> 将.css等文件不当作一个请求 --> <servlet-mapping> <servlet-name>springMVC</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> </web-app>
log4j.properties
#log4j.rootLogger=INFO,C,F
#first way log All
##########
# C,System.out
#log4j.appender.C.Threshold=INFO print info or above
##########
log4j.logger.sfk.bbs=INFO,C,F
#second way set log package
log4j.appender.C=org.apache.log4j.ConsoleAppender
log4j.appender.C.Threshold=INFO
log4j.appender.C.layout=org.apache.log4j.PatternLayout
log4j.appender.C.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %L %p %C{1} - %m%n
###########
#save in file
#log4j.appender.F.Threshold=INFO ,info or above
###########
log4j.appender.F=org.apache.log4j.DailyRollingFileAppender
# save file path
log4j.appender.F.File=/home/rocky/develop/luna/eclipse/logInfo/SpringMVC_log
log4j.appender.F.Append=true
log4j.appender.F.Threshold=INFO
log4j.appender.F.layout=org.apache.log4j.PatternLayout
log4j.appender.F.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %L %p %C{1} - %m%n
项目的结构图
工具类
package sfk.bbs.common.SpringUtil; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * 1.Spring的工具类,现在主要用来获取Spring配置文件中的bean * 2.这个方法里比较遗憾的是没有用到implements ApplicationContextAware * 原因是在web.xml文件中没有配置正确 * @author rocky * */ public class SpringHelper { private static ApplicationContext applicationContext; @SuppressWarnings("static-access") public SpringHelper() { this.applicationContext =new ClassPathXmlApplicationContext("classpath:applicationContext.xml"); } /* @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { System.out.println("setApplicationContext : "+this.applicationContext); this.applicationContext = applicationContext; }*/ public Object getBean(String beanId) { System.out.println("applicationContext : "+applicationContext); System.out.println("getBean : " + beanId); return applicationContext.getBean(beanId); } }
测试类
package sfk.bbs.test.testSpringMVCConfig.action; import java.sql.Connection; import java.sql.SQLException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.sql.DataSource; import org.apache.log4j.Logger; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import com.mchange.v2.c3p0.ComboPooledDataSource; import sfk.bbs.common.SpringUtil.SpringHelper; import sfk.bbs.common.constance.ActionURL; import sfk.bbs.common.constance.PagePath; @Controller public class StudentAction { private static Logger log = Logger.getLogger(StudentAction.class); /** * 1.现在的想法是把pages文件夹写在SpringMVC的配置文件中,将后缀.jsp也写在SpringMVC的配置文件中 * 在Controller中page页面写成这样"testPage/studentList * 斜杠左边的pages文件夹下面的下一层文件夹,斜杠右边的是jsp文件 * 2.jsp文件名和requestMapping中的value相同 * 3.注意:requestMapping不写.do,页面不写.jsp * * 查找所有的student列表 * @param request request * @param response response * @param model model * @return studentList */ @RequestMapping(value=ActionURL.STUDENT_LIST) public String findAllStudent(HttpServletRequest request, HttpServletResponse response,Model model) { SpringHelper springHelper = new SpringHelper(); DataSource datasource = (ComboPooledDataSource) springHelper.getBean("dataSourceLocal"); Connection conn = null; try { conn = datasource.getConnection(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { conn.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } System.out.println(conn); //ctx = new ("classpath:applicationContext.xml"); // ApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:applicationContext.xml"); //System.out.println("ctx : " + ctx); log.info("into findAllStudent"); return PagePath.STUDENT_LIST; } }
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/15387.html