首先在整合这个框架的时候,想想其一般的步骤是怎样的,先有个步骤之后,不至于在后面的搞混了,这样在整合的时候也比较清晰些。
然后我们就细细的一步一步来整合。
1 创建一个Web项目。
2 导入Mybatis3、Spring4、SpringMVC4、连接数据库(我使用的数据库是mysql)的jar包。
我所用的包:
spring-websocket-4.2.0.RELEASE.jar
3 创建Mybatis3、Spring4、SpringMVC4、连接数据库的配置文件。
4 配置web.xml
<?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"> <!-- 告知javaEE容器,有哪些内容需要添加到上下文中去 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value> /WEB-INF/classes/applicationContext.xml, <!-- /WEB-INF/classes/mvc-servlet.xml --> </param-value> </context-param> <!-- 加载LOG4J --> <context-param> <param-name>log4jConfigLocation</param-name> <param-value>/WEB-INF/log4j.xml</param-value> </context-param> <context-param> <param-name>log4jRefreshInterval</param-name> <param-value>60000</param-value> </context-param> <!-- 动态设置项目的运行路径 --> <context-param> <param-name>webAppRootKey</param-name> <param-value>ssm.root</param-value> </context-param> <!-- 配置静态资源 --> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>/static/*</url-pattern> </servlet-mapping> <!-- 配置springmvc的前端控制器 --> <servlet> <servlet-name>mvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 默认情况下:DispatcherServlet会寻找WEB-INF下,命名规范为[servlet-name]-servlet.xml文件。如:在上例中,它就会找/WEB-INF/spring-servlet.xml 如果需要修改,需要在web.xml中的<servlet>标记中增加 <init-param>。。。 </init-param>:--> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/classes/mvc-servlet.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>mvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!-- spring框架提供的字符集过滤器 --> <!-- spring Web MVC框架提供了org.springframework.web.filter.CharacterEncodingFilter用于解决POST方式造成的中文乱码问题 --> <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> <!-- force强制,促使 --> <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> <!-- 登录过滤器--> <filter> <filter-name>loginFilter</filter-name> <filter-class>com.cy.ssm.filter.LoginFilter</filter-class> </filter> <filter-mapping> <filter-name>loginFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- 监听器 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <listener> <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class> </listener> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
5 datasource.properties 连接数据库
jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=UTF-8 jdbc.username=root jdbc.password=root
6 mybatis.cfg.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> </configuration>
7 mvc-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" xsi:schemaLocation="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 http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> <!-- 启动注解,注册服务,如验证框架、全局类型转换器--> <mvc:annotation-driven/> <!-- 启动自动扫描 --> <context:component-scan base-package="com.cy.ssm"> <!-- 制定扫包规则 ,[email protected] --> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> <!-- 配置视图解析器 --> <!-- prefix和suffix:查找视图页面的前缀和后缀(前缀[逻辑视图名]后缀), 比如传进来的逻辑视图名为WEB-INF/jsp/hello,则该该jsp视图页面应该存放在“WEB-INF/jsp/hello.jsp”; --> <bean class="org.springframework.web.servlet.view.UrlBasedViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property> <property name="prefix" value="/"></property> <!-- 我这里的视图直接放在WebRoot下的 --> <property name="suffix" value=".jsp"></property> </bean> </beans>
8 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: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-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd"> <!-- 开启自动扫包 --> <context:component-scan base-package="com.cy.ssm"> <!--制定扫包规则,[email protected],其他的还是要扫描 --> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> <!-- 启动AOP支持 --> <aop:aspectj-autoproxy/> <!-- 引入外部数据源配置信息 --> <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <value>classpath:datasource.properties</value> </property> </bean> <!-- 配置数据源 --> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="${jdbc.driver}"></property> <property name="url" value="${jdbc.url}"></property> <property name="username" value="${jdbc.username}"></property> <property name="password" value="${jdbc.password}"></property> </bean> <!-- 配置Session工厂 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property> <!-- 加载mybatis.cfg.xml文件 --> <property name="configLocation" value="classpath:mybatis.cfg.xml"></property> <!-- 自动扫描需要定义类别名的包,将包内的JAVA类的类名作为类别名 --> <property name="typeAliasesPackage" value="com.cy.ssm.beans"></property> </bean> <!-- 自动扫描所有的Mapper接口与文件 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.cy.ssm.mapper"></property> </bean> <!-- 配置事务管理器 --> <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean> <!-- 定义个通知,指定事务管理器 --> <tx:advice id="txAdvice" transaction-manager="txManager"> <tx:attributes> <tx:method name="delete*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.Exception" /> <tx:method name="save*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.Exception" /> <tx:method name="insert*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.Exception" /> <tx:method name="update*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.Exception" /> <tx:method name="load*" propagation="SUPPORTS" read-only="true"/> <tx:method name="find*" propagation="SUPPORTS" read-only="true"/> <tx:method name="search*" propagation="SUPPORTS" read-only="true"/> <tx:method name="select*" propagation="SUPPORTS" read-only="true"/> <tx:method name="get*" propagation="SUPPORTS" read-only="true"/> </tx:attributes> </tx:advice> <aop:config> <!-- 配置一个切入点 --> <aop:pointcut id="serviceMethods" expression="execution(* com.cy.ssm.service.impl.*ServiceImpl.*(..))" /> <aop:advisor advice-ref="txAdvice" pointcut-ref="serviceMethods" /> </aop:config> </beans>
9 配置文件都差不多配置好了,接下来就写个测试的。
UserBean.java
package com.cy.ssm.beans; import java.io.Serializable; public class UserBean implements Serializable { private static final long serialVersionUID = -2682305557890221059L; private Integer id; private String username; private String password; private Double account; public UserBean() { super(); // TODO Auto-generated constructor stub } public UserBean(Integer id, String username, String password, Double account) { super(); this.id = id; this.username = username; this.password = password; this.account = account; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Double getAccount() { return account; } public void setAccount(Double account) { this.account = account; } @Override public String toString() { return "UserBean [account=" + account + ", id=" + id + ", password=" + password + ", username=" + username + "]"; } }
UserMapper.java
package com.cy.ssm.mapper; import java.util.List; import java.util.Map; import org.apache.ibatis.annotations.Delete; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Options; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Result; import org.apache.ibatis.annotations.ResultMap; import org.apache.ibatis.annotations.Results; import org.apache.ibatis.annotations.Select; import org.apache.ibatis.annotations.Update; import com.cy.ssm.beans.UserBean; public interface UserMapper { /** * 登录 * @param userName * @param password * @return * @throws Exception */ @Select("select * from t_user where username=#{un} and password=#{pw}") @Results({ @Result(id=true,property="id",column="id",javaType=Integer.class), @Result(property="username",column="username",javaType=String.class), @Result(property="password",column="password",javaType=String.class), @Result(property="account",column="account",javaType=Double.class) }) public UserBean login(@Param("un")String username,@Param("pw")String password); /** * 新增用戶 * @param user * @return * @throws Exception */ @Insert("insert into t_user value (null,user.username,user.password,user.account)") @Options(useGeneratedKeys=true,keyProperty="user.id") public int insertUser(@Param("user")UserBean user) throws Exception; /** * 修改用戶 * @param user * @param id * @return * @throws Exception */ @Update(" update t_user set username=#{u.username},password=#{u.password},account=#{u.account} where id=#{id}") public int updateUser (@Param("u")UserBean user,@Param("id")int id) throws Exception; /** * 刪除用戶 * @param id * @return * @throws Exception */ @Delete(" delete from t_user where id=#{id} ") public int deleteUser(int id) throws Exception; /** * 根据id查询用户信息 * @param id * @return * @throws Exception */ @Select(" select * from t_user where id=#{id}") @Results({ @Result(id=true,property="id",column="id",javaType=Integer.class), @Result(property="username",column="username",javaType=String.class), @Result(property="password",column="password",javaType=String.class), @Result(property="account",column="account",javaType=Double.class) }) public UserBean selectUserById(int id) throws Exception; /** * 查询所有的用户信息 * @return * @throws Exception */ @Select(" select * from t_user") @ResultMap("userMap") public List<UserBean> selectAllUser() throws Exception; /** * 批量增加 * @param user * @return * @throws Exception */ public int batchInsertUser(@Param("users")List<UserBean> user) throws Exception; /** * 批量删除 * @param list * @return * @throws Exception */ public int batchDeleteUser(@Param("list")List<Integer> list) throws Exception; /** * 分页查询数据 * @param parma * @return * @throws Exception */ public List<UserBean> pagerUser(Map<String, Object> parmas) throws Exception; /** * * 分页统计数据 * @param parma * @return * @throws Exception */ public int countUser(Map<String, Object> parmas) throws Exception; }
UserMapper.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org/DTD Mapper 3.0" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.cy.ssm.mapper.UserMapper"> <!-- 自定义返回结果集 --> <resultMap id="userMap" type="UserBean"> <id property="id" column="id" javaType="java.lang.Integer"></id> <result property="username" column="username" javaType="java.lang.String"></result> <result property="password" column="password" javaType="java.lang.String"></result> <result property="account" column="account" javaType="java.lang.Double"></result> </resultMap> <!-- 批量操作和foreach标签 --> <insert id="batchInsertUser" parameterType="java.util.List"> insert into t_user values <foreach collection="users" item="users" separator=","> (null,#{users.username},#{users.password},#{users.account}) </foreach> </insert> <delete id="batchDeleteUser"> delete from t_user where id in ( <foreach collection="list" item="list" separator=","> #{id} </foreach> ) </delete> <!--collection 为用于遍历的元素(必选),支持数组、List、Set --> <!-- item 表示集合中每一个元素进行迭代时的别名. --> <!--separator表示在每次进行迭代之间以什么符号作为分隔 符. --> <!--#在生成SQL时,对于字符类型参数,会拼装引号 $在生成SQL时,不会拼装引号,可用于order by之类的参数拼装 --> <select id="pagerUser" parameterType="java.util.Map" resultMap="userMap"> select * from t_user where 1=1 <if test="username!=null"> and username like '%${username}%' </if> limit ${index},${pageSize} </select> <select id="countUser" parameterType="java.util.Map" resultType="int"> select count(*) from t_user where 1=1 <if test="username != null"> and username like '%${username}%' </if> </select> </mapper>
ILoginService.java
package com.cy.ssm.service; import com.cy.ssm.beans.UserBean; public interface ILoginService { public UserBean Login(String username,String password); }
LoginServiceImpl.java
package com.cy.ssm.service.impl; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.cy.ssm.mapper.UserMapper; import com.cy.ssm.beans.UserBean; import com.cy.ssm.service.ILoginService; @Service public class LoginServiceImpl implements ILoginService{ @Resource private UserMapper um; @Override public UserBean Login(String username, String password) { return um.login(username, password); } }
LoginController .java
package com.cy.ssm.controller; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import org.apache.log4j.Logger; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import com.cy.ssm.beans.UserBean; import com.cy.ssm.service.ILoginService; @Controller public class LoginController { private Logger log = Logger.getLogger(this.getClass()); @Resource private ILoginService loginServiceImpl; @RequestMapping("/login") public ModelAndView login(HttpServletRequest req,UserBean user){ log.info(user); ModelAndView mv = new ModelAndView(); UserBean u=loginServiceImpl.Login(user.getUsername(), user.getPassword()); if(u != null){ req.getSession().setAttribute("user", u); mv.addObject("password", u.getPassword()); System.out.println(u.getPassword()); } mv.setViewName("index"); return mv; } }
jsp页面;
login.jsp
<body> <form action="<%=basePath%>login" method="post"> <input type="text" name="username"/> <input type="text" name="password"/> <input type="submit" value="提交"/> </form> index.jsp <body> ${password } </body>
测试:
点击提交
整体大概就这样了!
我把整个文件上传到:http://pan.baidu.com/s/1hrB1guo
继续我的作业了!
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/14101.html