Spring+Spring MVC+MyBatis+postgreSQL步骤整理
- 创建maven工程,在pom.xml中添加工程所需的jar包依赖,并且加入:
<!--防止java目录下xml文件不编译-->
<resources>
<resource>
<directory>src/main/resources</directory>
</resource>
<resource>
<directory>src/main/java</directory>
<excludes>
<exclude>**/*.java</exclude>
</excludes>
</resource>
</resources>
<testResources>
<testResource>
<directory>src/test/resources</directory>
<filtering>true</filtering>
</testResource>
</testResources>
- 使用Tomcat运行webAPP验证是否存在环境变量配置错误.
- 创建java和resources资源包,并在java1文件中创建包com.luojuan,包下新建文件夹:dao,controller,entity和mapper.
- 根据实际需求创建实体类User.java
public class User {
private Integer id;
private String username;
private String password;
……..getter,setter,toString}
- 根据实际需求在postgresql建立数据表,将主键设置为自增方式.
- 配置数据库映射文件UserMapper接口以及UserMapper.xml
UserMapper接口:
public interface UserMapper {
/**
* 用户注册
* @param
* @return
*/
Integer register(Map<String,Object> map);
/**
* 用户登录
* @param
* @return
*/
User login(Map<String,Object> map);
}
UserMapper.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="com.luojuan.mapper.UserMapper">
<resultMap id="userResultMap" type="com.luojuan.entity.User">
<id property="id" column="id"/>
<result property="username" column="username"/>
<result property="password" column="password"/>
</resultMap>
<insert id="register">
insert into u_user(username,password) values(#{username},#{password})
</insert>
<select id="login" resultMap="userResultMap">
select * from u_user where username=#{username} and password=#{password}
</select>
</mapper>
- 写dipatcher的配置文件spring-servlet.xml,配置扫描控制器,注解驱动以及视图解析器.
- 写数据库配置相关设置文件applicationContext.xml
<context:annotation-config />
<!--扫描业务层-->
<context:component-scan base-package="com.luojuan.dao"/>
<context:component-scan base-package="com.luojuan.mapper"/>
<context:component-scan base-package="com.luojuan.controller"/>
<!--使用Tomcat JDBC连接池-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" >
<property name="driverClassName" value="org.postgresql.Driver" />
<property name="url" value="jdbc:postgresql://10.13.66.11:5432/postgres" />
<property name="username" value="postgres" />
<property name="password" value="342501" />
</bean>
<!--配置sqlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--引用数据源-->
<property name="dataSource" ref="dataSource"/>
<!--扫描类的映射文件-->
<property name="mapperLocations" value="classpath:com/luojuan/mapper/*.xml"/>
</bean>
<!--配置映射接口,spring自动查找下面的接口-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.luojuan.mapper"/>
</bean>
<!--配置事务管理器-->
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--配置事务通知-->
<tx:advice transaction-manager="txManager" id="txAdvice">
<tx:attributes>
<tx:method name="register*"/>
<tx:method name="save*"/>
<tx:method name="update*"/>
<tx:method name="delete*"/>
<tx:method name="get*" propagation="SUPPORTS" read-only="true"/>
<tx:method name="login*" propagation="SUPPORTS" read-only="true"/>
</tx:attributes>
</tx:advice>
<!--配置aop增强处理-->
<aop:config>
<aop:advisor advice-ref="txAdvice" pointcut="execution(* com.luojuan.dao.*.*(..))"/>
</aop:config>
- 在web.xml中将以上dispatcher配置文件spring-servlet.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_3_1.xsd"
version="3.1">
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<!--上下文配置-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!--配置springMVC自带的乱码过滤器 -->
<filter>
<filter-name>characterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<!--初始化字符编码为utf-8 -->
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
<!-- 强制将请求的编码格式设置为utf-8 -->
<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>
<!-- 加载监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
- 写User的与数据库交互层Dao接口以及实现类,根据功能设计接口:
public interface UserDao {
Boolean register(String username,String password);
User login(String username,String password);
}
@Service(value = "userDao")
public class UserDaoImpl implements UserDao {
@Autowired
private UserMapper userMapper;
@Override
public Boolean register(String username, String password) {
Map<String,Object> map=new HashMap<>();
map.put("username",username);
map.put("password",password);
Integer result=userMapper.register(map);
if (result==1){
return true;
}
return false;
}
@Override
public User login(String username, String password) {
Map<String,Object> map=new HashMap<>();
map.put("username",username);
map.put("password",password);
User user=userMapper.login(map);
return user;
}
}
- 写User的控制层程序UserController.java:
@Controller
public class UserController {
@Resource
private UserDao userDao;
@RequestMapping(value = "/register",method = RequestMethod.POST)
public String register(String username,String password){
if(!"".equals(username)&&!"".equals(password)){
Boolean result=userDao.register(username, password);
if(result){
return "success";//为了防止刷新页面时表单重复提交
}
}
return "";
}
@RequestMapping(value = "/login",method = RequestMethod.POST)
public String login(String username, String password, Model model){
if(!"".equals(username)&&!"".equals(password)){
User user=userDao.login(username, password);
if(null!=user){
model.addAttribute("username",user.getUsername());
return "success";
}
}
return "";
}
@RequestMapping("/")
public String showIndex(){
return "index";
}
@RequestMapping("/success")
public String showSuccess(){
return "success";
}
}
- 编写界面程序.jsp
重点: :1.在MyBatis中,Java中的byte[]一般对应数据库类型:BLOB,LONGVARBINARY以及一些和二进制流有关的字段类型.
2.Mapper的接口和XML关联的时候,命名空间namespace需要配置成接口的全限定名称,MyBatis就是通过这个值将接口和XML关联起来
3.MyBatis使用java动态代理可以直接通过接口来调用相应的方法,不需要提供接口的实现类.
4. <select id="login" resultMap="userResultMap">
select * from u_user where username=#{username} and password=#{password}
</select>
在Mapper中select的id属性值和定义的接口方法名需要保持一致,MyBatis就是通过这种方法将接口方法与XML定义的SQL语句关联到一起的.resultMap用于指定返回值的类型和映射关系.
<resultMap id="userResultMap" type="com.luojuan.entity.User">
<id property="id" column="id"/>
<result property="username" column="username"/>
<result property="password" column="password"/>
</resultMap>
5.接口中定义的返回值类型必须和XML中配置的resultMap中的type类型一致.有一种情况是接口返回类的List,若确定xml语言只会返回一个对象,则无需特别指定为List,返回相应类即可.
6.在INSERT方法中,若使用主键自增时,插入数据库后可能需要得到自增主键值,若insert无需插入主键而且MyBatis想使用从数据库内部生成的主键,则需要在insert标签配置属性:
UseGeneratedKeys=”true”
KeyProperty=”id”