一、创建Web项目
最终整个工程目录如下:
需要导入的包
二、创建库表映射类并配置MyBatis
1、首先在数据库中创建一张表 t_user
use test;
DROP TABLE IF EXISTS t_user;
create table t_user
(
userId int primary key auto_increment,
userName VARCHAR(50) not null,
userAge int not null
);
然后插入4条数据:
insert into t_user values(1,'小王',10);
insert into t_user values(2,'红红',11);
insert into t_user values(3,'明明',12);
insert into t_user values(4,'天天',13);
查看下结果:
2、表创建好之后便创建其映射类User,位于包com.mucfc.model中
package com.mucfc.model;
/**
* User映射类
* @author linbingwen
* @time 2015.5.15
*/
public class User {
private Integer userId;
private String userName;
private int userAge;
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public int getUserAge() {
return userAge;
}
public void setUserAge(int userAge) {
this.userAge = userAge;
}
@Override
public String toString() {
return "User [userId=" + userId + ", userName=" + userName
+ ", userAge=" + userAge + "]";
}
}
2、映射类创建好之后便创建MyBatis映射文件(即Mapper文件),位于和src同级的conf的mapper包中,文件内容如下:
<?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.mucfc.mapper.UserMapper">
<!-- 查询单条记录 -->
<select id="selectUserById" parameterType="int" resultType="User">
select * from t_user where userId = #{userId}
</select>
</mapper>
3、创建映射UserMapper类如下,位于包com.mucfc.mapper中
package com.mucfc.mapper;
import com.mucfc.model.User;
/**
* Mapper映射类
* @author linbingwen
* @time 2015.5.15
*/
public interface UserMapper {
public User selectUserById(int userId);
}
4、创建操作数据的DAO层
package com.mucfc.dao;
import com.mucfc.model.User;
/**
* DAO接口层
* @author linbingwen
* @time 2015.5.15
*/
public interface UserDao {
/**
* 根据用户ID查询用户信息
* @param id
* @return
*/
public User findUserById(int id);
}
然后是对应的实现层
package com.mucfc.dao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.mucfc.mapper.UserMapper;
import com.mucfc.model.User;
/**
* DAO实现层
* @author linbingwen
* @time 2015.5.15
*/
@Component
public class UserDaoImpl implements UserDao{
@Autowired
private UserMapper userMapper;
@Override
public User findUserById(int id) {
User user = userMapper.selectUserById(id);
return user;
}
}
5、在conf里配置Mybatis的配置文件:
MyBatisConf.xmll放在conf里,注意路径
<?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="User" type="com.mucfc.model.User"/>
</typeAliases>
<!-- 配置Mapper文件的路径 -->
<mappers>
<mapper resource="mapper/UserMapper.xml"/>
</mappers>
</configuration>
如果不与Spring进行整合的话,此配置文件还需要配置数据源信息,与Spring整合之后数据源就配置在Spring配置文件中,只需要配置映射文件的路径就可以了。
三、配置Spring
1、在conf里创建Spring的配置文件:(conf是和src同级的文件夹)
SpringConf.xml放在conf里,注意路径
<?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"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<!-- 配置数据源 -->
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/test" />
<property name="username" value="root" />
<property name="password" value="christmas258@" />
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:MyBatisConf.xml" />
<!-- <property name="typeAliasesPackage" value="com.tiantian.ckeditor.model"
/> -->
</bean>
<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface"
value="com.mucfc.mapper.UserMapper" />
<property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>
<!-- 自动扫描注解的bean -->
<context:component-scan base-package="com.mucfc.dao" />
</beans>
2、web.xml中启动Spring
web.xml放在WEB-INF里
<?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">
<!-- 配置初始打开的页面 -->
<!-- <welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list> -->
<!-- Spring 容器加载 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:SpringConf.xml</param-value>
</context-param>
</web-app>
其实到这里就完成了Spring+Mybatis的配置中,可以在JSP中通过Spring中创建的bean来操作数据 库了。
四、配置SpringMVC
1、首先应该先更改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">
<!-- 配置初始打开的页面 -->
<!-- <welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list> -->
<!-- Spring 容器加载 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:SpringConf.xml</param-value>
</context-param>
<!-- SpringMVC的前端控制器 -->
<servlet>
<servlet-name>MyDispatcher</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>
<!-- 何时启动 大于0的值表示容器启动时初始化此servlet,正值越小优先级越高 -->
<load-on-startup>1</load-on-startup>
</servlet>
<!-- Spring MVC配置文件结束 -->
<!-- SpringMVC拦截设置 -->
<servlet-mapping>
<servlet-name>MyDispatcher</servlet-name>
<!-- 由SpringMVC拦截所有请求 -->
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- SpringMVC拦截设置结束 -->
<!--解决中文乱码问题 -->
<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>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
2、在conf里创建SpringMVC的配置文件:(conf是和src同级的文件夹)
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util" 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"
xsi:schemaLocation="
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<mvc:annotation-driven/>
<!-- 把标记了@Controller注解的类转换为bean -->
<context:component-scan base-package="com.mucfc.controller" />
<!-- 对模型视图名称的解析,即在模型视图名称添加前后缀 -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/views/" p:suffix=".jsp" />
</beans>
3、注解@conroller类的实现
com.mucfc.controller包下新建UserController.java
package com.mucfc.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class UserController {
@RequestMapping(value="/findUser",method = RequestMethod.POST)
public String getUser(){
return "findUser";
}
@RequestMapping("/")
public String getIndex(){
return "index";
}
}
根据浏览器输入的网址,定位到不同的页面中去
五、JSP页面创建
由于SpringMVC配置了p:prefix="/WEB-INF/views/" p:suffix=".jsp" /。。。
所以要在WEB-INF中创建文件夹views,然后在这里放置JSP文件
首先是index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>查找用户信息</title>
<base href="<%=basePath%>">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<center>
<form action="findUser" method="post">
请输入用户ID:<input type="text" name="id">
<input type="submit" value="确定">
</form>
</center>
</body>
</html>
将数据传递给findUser.jsp
findUser.jsp内容如下
<%@ page import="com.mucfc.dao.UserDao"%>
<%@page import="org.springframework.web.context.WebApplicationContext"%>
<%@page import="org.springframework.web.context.support.WebApplicationContextUtils"%>
<%@ page language="java" contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Insert title here</title>
</head>
<body>
<center>
通过controller访问<br/>
欢迎<br/>
<%
WebApplicationContext wac = WebApplicationContextUtils
.getWebApplicationContext(this.getServletContext());
UserDao userDao = (UserDao) wac.getBean("userDaoImpl");
String in=(String)request.getParameter("id");
System.out.println(in);
int num=Integer.parseInt(in);
%>
<%=userDao.findUserById(num)%><br />
<%-- <%=userDao.findUserById(2)%><br />
<%=userDao.findUserById(3)%><br />
<%=userDao.findUserById(4)%><br /> --%>
</center>
</body>
</html>
根据 输入的id,来查找数据库中是否有这个人
六、运行
输入1
结果表明这个人存在
输入5,不存在这个人