资料看的再多,不如自己手动操作一遍。
这里我吧框架搭建的步骤罗列出来,只要跟着步骤走,就能实现一个web框架的搭建。
本篇的任务:基本框架的搭建,并实现注册登录功能。
准备工作:
1、开发环境的准备
详细步骤不写出来了,非常简单,我把我的开发环境列出来。
2、jar包准备
这里我把spring的jar包全部导入到项目中,因为我的另一个工程比较大,所以全部导入了进去(也可以只导入必须的jar包)。
搭建步骤:
1、首先给大家看一下我的工程目录。
2、web.xml
都有注释,就不用细说了。
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>myweb</display-name> <!-- 加载Spring容器配置 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 设置Spring容器加载所有的配置文件的路径 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext*.xml</param-value> </context-param> <!-- 配置SpringMVC核心控制器 --> <servlet> <servlet-name>springMVC</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 配置初始配置化文件,前面contextConfigLocation看情况二选一 --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-mvc.xml</param-value> </init-param> <!-- 启动加载一次 --> <load-on-startup>1</load-on-startup> </servlet> <!--为DispatcherServlet建立映射 --> <servlet-mapping> <servlet-name>springMVC</servlet-name> <!-- 此处可以可以配置成*.do,对应struts的后缀习惯 --> <url-pattern>/</url-pattern> </servlet-mapping> <!-- 解决工程编码过滤器 --> <filter> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <welcome-file-list> <welcome-file>/pages/system/login/login.jsp</welcome-file> </welcome-file-list> </web-app>PS: 这里要提醒一下,文件头版本号那里本来是3.0版本,但是tomcat7不支持,启动会报错,所以我给改成了2.5版本。
2、spring-mvc.xml
spring相关的配置文件
<?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:jdbc="http://www.springframework.org/schema.jdbc" 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.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> <!-- 注解扫描包 --> <context:component-scan base-package="com.leq" /> <!-- 开启注解 --> <mvc:annotation-driven /> <!-- 注解的处理器适配器 --> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/> <!-- 注解的处理器映射器 --> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/> <!-- 配置静态资源,直接映射到对应的文件夹,不被DispatcherServlet处理 --> <mvc:resources mapping="/img/**" location="/img/" /> <mvc:resources mapping="/js/**" location="/js/" /> <mvc:resources mapping="/css/**" location="/css/" /> <mvc:resources mapping="/html/**" location="/html/" /> <mvc:resources mapping="/pages/**" location="/pages/" /> <mvc:resources mapping="/resource/**" location="/resource/" /> <!-- 定义跳转的文件的前后缀 ,视图模式配置--> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- 这里配的是接收后台响应的jsp页面地址,如果controller中返回的是【pages/system/login】,则返回到的页面是【/pages/system/login.jsp】 --> <property name="prefix" value="/" /> <property name="suffix" value=".jsp" /> </bean> <!-- 配置自定义拦截器 --> <mvc:interceptors> <mvc:interceptor> <!-- 需要拦截的请求,这里配的是所有请求都会拦截 --> <mvc:mapping path="/**"/> <!-- 不被拦截的请求 --> <mvc:exclude-mapping path="/leq/**"/> <mvc:exclude-mapping path="/pages/system/**"/> <!-- 自定义拦截器类 --> <bean class="com.leq.common.util.CommonInterceptor"></bean> </mvc:interceptor> </mvc:interceptors> </beans>
3、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:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jee="http://www.springframework.org/schema/jee" 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.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <!-- 配置数据源 --> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="oracle.jdbc.OracleDriver" /> <property name="url" value="jdbc:oracle:thin:@127.0.0.1:1521:orcl" /> <property name="username" value="first" /> <property name="password" value="1111" /> </bean> <!-- 2. mybatis的SqlSession的工厂: SqlSessionFactoryBean dataSource:引用数据源 MyBatis定义数据源,同意加载配置 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property> <property name="configLocation" value="classpath:mybatis-config.xml" /> </bean> <!-- 配置mapper扫描器 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!-- 扫描包路径,如果需要扫描多个包中间用半角逗号隔开 --> <property name="basePackage" value="com.leq.*.*.dao"></property> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /> </bean> <!-- 事务控制 对MyBatis操作数据库 spring使用JDBC事务控制类 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <!-- 配置数据源 --> <property name="dataSource" ref="dataSource" /> </bean> <!-- 通知 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <!-- 传播行为 --> <tx:method name="save*" propagation="REQUIRED" /> <tx:method name="insert*" propagation="REQUIRED" /> <tx:method name="update*" propagation="REQUIRED" /> <tx:method name="delete*" propagation="REQUIRED" /> <tx:method name="get*" propagation="SUPPORTS" read-only="true" /> <tx:method name="select*" propagation="SUPPORTS" read-only="true" /> </tx:attributes> </tx:advice> <!-- 配置aop --> <aop:config> <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.leq.*.*.service.impl.*.*(..))" /> </aop:config> </beans>
PS:这里说一下,其实applicationContext.xml和spring-mvc.xml这两个配置文件可以合并在一起。由于个人习惯,我将他们分开了。
4、mybatis-config.xml
mybatis相关的配置文件,主要加载mapper.xml文件
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <!-- 实体类,简称 -设置别名 --> <typeAliases> <typeAlias alias="userInfo" type="com.leq.system.login.bean.UserInfoBean" /> </typeAliases> <!-- 实体接口映射资源 ,加载mapper.xml配置文件--> <mappers> <mapper resource="com/leq/mapper/system/UserInfoMapper.xml" /> </mappers> </configuration>
5、log4j.properties
### set log levels ### log4j.rootLogger = DEBUG , Console , D #Console控制台相关 log4j.appender.Console=org.apache.log4j.ConsoleAppender log4j.appender.Console.layout=org.apache.log4j.PatternLayout log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n log4j.logger.org.apache=DEBUG #sql相关 log4j.logger.java.sql.ResultSet=INFO log4j.logger.java.sql.Connection=DEBUG log4j.logger.java.sql.Statement=DEBUG log4j.logger.java.sql.PreparedStatement=DEBUG #log file日志文件相关 log4j.appender.D = org.apache.log4j.DailyRollingFileAppender log4j.appender.D.File = D:/logs/log.log log4j.appender.D.Append = true log4j.appender.D.Threshold = INFO 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
PS:细心的朋友可能会注意到,我的xml配置文件里面并没有加载log4j.properties,为什么还要写?而且在项目启动后,log4j.properties文件确实被加载了且起作用了。我一开始也纠结,后来查看源码的时候发现了这样一段代码,于是便猜到了src目录下会自动加载log4j.properties文件。
6、UserInfoMapper.xml
这里就是mybatis操作数据库的部分了
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.leq.system.login.dao.UserInfoDao"> <resultMap type="com.leq.system.login.bean.UserInfoBean" id="BaseResultType"> <id column="LOGIN_ID" property="loginId" jdbcType="VARCHAR"/> <result column="USER_NAME" property="userName" jdbcType="VARCHAR"/> <result column="PASSWD" property="passwd" jdbcType="VARCHAR"/> <result column="MOBILE" property="mobile" jdbcType="VARCHAR"/> <result column="MAIL" property="mail" jdbcType="VARCHAR"/> <result column="CREATED_BY" property="createdBy" jdbcType="VARCHAR"/> <result column="CREATED_DATE" property="createdDate" jdbcType="TIMESTAMP"/> <result column="UPDATED_BY" property="updatedBy" jdbcType="VARCHAR"/> <result column="UPDATED_DATE" property="updatedDate" jdbcType="TIMESTAMP"/> </resultMap> <insert id="toRegister"> INSERT INTO USER_INFO( LOGIN_ID, USER_NAME, PASSWD, MOBILE, MAIL) VALUES ( #{loginId,jdbcType=VARCHAR}, #{userName,jdbcType=VARCHAR}, #{passwd,jdbcType=VARCHAR}, #{mobile,jdbcType=VARCHAR}, #{mail,jdbcType=VARCHAR} ) </insert> <select id="getUserPasswd" parameterType="java.lang.String" resultType="java.lang.String"> SELECT PASSWD FROM USER_INFO WHERE LOGIN_ID = #{loginId,jdbcType=VARCHAR} </select> </mapper>
好了,配置文件已经弄好了,剩下的就是jsp和java部分了。
因为jsp和java部分都很简单,所以我就不把代码全部展示出来了。
login.jsp
就一个form表单
LoginController.java
package com.leq.system.login.controller; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import com.leq.common.util.BaseController; import com.leq.common.util.BaseResponse; import com.leq.system.login.bean.UserInfoBean; import com.leq.system.login.service.UserInfoService; @Controller @RequestMapping(value="/leq") public class LoginController extends BaseController{ @Autowired private UserInfoService userInfoService; @RequestMapping(value="/home",method=RequestMethod.POST) public ModelAndView toLogin(HttpServletRequest request,HttpServletResponse response){ String loginId = (String)request.getParameter("loginId"); String passwd = (String)request.getParameter("passwd"); if(StringUtils.isEmpty(loginId) || StringUtils.isEmpty(passwd)){ return new ModelAndView("pages/system/login/login",null); } String dbPasswd = userInfoService.getUserPasswd(loginId); Map<String,String> map = new HashMap<String,String>(); if(dbPasswd == null || !dbPasswd.equals(passwd)){ map.put("CODE", "999999"); return new ModelAndView("pages/system/login/login",map); } request.getSession().setAttribute("user", loginId); return new ModelAndView("pages/common/menu",null); } }
UserInfoServiceImpl.java
package com.leq.system.login.service.impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.leq.system.login.bean.UserInfoBean; import com.leq.system.login.dao.UserInfoDao; import com.leq.system.login.service.UserInfoService; @Service public class UserInfoServiceImpl implements UserInfoService{ @Autowired private UserInfoDao userInfoDao; @Override public String getUserPasswd(String loginId) { return userInfoDao.getUserPasswd(loginId); } }
UserInfoDao.java
package com.leq.system.login.dao; import org.springframework.stereotype.Repository; import com.leq.system.login.bean.UserInfoBean; @Repository public interface UserInfoDao { String getUserPasswd(String loginId); }
好了,现在可以将项目添加到tomcat,然后启动。
恭喜你,项目成功启动!!!
虽然篇幅挺多,但是实际内容不多,小伙伴多看几遍,就都能看懂了。
另外如果小伙伴疑惑,可以给我留言,我会努力帮忙解决,一起学习一起进步!!!