Spring_Springmvc_mybatis一般配置

时间:2021-11-09 16:11:37

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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
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>Archetype Created Web Application</display-name>

<!-- 读取spring配置文件 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:conf/spring.xml;
classpath:conf/spring-mybatis.xml
</param-value>
</context-param>
<!-- 设计路径变量值 -->
<context-param>
<param-name>webAppRootKey</param-name>
<param-value>springmvc.root</param-value>
</context-param>
<!-- 日志记录 -->
<context-param>
<!-- 日志配置文件路径 -->
<param-name>log4jConfigLocation</param-name>
<param-value>classpath:conf/log4j.properties</param-value>
</context-param>
<context-param>
<!-- 日志页面的刷新间隔 -->
<param-name>log4jRefreshInterval</param-name>
<param-value>60000000</param-value>
</context-param>

<!-- 启动日志-->
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
<!-- 启动Spring容器-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<!-- Spring mvc访问静态资源-->
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.css</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.js</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.ico</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.gif</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.jpg</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.png</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.bmp</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.jpeg</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.swf</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.flv</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.xml</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.txt</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<!-- Spring字符集过滤器 -->
<filter>
<filter-name>SpringEncodingFilter</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>SpringEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

<!-- 访问的首页,也可以在tomcat-web.xml配置-->
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<!-- springMVC核心配置 -->
<servlet>
<servlet-name>springMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>WEB-INF/spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springMVC</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>

<!-- 错误跳转页面 -->
<error-page>
<!-- 路径不正确 -->
<error-code>404</error-code>
<location>/WEB-INF/errorpage/404.jsp</location>
</error-page>
<error-page>
<!-- 没有访问权限,访问被禁止 -->
<error-code>405</error-code>
<location>/WEB-INF/errorpage/405.jsp</location>
</error-page>
<error-page>
<!-- 内部错误 -->
<error-code>500</error-code>
<location>/WEB-INF/errorpage/500.jsp</location>
</error-page>
</web-app>

web容器执行的顺序是context-->listener-->filter-->servlet

因为用了Springmvc 做请求控制 所以首页<welcome-file-list>配置信息放在Springmvc配置的上面

Spring xml配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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.xsd">

<!-- 引入jdbc配置文件 -->
<context:property-placeholder location="classpath:conf/jdbc.properties"/>
<!-- 扫描文件 自动将service层和dao层组件注入 -->
<context:component-scan base-package="cn.springmvc.service"></context:component-scan>
<context:component-scan base-package="cn.springmvc.dao"></context:component-scan>
</beans>

1.读取jdbc的配置

2.扫面dao和service就行

mybatis.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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="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
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-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/util
http://www.springframework.org/schema/util/spring-util-3.2.xsd">

<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init"
destroy-method="close" >
<property name="driverClassName">
<value>${jdbc_driverClassName}</value>
</property>
<property name="url">
<value>${jdbc_url}</value>
</property>
<property name="username">
<value>${jdbc_username}</value>
</property>
<property name="password">
<value>${jdbc_password}</value>
</property>
<!-- 连接池最大使用连接数 -->
<property name="maxActive">
<value>20</value>
</property>
<!-- 初始化连接大小 -->
<property name="initialSize">
<value>1</value>
</property>
<!-- 获取连接最大等待时间 -->
<property name="maxWait">
<value>60000</value>
</property>
<!-- 连接池最大空闲 -->
<property name="maxIdle">
<value>20</value>
</property>
<!-- 连接池最小空闲 -->
<property name="minIdle">
<value>3</value>
</property>
<!-- 自动清除无用连接 -->
<property name="removeAbandoned">
<value>true</value>
</property>
<!-- 清除无用连接的等待时间 -->
<property name="removeAbandonedTimeout">
<value>180</value>
</property>
<!-- 连接属性 -->
<property name="connectionProperties">
<value>clientEncoding=UTF-8</value>
</property>
</bean>

<!-- mybatis文件配置,扫描所有mapper文件 -->
<bean id="sqlSessionFactory"
class="org.mybatis.spring.SqlSessionFactoryBean"
p:dataSource-ref="dataSource"
p:configLocation="classpath:conf/mybatis-config.xml"
p:mapperLocations="classpath:mapper/*.xml"/><!-- configLocation为mybatis属性 mapperLocations为所有mapper-->

<!-- spring与mybatis整合配置,扫描所有dao.impl -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"
p:basePackage="cn.springmvc.dao.Impl"
p:sqlSessionFactoryBeanName="sqlSessionFactory"/>
<!-- SqlSessionTemplate -->
<bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactory"/>
<constructor-arg index="1" value="BATCH"/>
</bean>

<!-- 对数据源进行事务管理 -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
p:dataSource-ref="dataSource"/>
</beans>

mybatis-config.xm为实体类启别名

<?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="cn.springmvc.model.User"/>
</typeAliases>

<!-- 映射map -->
<mappers>
</mappers>
</configuration>

数据库和实体类的映射

