spring+springmvc+mybatis框架基础配置
1.jar包
jar包地址:
https://pan.baidu.com/s/1HOWC3iJO3PPcIRi-hxVtnw
2.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" 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>MyBatisPro05</display-name>
<welcome-file-list>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list>
<!-- Spring配置文件 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!-- 编码过滤器 -->
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<async-supported>true</async-supported>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- Spring监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 添加对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>classpath:spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
<async-supported>true</async-supported>
</servlet>
<servlet-mapping>
<servlet-name>springMVC</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>
3.spring 配置
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd ">
<!--***********spring 框架中的配置******************** -->
<!-- 自动扫描 -->
<context:component-scan base-package="com.java1234.service" />
<!--<context:component-scan base-package="com.java1234.quartz" />-->
<!-- 加载定时任务 -->
<task:annotation-driven/>
<!-- 配置数据源 -->
<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/db_crm"/>
<property name="username" value="root"/>
<property name="password" value="duran"/>
</bean>
<!-- DAO接口所在包名,Spring会自动查找其下的类 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.java1234.dao" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
</bean>
<!-- 配置mybatis的sqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!-- 自动扫描mappers.xml文件 -->
<property name="mapperLocations" value="classpath:com/java1234/mappers/*.xml"></property>
<!-- mybatis配置文件 -->
<property name="configLocation" value="classpath:mybatis-config.xml"></property>
</bean>
<!-- (事务管理)transaction manager, use JtaTransactionManager for global tx -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- 配置事务通知属性 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<!-- 定义事务传播属性 -->
<tx:attributes>
<tx:method name="insert*" propagation="REQUIRED" />
<tx:method name="update*" propagation="REQUIRED" />
<tx:method name="edit*" propagation="REQUIRED" />
<tx:method name="save*" propagation="REQUIRED" />
<tx:method name="add*" propagation="REQUIRED" />
<tx:method name="new*" propagation="REQUIRED" />
<tx:method name="set*" propagation="REQUIRED" />
<tx:method name="remove*" propagation="REQUIRED" />
<tx:method name="delete*" propagation="REQUIRED" />
<tx:method name="change*" propagation="REQUIRED" />
<tx:method name="check*" propagation="REQUIRED" />
<tx:method name="get*" propagation="REQUIRED" read-only="true" />
<tx:method name="find*" propagation="REQUIRED" read-only="true" />
<tx:method name="load*" propagation="REQUIRED" read-only="true" />
<tx:method name="*" propagation="REQUIRED" read-only="true" />
</tx:attributes>
</tx:advice>
<!-- 配置事务切面 -->
<aop:config>
<aop:pointcut id="serviceOperation"
expression="execution(* com.java1234.service.*.*(..))" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="serviceOperation" />
</aop:config>
</beans>
4.springMvc 配置
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<!--***********springMvc 框架中的配置******************** -->
<!-- 使用注解的包,包括子集 -->
<context:component-scan base-package="com.java1234.controller" />
<!-- 视图解析器 -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/" />
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
mybatis-config.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>
<!-- 别名 -->
<typeAliases>
<package name="com.java1234.entity"/>
</typeAliases>
</configuration>
5. 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="com.java1234.dao.UserDao">
<resultMap type="User" id="UserResult">
<result property="id" column="id"/>
<result property="userName" column="userName"/>
<result property="password" column="password"/>
<result property="trueName" column="trueName"/>
<result property="email" column="email"/>
<result property="phone" column="phone"/>
<result property="roleName" column="roleName"/>
</resultMap>
<select id="login" parameterType="User" resultMap="UserResult">
select * from t_user where userName=#{userName} and password=#{password} and roleName=#{roleName}
</select>
<select id="find" parameterType="Map" resultMap="UserResult">
select * from t_user
<where>
<if test="userName!=null and userName!='' ">
and userName like #{userName}
</if>
<if test="roleName!=null and roleName!='' ">
and roleName like #{roleName}
</if>
</where>
<if test="start!=null and size!=null">
limit #{start},#{size}
</if>
</select>
<select id="getTotal" parameterType="Map" resultType="Long">
select count(*) from t_user
<where>
<if test="userName!=null and userName!='' ">
and userName like #{userName}
</if>
<if test="roleName!=null and roleName!='' ">
and roleName like #{roleName}
</if>
</where>
</select>
<insert id="add" parameterType="User">
insert into t_user values(null,#{userName},#{password},#{trueName},#{email},#{phone},#{roleName})
</insert>
<update id="update" parameterType="User">
update t_user
<set>
<if test="userName!=null and userName!='' ">
userName=#{userName},
</if>
<if test="password!=null and password!='' ">
password=#{password},
</if>
<if test="trueName!=null and trueName!='' ">
trueName=#{trueName},
</if>
<if test="email!=null and email!='' ">
email=#{email},
</if>
<if test="phone!=null and phone!='' ">
phone=#{phone},
</if>
<if test="roleName!=null and roleName!='' ">
roleName=#{roleName},
</if>
</set>
where id=#{id}
</update>
<delete id="delete" parameterType="Integer">
delete from t_user where id=#{id}
</delete>
</mapper>
6.entity
package com.java1234.entity;
/**
* 用户实体
* @author Administrator
*
*/
public class User {
private Integer id; // 编号
private String userName; // 用户名
private String password; // 密码
private String trueName; // 真实姓名
private String email; // 邮件
private String phone; // 联系电话
private String roleName; // 角色名称 系统管理员 销售主管 客户经理 高管
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 String getTrueName() {
return trueName;
}
public void setTrueName(String trueName) {
this.trueName = trueName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
}
6.dao层
package com.java1234.dao;
import java.util.List;
import java.util.Map;
import com.java1234.entity.User;
/**
* 用户Dao接口
* @author Administrator
*
*/
public interface UserDao {
/**
* 用户登录
* @param user
* @return
*/
public User login(User user);
/**
* 查询用户集合
* @param map
* @return
*/
public List<User> find(Map<String,Object> map);
/**
* 获取总记录数
* @param map
* @return
*/
public Long getTotal(Map<String,Object> map);
/**
* 修改用户
* @param user
* @return
*/
public int update(User user);
/**
* 添加用户
* @param user
* @return
*/
public int add(User user);
/**
* 删除用户
* @param id
* @return
*/
public int delete(Integer id);
}
7 server接口
package com.java1234.service;
import java.util.List;
import java.util.Map;
import com.java1234.entity.User;
/**
* 用户Service接口
* @author Administrator
*
*/
public interface UserService {
/**
* 用户登录
* @param user
* @return
*/
public User login(User user);
/**
* 查询用户集合
* @param map
* @return
*/
public List<User> find(Map<String,Object> map);
/**
* 获取总记录数
* @param map
* @return
*/
public Long getTotal(Map<String,Object> map);
/**
* 修改用户
* @param user
* @return
*/
public int update(User user);
/**
* 添加用户
* @param user
* @return
*/
public int add(User user);
/**
* 删除用户
* @param id
* @return
*/
public int delete(Integer id);
}
8 service 实现类
package com.java1234.service.impl;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.java1234.dao.UserDao;
import com.java1234.entity.User;
import com.java1234.service.UserService;
/**
* 用户Service实现类
* @author Administrator
*
*/
@Service("userService")
public class UserServiceImpl implements UserService{
@Resource
private UserDao userDao;
@Override
public User login(User user) {
return userDao.login(user);
}
@Override
public List<User> find(Map<String, Object> map) {
return userDao.find(map);
}
@Override
public Long getTotal(Map<String, Object> map) {
return userDao.getTotal(map);
}
@Override
public int update(User user) {
return userDao.update(user);
}
@Override
public int add(User user) {
return userDao.add(user);
}
@Override
public int delete(Integer id) {
return userDao.delete(id);
}
}
8 controller层
package com.java1234.controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.java1234.entity.PageBean;
import com.java1234.entity.User;
import com.java1234.service.UserService;
import com.java1234.util.ResponseUtil;
import com.java1234.util.StringUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
/**
* 用户Controller层
* @author Administrator
*
*/
@Controller
@RequestMapping("/user")
public class UserController {
@Resource
private UserService userService;
/**
* 用户登录
* @param user
* @param request
* @return
* @throws Exception
*/
@RequestMapping("/login")
public String login(User user,HttpServletRequest request)throws Exception{
User resultUser=userService.login(user);
if(resultUser==null){
request.setAttribute("user", user);
request.setAttribute("errorMsg", "用户名或密码错误!");
return "login";
}else{
HttpSession session=request.getSession();
session.setAttribute("currentUser", resultUser);
return "redirect:/main.jsp";
}
}
/**
* 分页条件查询用户
* @param page
* @param rows
* @param s_user
* @param response
* @return
* @throws Exception
*/
@RequestMapping("/list")
public String list(@RequestParam(value="page",required=false)String page,@RequestParam(value="rows",required=false)String rows,User s_user,HttpServletResponse response)throws Exception{
PageBean pageBean=new PageBean(Integer.parseInt(page),Integer.parseInt(rows));
Map<String,Object> map=new HashMap<String,Object>();
map.put("userName", StringUtil.formatLike(s_user.getUserName()));
map.put("start", pageBean.getStart());
map.put("size", pageBean.getPageSize());
List<User> userList=userService.find(map);
Long total=userService.getTotal(map);
JSONObject result=new JSONObject();
JSONArray jsonArray=JSONArray.fromObject(userList);
result.put("rows", jsonArray);
result.put("total", total);
ResponseUtil.write(response, result);
return null;
}
/**
* 获取客户经理信息 下拉框数据用到
* @param response
* @return
* @throws Exception
*/
@RequestMapping("/customerManagerComboList")
public String customerManagerComboList(HttpServletResponse response)throws Exception{
Map<String,Object> map=new HashMap<String,Object>();
map.put("roleName", "客户经理");
List<User> userList=userService.find(map);
JSONArray row=JSONArray.fromObject(userList);
ResponseUtil.write(response, row);
return null;
}
/**
* 添加或者修改用户
* @param user
* @param response
* @return
* @throws Exception
*/
@RequestMapping("/save")
public String save(User user,HttpServletResponse response)throws Exception{
int resultTotal=0; // 操作的记录条数
if(user.getId()==null){
resultTotal=userService.add(user);
}else{
resultTotal=userService.update(user);
}
JSONObject result=new JSONObject();
if(resultTotal>0){
result.put("success", true);
}else{
result.put("success", false);
}
ResponseUtil.write(response, result);
return null;
}
/**
* 删除用户
* @param ids
* @param response
* @return
* @throws Exception
*/
@RequestMapping("/delete")
public String delete(@RequestParam(value="ids")String ids,HttpServletResponse response)throws Exception{
String []idsStr=ids.split(",");
for(int i=0;i<idsStr.length;i++){
userService.delete(Integer.parseInt(idsStr[i]));
}
JSONObject result=new JSONObject();
result.put("success", true);
ResponseUtil.write(response, result);
return null;
}
/**
* 修改用户密码
* @param user
* @param response
* @return
* @throws Exception
*/
@RequestMapping("/modifyPassword")
public String modifyPassword(Integer id,String newPassword,HttpServletResponse response)throws Exception{
User user=new User();
user.setId(id);
user.setPassword(newPassword);
int resultTotal=userService.update(user);
JSONObject result=new JSONObject();
if(resultTotal>0){
result.put("success", true);
}else{
result.put("success", false);
}
ResponseUtil.write(response, result);
return null;
}
/**
* 用户注销
* @param session
* @return
* @throws Exception
*/
@RequestMapping("/logout")
public String logout(HttpSession session)throws Exception{
session.invalidate();
return "redirect:/login.jsp";
}
}