第一次尝试自己搭建框架, 算是比较小有收获, 今天把步骤整理以便日后复习。
1. 先创建一个web项目,加入所需要的jar包, 该实例用到如下jar包:
还需要“mysql-connector-java-5.1.18-SNAPSHOT-bin.jar” jdbc的驱动包。
2. 首先Springmvc搭建的部分
在web.xml里配置过滤器和servlet, 代码如下:
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <!-- Reads request input using UTF-8 encoding --> <filter> <filter-name>characterEncodingFilter</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>characterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
<servlet> <servlet-name>Spring MVC Dispatcher Servlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value> /WEB-INF/spring/appServlet/servlet-context.xml </param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>Spring MVC Dispatcher Servlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
在配置servlet时候,定义了servlet的配置文件路径 /WEB-INF/spring/appServlet/servlet-context.xml, 具体配置如下:
<!-- Configures the @Controller programming model --> <mvc:annotation-driven /> <!-- Forwards requests to the "/" resource to the "welcome" view --> <mvc:view-controller path="/" view-name="welcome"/> <!-- Configures Handler Interceptors --> <mvc:interceptors> <!-- Changes the locale when a 'locale' request parameter is sent; e.g. /?locale=de --> <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" /> </mvc:interceptors>
<!--Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources/ directory--> <mvc:resources mapping="/resources/**" location="/resources/" /> <!-- Saves a locale change using a cookie --> <bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver" /> <!-- Application Message Bundle --> <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource"> <property name="basename" value="/WEB-INF/messages/messages" /> <property name="cacheSeconds" value="0" /> </bean> <!-- Resolves view names to protected .jsp resources within the /WEB-INF/views directory --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/views/"/> <property name="suffix" value=".jsp"/> </bean>
<!-- enable component scanning (beware that this does not enable mapper scanning!) -->
<context:component-scan base-package="org.springframework.basic.service" />
<context:component-scan base-package="org.springframework.basic.action"></context:component-scan>
<!-- enable autowire -->
<context:annotation-config />
3. 创建一个java action类
注意: 需要在servlet配置文件中定义action 扫描“<context:component-scan base-package="org.springframework.basic.action"></context:component-scan>” 不然, 启动服务后, web项目跑不到对应的action中。 而且需要在Action上标注@Controller, 不然就会报404的错误。
package org.springframework.basic.action; import javax.annotation.Resource; import org.springframework.basic.entity.User; import org.springframework.basic.service.UserService; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; @Controller @RequestMapping(value="/login") public class LoginController { @Resource private UserService userService; @RequestMapping(method=RequestMethod.POST) public String login(@RequestParam String id, @RequestParam String pass) { User user = new User(); user.setUserName(id); user.setUserPass(pass); String result = userService.checkUser(user); return result; } }
4. 配置ibatis, 在servlet的配置文件中加入:
<!-- data base set configure --> <context:property-placeholder location="classpath:mysql.properties" /> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="${jdbc.driverClassName}" /> <property name="url" value="${jdbc.url}" /> </bean> <!-- transaction manager, use JtaTransactionManager for global tx --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean>
<!-- enable transaction demarcation with annotations --> <tx:annotation-driven /> <!-- define the SqlSessionFactory --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="typeAliasesPackage" value="org.springframework.basic.entity" /> </bean> <!-- scan for mappers and let them be autowired --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="org.springframework.basic.persistence" /> </bean>
然后在src包下新建mysql.properties文件:
jdbc.driverClassName=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/c_chowhound?user=root&password=123456&useUnicode=true&characterEncoding=UTF-8 #jdbc.url=jdbc:mysql://sqld.duapp.com:4050/dbname?user=ak&password=sk&useUnicode=true&characterEncoding=UTF-8
完整的servlet的配置文件:
<?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:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation=" http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <!-- Configures the @Controller programming model --> <mvc:annotation-driven /> <!-- Forwards requests to the "/" resource to the "welcome" view --> <mvc:view-controller path="/" view-name="welcome"/> <!-- Configures Handler Interceptors --> <mvc:interceptors> <!-- Changes the locale when a 'locale' request parameter is sent; e.g. /?locale=de --> <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" /> </mvc:interceptors> <!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources/ directory --> <mvc:resources mapping="/resources/**" location="/resources/" /> <!-- Saves a locale change using a cookie --> <bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver" /> <!-- Application Message Bundle --> <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource"> <property name="basename" value="/WEB-INF/messages/messages" /> <property name="cacheSeconds" value="0" /> </bean> <!-- Resolves view names to protected .jsp resources within the /WEB-INF/views directory --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/views/"/> <property name="suffix" value=".jsp"/> </bean> <!-- data base set configure --> <context:property-placeholder location="classpath:mysql.properties" /> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="${jdbc.driverClassName}" /> <property name="url" value="${jdbc.url}" /> </bean> <!-- transaction manager, use JtaTransactionManager for global tx --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <!-- enable component scanning (beware that this does not enable mapper scanning!) --> <context:component-scan base-package="org.springframework.basic.service" /> <context:component-scan base-package="org.springframework.basic.action"></context:component-scan> <!-- enable autowire --> <context:annotation-config /> <!-- enable transaction demarcation with annotations --> <tx:annotation-driven /> <!-- define the SqlSessionFactory --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="typeAliasesPackage" value="org.springframework.basic.entity" /> </bean> <!-- scan for mappers and let them be autowired --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="org.springframework.basic.persistence" /> </bean> <!--根据dataSource和configLocation创建一个SqlMapClient--> <!--<bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean"> <property name="configLocation"> <value>/WEB-INF/SqlMapConfig.xml</value> </property> <property name="dataSource"> <ref bean="dataSource" /> </property> </bean> <bean id="sqlMapClientTemplate" class="org.springframework.orm.ibatis.SqlMapClientTemplate"> <property name="sqlMapClient"> <ref bean="sqlMapClient" /> </property> </bean> --> </beans>
5. service 类:
package org.springframework.basic.service; import org.springframework.basic.entity.User; import org.springframework.basic.persistence.UserMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * @author ychen * */ @Service public class UserService { @Autowired private UserMapper userDao; public String checkUser(User user) { User entity = userDao.getUser(user); return entity != null ? (entity.getAuthority() .equalsIgnoreCase("admin") ? "admin" : "part") : "false"; } }
6. Map 类:
package org.springframework.basic.persistence; import org.springframework.basic.entity.User; /** * @author ychen * */ public interface UserMapper { public User getUser(User user); }
同时配置对应的Map.xml
<?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="org.springframework.basic.persistence.UserMapper"> <cache /> <select id="getUser" parameterType="User" resultType="User"> select * from user where userName=#{userName} </select> </mapper>
7. entity 类:
package org.springframework.basic.entity; import java.io.Serializable; /** * @author ychen * */ public class User implements Serializable{ private static final long serialVersionUID = 1842675592435756862L; private String userName; private String userPass; private String userId; private String authority; /** * @return the userName */ public String getUserName() { return userName; } /** * @param userName the userName to set */ public void setUserName(String userName) { this.userName = userName; } /** * @return the userPass */ public String getUserPass() { return userPass; } /** * @param userPass the userPass to set */ public void setUserPass(String userPass) { this.userPass = userPass; } /** * @return the userId */ public String getUserId() { return userId; } /** * @param userId the userId to set */ public void setUserId(String userId) { this.userId = userId; } /** * @return the authority */ public String getAuthority() { return authority; } /** * @param authority the authority to set */ public void setAuthority(String authority) { this.authority = authority; } }
对应的类包图:
8. 页面文件:
<div class="container"> <div id=firstDiv> </div> <div id="inputTable"> <form method="post" action="login"> <table id="loginArea"> <tbody> <tr> <th>帐号</th> <td><input type="text" name="id"/></td> </tr> <tr> <th>密码</th> <td><input type="password" name="pass"/></td> </tr> <tr> <th></th> <td><input type="submit" value="登录"/></td> </tr> </tbody> </table> </form> </div> </div>
9. 新建服务, 注意最好使用Module的web Module, 这里的Path就是web项目名字。 URL里和这里的path还有servlet中的<servlet-mapping>里的“<url-pattern>/</url-pattern>” 有关系。
这样一个粗略的springmvc+ibatis框架就搭好啦。