<?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="cn.springmvc.dao.UserDAO">
<!-- 将db查询出来的结果映射到Model User -->
<resultMap type="cn.springmvc.model.User" id="user">
<id column="id" property="id"/>
<result column="name" property="name"/>
<result column="age" property="age"/>
<result column="hobby" property="hobby"/>
</resultMap>
<!-- 根据id查询 返回Gt_user类型-->
<select id="selectUserById" resultMap="user" parameterType="int">
select id,name,age,hobby
from t_user where pk = #{pk}
</select>
<!-- 查询所有user 返回resultMap类型-->
<select id="selectAllUser" resultMap="user">
select id,name,age,hobby from t_user
</select>
<!-- 指定parameterType=map 其中map的形式为Map<String,PageBean> map-->
<select id="selectuserByPage" resultMap="user" parameterType="map">
<!-- order by id asc是指对查询后的结果进行升序排序 -->
<!-- <![CDATA[
select * from
(select g.*,rownum rn from (select * from goods) g where 1=1 and rownum <= #{pageBean.endNumber})
where rn >= #{pageBean.startNumber}
order by id asc
]]> -->
<![CDATA[select * from t_user limit #{page.startNumber},#{page.endNumber}]]>
</select>
<!-- 新增t_user 参数类型为user-->
<insert id="insertUser" parameterType="user">
insert into t_user(name,age,hobby)
values(#{name},#{age},#{hobby})
</insert>
<!-- 更新user 参数类型为user-->
<update id="updateUser" parameterType="user">
update t_user
set name = #{name},age =#{age},hobby=#{hobby}
where id = #{id}
</update>
<!-- 删除user 参数类型为int-->
<delete id="deleteUser" parameterType="int">
delete from t_user
where id = #{id}
</delete>
</mapper>

JDBC的配置

jdbc_driverClassName=com.mysql.jdbc.Driver
jdbc_url=jdbc:mysql://ip/数据库名?useUnicode=true&amp;characterEncoding=UTF-8
jdbc_username=用户名
jdbc_password=密码

日志配置 log4j.properties

### set log levels ###
#log4j.rootLogger = debug , stdout , D , E
log4j.rootLogger = debug , stdout , D

### output to the console ###
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target = System.out
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
#log4j.appender.stdout.layout.ConversionPattern = %d{ABSOLUTE} %5p %c{ 1 }:%L - %m%n
log4j.appender.stdout.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [%c]-[%p] %m%n

### Output to the log file ###
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File = ${springmvc.root}/WEB-INF/logs/log.log
log4j.appender.D.Append = true
log4j.appender.D.Threshold = DEBUG
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

### Save exception information to separate file ###
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File = ${springmvc.root}/WEB-INF/logs/error.log
log4j.appender.D.Append = true
log4j.appender.D.Threshold = ERROR
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p

接下来就是接口

package cn.springmvc.dao;

import java.util.List;
import java.util.Map;

import cn.springmvc.model.User;
import cn.springmvc.pageQurty.PageBean;

public interface UserDAO {
/**
* 娣诲姞鐢ㄦ埛
* @author 鐜嬫灄
* 2015骞�鏈�9鏃�
*/
public int insertUser(User user);
/**
* 鏇存柊鐢ㄦ埛
* @author 鐜嬫灄
* 2015骞�鏈�9鏃�
*/
public int updateUser(User user);
/**
* 鍒犻櫎鐢ㄦ埛
* @author 鐜嬫灄
* 2015骞�鏈�9鏃�
*/
public int deleteUser(Integer id);
/**
* 鏌ヨ涓�釜鐢ㄦ埛
* @author 鐜嬫灄
* 2015骞�鏈�9鏃�
*/
public User findUserById(Integer id);
/**
* 鎵�湁鐢ㄦ埛
* @author 鐜嬫灄
* 2015骞�鏈�9鏃�
*/
public List<User> findAllUser();
/**
* 鐢ㄦ埛鍒嗛〉
* @author 鐜嬫灄
* 2015骞�鏈�9鏃�
*/
public List<User> findUserByPage(Map<String, PageBean> map);

}

DAO实现类

package cn.springmvc.dao.Impl;

import java.util.List;
import java.util.Map;

import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.springmvc.dao.UserDAO;
import cn.springmvc.model.User;
import cn.springmvc.pageQurty.PageBean;

@Service
public class UserDaoImpl implements UserDAO {

@Autowired
private SqlSessionFactory sessionFactory;

@Override
public int insertUser(User user) {
// clark--userMapper.xml 娑擃厼鎳¢崥宥団敄闂傜ame = clark,insertGood---insert id
int result = sessionFactory.openSession().insert(
"cn.springmvc.dao.UserDAO.insertUser", user);
// mybatis娴滃澧块棁锟筋洣閹靛濮╅幓鎰唉閿涘矂绮拋銈勮礋false
sessionFactory.openSession().commit();
return result;
}

@Override
public int updateUser(User user) {
int result = sessionFactory.openSession().update(
"cn.springmvc.dao.UserDAO.updateUser", user);
// mybatis娴滃澧块棁锟筋洣閹靛濮╅幓鎰唉閿涘矂绮拋銈勮礋false
sessionFactory.openSession().commit();
return result;
}

@Override
public int deleteUser(Integer id) {
int result = sessionFactory.openSession().delete(
"cn.springmvc.dao.UserDAO.deleteUser", id);
// mybatis娴滃澧块棁锟筋洣閹靛濮╅幓鎰唉閿涘矂绮拋銈勮礋false
sessionFactory.openSession().commit();
return result;
}

@Override
public User findUserById(Integer id) {
User user = sessionFactory.openSession().selectOne(
"cn.springmvc.dao.UserDAO.selectUserById", id);
return user;
}

@Override
public List<User> findAllUser() {
List<User> users = sessionFactory.openSession().selectList(
"cn.springmvc.dao.UserDAO.selectAllUser");
return users;
}

@Override
public List<User> findUserByPage(Map<String, PageBean> map) {
List<User> users = sessionFactory.openSession().selectList(
"cn.springmvc.dao.UserDAO.selectuserByPage", map);
return users;
}

}

Service接口

package cn.springmvc.service;

import java.util.List;
import java.util.Map;

import cn.springmvc.model.User;
import cn.springmvc.pageQurty.PageBean;

public interface UserService {
/**
* 娣诲姞鐢ㄦ埛
* @author 鐜嬫灄
* 2015骞�鏈�9鏃�
*/
public int insertUser(User user);
/**
* 鏇存柊鐢ㄦ埛
* @author 鐜嬫灄
* 2015骞�鏈�9鏃�
*/

public int updateUser(User user);
/**
* 鍒犻櫎鐢ㄦ埛
* @author 鐜嬫灄
* 2015骞�鏈�9鏃�
*/

public int deleteUser(Integer id);
/**
* 鏌ヨ涓�釜鐢ㄦ埛
* @author 鐜嬫灄
* 2015骞�鏈�9鏃�
*/

public User findUserById(Integer id);
/**
* 鏌ヨ鎵�湁鐢ㄦ埛
* @author 鐜嬫灄
* 2015骞�鏈�9鏃�
*/

public List<User> findAllUser();

/**
* 鐢ㄦ埛鍒嗛〉
* @author 鐜嬫灄
* 2015骞�鏈�9鏃�
*/
public List<User> findUserByPage(Map<String, PageBean> map);
}

service实现类

package cn.springmvc.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.springmvc.dao.UserDAO;
import cn.springmvc.model.User;
import cn.springmvc.pageQurty.PageBean;
import cn.springmvc.service.UserService;
/**
* UserService瀹炵幇
* @author 鐜嬫灄
* 2015骞�鏈�9鏃�
* @version 1.0
*/

@Service
public class UserServiceImpl implements UserService{
/**
* 瀹炵幇鎺ュ彛
*/
@Autowired
private UserDAO userDAO;
/**
* 娣诲姞鐢ㄦ埛
*/
@Override
public int insertUser(User user) {
int insertUser = userDAO.insertUser(user);
return insertUser;
}
/**
* 鏇存柊鐢ㄦ埛
*/
@Override
public int updateUser(User user) {
return userDAO.updateUser(user);
}
/**
* 鍒犻櫎鐢ㄦ埛
*/
@Override
public int deleteUser(Integer id) {
int deleteUser = userDAO.deleteUser(id);
return deleteUser;
}
/**
* 鏌ヨ涓�釜鐢ㄦ埛
*/
@Override
public User findUserById(Integer id) {
User findUserById = userDAO.findUserById(id);
return findUserById;
}
/**
* 鏌ヨ鎵�湁鐢ㄦ埛
*/
@Override
public List<User> findAllUser() {
List<User> findAllUser = userDAO.findAllUser();
return findAllUser;
}
/**
* 鐢ㄦ埛鍒嗛〉
*/
@Override
public List<User> findUserByPage(Map<String, PageBean> map) {
//Example page涔焟apper.xml鐨勫弬鏁颁竴鑷�
/*Map<String,PageBean> map=new HashMap<String,PageBean>();
PageBean pageBean=new PageBean();
pageBean.setStartNumber(0);
pageBean.setEndNumber(2);
map.put("page", pageBean);*/
List<User> findUserByPage = userDAO.findUserByPage(map);
return findUserByPage;
}
}

最后controller

package cn.springmvc.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import cn.springmvc.model.User;
import cn.springmvc.service.UserService;

@Controller
@RequestMapping("/home")
public class UserController {
@Autowired
private UserService userService;

@RequestMapping("/user")
public String index(Model model){
List<User> findAllUser = userService.findAllUser();
model.addAttribute("UserAll",findAllUser);
return "index";
}

}

访问

最后配置通过域名或者IP直接访问项目

tomcat conf-->server.xml配置修改

<Connector connectionTimeout="20000" port="80" protocol="HTTP/1.1" redirectPort="8443"/>

在<host><host>中间 加上

<Context path="" docBase="项目名(就是部署到webapps下面的名字)" debug="0"/>

上面项目已经设置首页了 直接输入localhost或者IP或者你申请的域名直接访问项目。