文章目录
1、加入Spring、Spring MVC、数据库驱动等相关jar文件
2、配置文件
3、改造DAO层
4、改造Service层
5、Entity层(User实体类)
6、改造Controller层
7、改造View层
8、结果演示
1、加入Spring、Spring MVC、数据库驱动等相关jar文件
2、配置文件
因为正在学习阶段,所以将配置文件的所有代码都放出来,供正在入门的朋友一起交流学习,配置文件中大部分需要注意的地方,都进行了注释。
Spring配置文件——applicationContext-jdbc.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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" 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/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!--引入properties文件--> <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location"> <value>classpath:database.properties</value> </property> </bean> <!--配置DataSource--> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="${driver}"/> <property name="url" value="${url}"/> <property name="username" value="${user}"/> <property name="password" value="${pwd}"/> </bean> <!--配置扫描注解定义的业务Bean--> <context:component-scan base-package="cn.kgc.service,cn.kgc.dao"/> </beans>
Spring MVC配置文件——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:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p" 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"> <!--支持注解式处理器--> <mvc:annotation-driven/> <!--对包进行扫描,实现注解驱动Bean的定义--> <context:component-scan base-package="cn.kgc.servlet"/> <!--视图解析器--> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- 前缀 --> <property name="prefix" value="/jsp/"/> <!-- 后缀 --> <property name="suffix" value=".jsp"/> </bean> </beans>
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0"> <!--配置环境参数,指定Spring配置文件所在的目录--> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:ApplicationContext-jdbc.xml</param-value> </context-param> <!--配置Spring的ContextLoaderListener监听器,初始化Spring--> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener> <!--配置Spring MVC的核心控制器DispatcherServlet--> <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:springmvc-servlet.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
database.properties
driver=com.mysql.jdbc.Driver #在和mysql传递数据的过程中,使用unicode编码格式,并且字符集设置为utf-8 url=jdbc:mysql://127.0.0.1:3306/smbms?useUnicode=true&characterEncoding=utf-8 user=root pwd=root
log4j.properties
log4j.rootLogger = debug,stdout,D log4j.appender.stdout = org.apache.log4j.ConsoleAppender log4j.appender.stdout.Target = System.out log4j.appender.stdout.layout = org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern = [%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n log4j.appender.D = org.apache.log4j.DailyRollingFileAppender log4j.appender.D.File = D://logs/log.log log4j.appender.D.Append = true log4j.appender.D.Threshold = DEBUG log4j.appender.D.layout = org.apache.log4j.PatternLayout log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n log4j.appender.E = org.apache.log4j.DailyRollingFileAppender log4j.appender.E.File =D://logs/error.log log4j.appender.E.Append = true log4j.appender.E.Threshold = ERROR log4j.appender.E.layout = org.apache.log4j.PatternLayout log4j.appender.E.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
3、改造DAO层
1、BaseDao类
package cn.kgc.dao; import java.io.IOException; import java.io.InputStream; import java.sql.*; import java.util.Properties; /** * 操作数据库的基类--静态类 * @author Administrator * */ public class BaseDao { static{//静态代码块,在类加载的时候执行 init(); } private static String driver; private static String url; private static String user; private static String password; //初始化连接参数,从配置文件里获得 public static void init(){ Properties params=new Properties(); String configFile = "database.properties"; InputStream is=BaseDao.class.getClassLoader().getResourceAsStream(configFile); try { params.load(is); } catch (IOException e) { e.printStackTrace(); } driver=params.getProperty("driver"); url=params.getProperty("url"); user=params.getProperty("user"); password=params.getProperty("pwd"); } /** * 获取数据库连接 * @return */ public static Connection getConnection(){ Connection connection = null; try { Class.forName(driver); connection = DriverManager.getConnection(url, user, password); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return connection; } /** * 查询操作 * @param connection * @param pstm * @param rs * @param sql * @param params * @return */ public static ResultSet execute(Connection connection,PreparedStatement pstm,ResultSet rs, String sql,Object[] params) throws Exception{ pstm = connection.prepareStatement(sql); for(int i = 0; i < params.length; i++){ pstm.setObject(i+1, params[i]); } rs = pstm.executeQuery(); return rs; } /** * 更新操作 * @param connection * @param pstm * @param sql * @param params * @return * @throws Exception */ public static int execute(Connection connection,PreparedStatement pstm, String sql,Object[] params) throws Exception{ int updateRows = 0; pstm = connection.prepareStatement(sql); for(int i = 0; i < params.length; i++){ pstm.setObject(i+1, params[i]); } updateRows = pstm.executeUpdate(); return updateRows; } /** * 释放资源 * @param connection * @param pstm * @param rs * @return */ public static boolean closeResource(Connection connection,PreparedStatement pstm,ResultSet rs){ boolean flag = true; if(rs != null){ try { rs.close(); rs = null;//GC回收 } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); flag = false; } } if(pstm != null){ try { pstm.close(); pstm = null;//GC回收 } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); flag = false; } } if(connection != null){ try { connection.close(); connection = null;//GC回收 } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); flag = false; } } return flag; } }
2、UserDao接口
package cn.kgc.dao; import cn.kgc.entity.User; public interface UserDao { User login(String name,String pwd); }
3、UserDaoImpl类
package cn.kgc.dao; import cn.kgc.entity.User; import org.springframework.stereotype.Repository; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; /** * @author:BeiisBei * @date:2019/11/8 * @aim: */ @Repository("userDao") public class UserDaoImpl extends BaseDao implements UserDao { @Override public User login(String name, String pwd) { Connection conn=this.getConnection(); String sql="select * from smbms_user where userCode=? and userPassword=? "; User user=new User(); PreparedStatement pstm=null; ResultSet set=null; if(null!=conn){ try { Object[] obj={name,pwd}; set=this.execute(conn,pstm,set,sql,obj); if(set!=null && set.next()){ user.setName(set.getString("userCode")); user.setPwd(set.getString("userPassword")); } } catch (SQLException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { this.closeResource(conn,pstm,set); } } return user; //注意,此次调试过程中出现空指针异常的问题,是由于自己这里return null导致的,要细心。 } }
4、改造Service层
1、UserService接口
package cn.kgc.service; import cn.kgc.entity.User; public interface UserService { User login(String name, String pwd); }
2、UserServiceImpl 实现类
package cn.kgc.service; import cn.kgc.dao.UserDao; import cn.kgc.entity.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; /** * @author:BeiisBei * @date:2019/11/8 * @aim: */ @Service("userService") public class UserServiceImpl implements UserService { @Autowired @Qualifier("userDao") private UserDao userDao; @Override public User login(String name, String pwd) { return userDao.login(name,pwd); } }