`

Springmvc3+Spring3+MyBatis3

 
阅读更多

 最近写的一个三层框架:Springmvc3+Spring3+MyBatis3,后来,在Web层和Service层之间加了一个门面层,前台模块跟Web层的Controller类是对应的,Controller与门面层的类是一一对应的,在门面类中可以添加所需要的Server层所需的接口。

 

1. 项目的目录



 
2. 所用jar文件

 

3. 在MyEclipse创建Web工程

 

4. 修改/WebRoot/WEB-INF/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">
 
	<!-- 加载Spring容器配置 -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

 	<context-param>
 		<param-name>contextConfigLocation</param-name>
 		<param-value>classpath*:applicationContext.xml</param-value>
 	</context-param>
	
	<!-- 配置Spring mvc核心控制器 -->
	<servlet>
		<servlet-name>spring</servlet-name>
		<servlet-class>	org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name> 
			<param-value>/WEB-INF/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>
	
	<!-- 解决工程编码过滤器 -->
	<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>

	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
</web-app>

 
 5. 创建 Spring MVC配置文件 /WebRoot/WEB-INF/spring-servlet.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:p="http://www.springframework.org/schema/p"
 xmlns:mvc="http://www.springframework.org/schema/mvc"
 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
      http://www.springframework.org/schema/mvc
      http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
      
     <!-- 启动注解驱动的Spring MVC功能,注册请求url和注解POJO类方法的映射-->
     <mvc:annotation-driven />

     <!-- 启动包扫描功能,以便注册带有@Controller、@Service、@repository、@Component等注解的类成为spring的bean -->
     <context:component-scan base-package="com.smartcom.esp.web" />

     <!-- 动态页面配置-->
     <bean id="loginController" class="com.smartcom.esp.web.LoginController">
     	<property name="formView" value="esp/error"/>
     	<property name="succView" value="esp/main"/>
     </bean>
     
     <!-- 对模型视图名称的解析,在请求时模型视图名称添加前后缀 -->
     <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
     	<property name="prefix" value="/WEB-INF/view/"/> 
     	<property name="suffix" value=".jsp"/> 
     </bean> 
</beans>

 
 6. 创建页面:/WebRoot/login.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    <title>Login</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
  </head>
  
  <body>
   		<form action="login">
   			<div>
				<div>UserName:<input type="text" value="" name="username"></div>
				<div>Password:<input type="password" value=""  name="password"></div>
				<div><input type="reset" value="取消">&nbsp;&nbsp;<input type="submit" value="提交"></div>
   			</div>
   		</form>
  </body>
</html>

 

 

7.  创建页面:/WEB-INF/view/main.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
		<title>Home</title>
		<meta http-equiv="pragma" content="no-cache">
		<meta http-equiv="cache-control" content="no-cache">
  </head>
  <body>
    	你好:<%=((com.smartcom.esp.pojo.User)request.getSession().getAttribute("loginUser")).getUsername() %>,现在时间是<%= new Date() %>       
</body>
</html>

 

8. 创建Spring配置文件 /src/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.1.xsd
	http://www.springframework.org/schema/context 
	http://www.springframework.org/schema/context/spring-context-3.1.xsd
	http://www.springframework.org/schema/aop 
	http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
	http://www.springframework.org/schema/tx 
	http://www.springframework.org/schema/tx/spring-tx-3.1.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/bsdev" />
		<property name="username" value="root" />
		<property name="password" value="root" />
	</bean>

	<!-- 配置sqlSessionFactory -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<property name="configLocation" value="classpath:mybatis-cfg.xml" />
	</bean>

	<!-- 配置sqlSessionTemplate -->
	<bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
		<constructor-arg index="0" ref="sqlSessionFactory" />
	</bean>

	<!-- 配置事务 -->
	<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource" />
	</bean>
	<tx:annotation-driven transaction-manager="txManager" />

	<!-- 数据映射器类  mapper bean -->
	<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
		<property name="mapperInterface" value="com.smartcom.esp.dao.mapper.IUserDao" />
		<property name="sqlSessionFactory" ref="sqlSessionFactory" />
	</bean>
	
	<!-- 配置Service -->
	<bean id="userService" class="com.smartcom.esp.service.impl.UserServiceImpl">
		<property name="userDao" ref="userMapper" />
	</bean>
	
	<!-- 配置Manage -->
	<bean id="loginManage" class="com.smartcom.esp.manage.LoginManage">
		<property name="userService" ref="userService" />
	</bean>

</beans>

 

9. 创建MyBatis的配置文件:/src/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>  
	<!-- 定义实体类的别名 -->
	<typeAliases>
		<typeAlias type="com.smartcom.esp.pojo.User" alias="User" />
	</typeAliases>

	<!-- 定义映射资源 -->
	<mappers>
		<mapper resource="com/smartcom/esp/dao/mapper/IUserDao.xml" />
	</mappers>
</configuration>

 

10.  创建实体类:com.smartcom.esp.pojo.User.java

package com.smartcom.esp.pojo;

public class User {
	private Integer id;
	private String username;
	private String password;
	private Integer age;
	private Integer status;
	private String name;
	
	public final static Integer USER_LOCK=-1; 	//锁定
	public final static Integer USER_NORMAL=1;	//正常
	public final static Integer USER_NOEXISTS=0;//不存在
	
	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 Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
	
	public Integer getStatus() {
		return status;
	}
	public void setStatus(Integer status) {
		this.status = status;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public User() {
		super();
	}
	
	public User(Integer id, String username, String password, Integer age,Integer status,String name) {
		super();
		this.id = id;
		this.username = username;
		this.password = password;
		this.age = age;
		this.status = status;
		this.name = name;
	}
}

 

 

11.    创建Dao层:com.smartcom.esp.dao.mapper (勿需实现Dao层的接口)

11.1  创建Dao层接口文件:com.smartcom.esp.dao.mapper.IUserDao.java

package com.smartcom.esp.dao.mapper;

import com.smartcom.esp.pojo.User;

public interface IUserDao {
	public User findByName(String username);
}

 

11.2  创建Dao层映射文件:com.smartcom.esp.dao.mapper.IUserDao.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文件最好放在与Dao接口同一目录下 -->
<mapper namespace="com.smartcom.esp.dao.mapper.IUserDao">

	<!-- 定义数据库字段与实体对象的映射关系 -->
	<resultMap type="com.smartcom.esp.pojo.User" id="User">
		<id column="id" property="id" javaType="int" jdbcType="INTEGER" />
		<result column="name" property="name" javaType="java.lang.String" jdbcType="VARCHAR" />
		<result column="username" property="username" javaType="java.lang.String" jdbcType="VARCHAR" />
		<result column="password" property="password" javaType="java.lang.String" jdbcType="VARCHAR" />
		<result column="age" property="age" javaType="int" jdbcType="INTEGER" />
		<!-- result column="birthday" property="birthday" javaType="java.util.Date" jdbcType="DATE" / -->
	</resultMap>

	<!-- 定义要操作的SQL语句 -->

	<insert id="save" parameterType="com.smartcom.esp.pojo.User" useGeneratedKeys="true" keyProperty="id">
		insert into
		user(name,phone,birthday)
		values(#{name},#{phone},#{birthday})
	</insert>

	<update id="update" parameterType="com.smartcom.esp.pojo.User">
		update user set
		name=#{name},phone=#{phone},birthday=#{birthday}
		where id=#{id}
	</update>

	<delete id="delete" parameterType="int">
		delete from user
		where id=#{id}
	</delete>

	<select id="findByName" parameterType="String" resultMap="User">
		select *
		from user
		where username=#{username}
	</select>

	<select id="findAll" resultMap="User">
		select *
		from user
	</select>
	
</mapper> 

 

12.    创建Service层:com.smartcom.esp.service---->该层依赖Dao层(com.smartcom.esp.dao).  

12.1  创建Service层基本接口文件,所有Server中的接口都需继承该接口:com.smartcom.esp.service.IBaseService.java

package com.smartcom.esp.service;
public interface IBaseService {
        //无任何方法   
}

12.2  创建Service层接口文件:com.smartcom.esp.service.IUserService.java

package com.smartcom.esp.service;

import com.smartcom.esp.pojo.User;

public interface IUserService extends IBaseService{
	public User checkPWD(String username);
}

12.3  创建Service层实现文件:com.smartcom.esp.service.impl.UserServiceImpl.java

package com.smartcom.esp.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import com.smartcom.esp.dao.mapper.IUserDao;
import com.smartcom.esp.pojo.User;
import com.smartcom.esp.service.IUserService;

@Transactional  
public class UserServiceImpl implements IUserService {

	@Autowired
	private IUserDao userDao;
	

	public IUserDao getUserDao() {
		return userDao;
	}


	public void setUserDao(IUserDao userDao) {
		this.userDao = userDao;
	}


	@Override
	public User checkPWD(String username) {
		return userDao.findByName(username);
	} 
}

 

13.    创建门面层:com.smartcom.esp.manage---->该层依赖Service层(com.smartcom.esp.service).  

13.1  创建门面层接口文件:com.smartcom.esp.manage.IBizManage.java

package com.smartcom.esp.manage;
/**
 * 门面层
 * @author Administrator
 *
 */
public interface IBizManage<T> {
	//返回Service层对象
	public T getService();
}

 13.2  创建门面层实现文件:com.smartcom.esp.manage.LoginManage.java

package com.smartcom.esp.manage;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.smartcom.esp.service.IBaseService;
import com.smartcom.esp.service.IUserService;
/**
 * 登录门面
 * @author Administrator
 *
 */
@Service
public class LoginManage implements IBizManage<IBaseService> {
	
	@Autowired
	private IUserService userService;
	

	public IUserService getUserService() {
		return userService;
	}

	public void setUserService(IUserService userService) {
		this.userService = userService;
	}

	@Override
	public IBaseService getService() {
		if(this.userService instanceof IBaseService){
			return userService;
		}else{
			return null;
		}
	}
}

 14. 创建Web层:com.smartcom.esp.web [放置所有Controller] ---->该层依赖门面层(com.smartcom.esp.manage).  

com.smartcom.esp.web.LoginController.java

package com.smartcom.esp.web;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
 
import com.smartcom.esp.manage.IBizManage;
import com.smartcom.esp.pojo.User;
import com.smartcom.esp.service.IUserService;

/**
 * 登录
 * 
 * @author Administrator
 * 
 */
@Controller
@RequestMapping("/login")
public class LoginController extends  BaseController { 
	 
	private String formView ;
	private String succView ; 
	
	@Autowired 
	public IBizManage<IUserService> login; 
	
	public IBizManage<IUserService> getLogin() {
		return login;
	}

	public void setLogin(IBizManage<IUserService> login) {
		this.login = login;
	}
 
	public String getSuccView() {
		return succView;
	}

	public void setSuccView(String succView) {
		this.succView = succView;
	}

	public String getFormView() {
		return formView;
	}

	public void setFormView(String formView) {
		this.formView = formView;
	}

	public LoginController() {
		
	}
 
	// 用户登录
	@RequestMapping("login")
	public ModelAndView login(HttpServletRequest request, User user) {
		//由用户名取用户信息
		User dbUser = login.getService().checkPWD(user.getUsername());
		ModelAndView mav = new ModelAndView();
		mav.setViewName("forward:login");
		
		if (dbUser == null) {
			mav.addObject("errorMsg", "用户名不存在");
		} else if (!dbUser.getPassword().equals(user.getPassword())) {
			mav.addObject("errorMsg", "用户密码不正确");
		} else if (dbUser.getStatus() == User.USER_LOCK) {
			mav.addObject("errorMsg", "用户已经被锁定,不能登录");
		} else {
			mav.addObject("Msg", "登录成功");
			setSessionUser(request, dbUser);
			String toUrl = (String) request.getSession().getAttribute(LOGIN_TO_URL);
			
			// 如果当前会话中没有保存登录之前的请求URL,则直接跳转到主页
			if (StringUtils.isEmpty(toUrl)) {
				toUrl = "esp/main";			//前台首页
				//toUrl = "esptool/main"; 	//后台首页
			}
			System.out.println("++============>>:"+request.getAttribute("loginUser"));
			mav.setViewName(getSuccView());
		}
		return mav;
	}

	// 登录注销
	@RequestMapping("/doLogout")
	public String logout(HttpSession session) {
		session.removeAttribute(USER_CONTEXT);
		return "forward:/login";
	}
}

 

 15. 测试:http://localhost:8080/esp/login.jsp 

 

 

结果:      你好:lis,现在时间是Tue Nov 27 15:02:17 CST 2012 
 

 

  • 大小: 34.8 KB
  • 大小: 68 KB
  • 大小: 7.1 KB
  • esp.zip (7.2 MB)
  • 下载次数: 699
分享到:
评论
2 楼 larryscale 2013-06-04  
zz_wangyuhoho 写道
你这个工程跑不起来呀


我测试过的,可以跑起来的,你的报什么错?
1 楼 zz_wangyuhoho 2013-05-22  
你这个工程跑不起来呀

相关推荐

Global site tag (gtag.js) - Google Analytics