码迷,mamicode.com
首页 > 编程语言 > 详细

Spring4 SpringMVC Hibernate4 Freemaker 整合例子

时间:2014-05-26 04:31:14      阅读:622      评论:0      收藏:0      [点我收藏+]

标签:springmvc   freemaker   bootstrap   整合   

前话:

           写了半年的Flex,也就是一个做一个WEB的视频监控浏览端,已经初步成型,现在是要做一个管理平台,于是终于又要用回JAVA了,但是一切都变的陌生了,

比如写个方法或者定义一个变量,总是会用Flex的语法去写,以前都是用Struts2 Hibernate Spring框架的,现在据说springMVC更流行了,于是花了这一周时间入了下门,感觉

确实不错,我是看的这个系列教程,跟开涛学SpringMvc http://jinnianshilongnian.iteye.com/category/231099,写的很赞,通俗易懂,非常感谢!

后来顺便也看了下这个前端开发框架Bootstrap也很不错,简直是后端开发人员的福音啊,并且我发现改版后的CSDN登录界面也用到了这个框架,所以学习了下,也是在

一个系列博客中看的,http://www.cnblogs.com/aehyok/p/3404867.html#title02 其实是跟Bootstrap中文网的教程差不多,但是在博客中看比较集中,并且目录清晰,当时在中文网看的12栅格布局是真心没看懂,后来在这位仁兄的博

客中看懂了,在这里非常感谢!

今天周五,所以简单的整合了一下来熟悉这周看的东西

老规矩(有图有真相),先看下相关效果图吧:

登录界面:(Bootstrap的样式还挺赞的吧)

bubuko.com,布布扣

主页面:

bubuko.com,布布扣

添加:

bubuko.com,布布扣

修改:(上面的修改和删除你要点击一下某一行,才能进行操作)

bubuko.com,布布扣

项目目录结构:

bubuko.com,布布扣bubuko.com,布布扣


部分配置和相关代码:

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://xmlns.jcp.org/xml/ns/javaee"
	xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
	id="Bufoon_WebApp_ID" version="3.1">
	<display-name>WebApp</display-name>
	
	
	<!-- log4j配置。如果不需要下面的配置,可以将log4j文件放到src目录下,log4j会默认加载 -->
	<context-param>  
        <param-name>log4jConfigLocation</param-name>  
        <param-value>classpath:/properties/log4j.properties</param-value>  
    </context-param>  
      
    <context-param>  
        <param-name>log4jRefreshInterval</param-name>  
        <param-value>60000</param-value>  
    </context-param>  
    <listener>  
        <listener-class>  
            org.springframework.web.util.Log4jConfigListener  
        </listener-class>  
    </listener>  
    
	<!-- 添加对spring的支持 -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:/xml/applicationContext.xml</param-value>
	</context-param>

	<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>
		<load-on-startup>1</load-on-startup>
		<!-- 添加配置文件,如果不想要厦门的配置,可以将 [servlet-name]-servlet.xml放到WEB-INF目录下,springMVC会默认加载 -->
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:/xml/springMVC-servlet.xml</param-value>
		</init-param>
	</servlet>
	<servlet-mapping>
		<servlet-name>springMVC</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>

	<!-- 添加UTF-8编码支持 -->
	<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>

	
	<!-- 当hibernate+spring配合使用的时候,如果设置了lazy=true,那么在读取数据的时候,当读取了父数据后, hibernate会自动关闭session,这样,当要使用子数据的时候,系统会抛出lazyinit的错误, 
		这时就需要使用spring提供的 OpenSessionInViewFilter,OpenSessionInViewFilter主要是保持Session状态 
		知道request将全部页面发送到客户端,这样就可以解决延迟加载带来的问题 -->
	<filter>
		<filter-name>openSessionInViewFilter</filter-name>
		<filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
		<init-param>
			<param-name>singleSession</param-name>
			<param-value>true</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>openSessionInViewFilter</filter-name>
		<url-pattern>*.do,*.action</url-pattern>
	</filter-mapping>
	
	<welcome-file-list>
		<welcome-file>login.jsp</welcome-file>
	</welcome-file-list>
</web-app>
springMVC-servlet.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:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
	http://www.springframework.org/schema/beans/spring-beans.xsd
	http://www.springframework.org/schema/context
	http://www.springframework.org/schema/context/spring-context-3.2.xsd
	http://www.springframework.org/schema/mvc
	http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">

	<!-- 注解扫描包 -->
	<context:component-scan base-package="com.bufoon.controller" />

	<!-- 开启注解 -->
	<mvc:annotation-driven />

	<!-- 静态资源的访问 -->
	<mvc:resources location="/plugins/" mapping="/plugins/**" />

	<!-- 返回JSON模版 -->
	<bean
		class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
		<property name="messageConverters">
			<list>
				<bean
					class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" />
			</list>
		</property>
	</bean>
	<!-- 注意:FreeMarker与SpringMVC集成时,其配置一定要放在SpringMVC的配置之前 -->
	<!-- 否则:在访问"/getUser"时服务器就会报告[HTTP Status 404 - /WEB-INF/jsp/myfree.jsp] -->
	<bean id="freemarkerConfig"
		class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
		<!-- 指定FreeMarker模板文件目录 -->
		<property name="templateLoaderPath" value="/WEB-INF/app/ftl/" />
		<!-- 编码设置 -->
		<property name="freemarkerSettings">
			<props>
				<prop key="defaultEncoding">UTF-8</prop>
			</props>
		</property>
	</bean>
	<bean id="freeMarkerViewResolver"
		class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
		<property name="prefix" value="" />
		<property name="suffix" value=".ftl" />
		<property name="contentType" value="text/html; charset=UTF-8" />
	</bean>

	<!-- 定义视图解析器 -->
	<bean id="viewResolver"
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/app/"></property>
		<property name="suffix" value=".jsp"></property>
	</bean>
</beans>

UserController.java

package com.bufoon.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.bufoon.entity.User;
import com.bufoon.model.UserModel;
import com.bufoon.service.UserService;
import com.bufoon.util.Constants;
import com.bufoon.util.Util;
import com.bufoon.util.page.PageResultSet;

@Controller
@RequestMapping("/user")
public class UserController {

	@Resource
	private UserService userService;
	
	@RequestMapping("/userLogin")
	public String userLogin(UserModel userModel, Model model){
		userModel.setPassword(Util.encryptMD5(userModel.getPassword()));
		User user = userService.findUserByByCondition(userModel);
		if (user == null) {
			model.addAttribute("errorInfo", "you password is error!");
			return "login";
		}
		
		Constants.LOGIN_USER = user.getUsername();
		return "redirect:/user/index";
	}
	@RequestMapping("/addUser")
	public String addUser(UserModel userModel){
		Date date = new Date();
		User user = new User();
		BeanUtils.copyProperties(userModel, user); //实体属性复制,将userModel中的属性值复制到User中
		user.setPassword(Util.encryptMD5(userModel.getPassword()));
		user.setCreateTime(date);
		user.setUpdateTime(date);
		user.setUpdateUser(Constants.LOGIN_USER);
		user.setCreateUser(Constants.LOGIN_USER);
		userService.saveUser(user);
		return "redirect:/user/index";
	}
	@RequestMapping("/index")
	public ModelAndView index(UserModel userModel, HttpServletRequest request) {  
		if(Util.isNull(Constants.LOGIN_USER)){
			ModelAndView mav = new ModelAndView("login");
			mav.addObject("errorInfo", "user is overdue!");
			return mav;
		}
	    return new ModelAndView("userList");  
	 }  
	
	@RequestMapping("/getUser")
	public void getUser(HttpServletRequest request, HttpServletResponse response, Model model) {  
	    int id = Integer.parseInt(request.getParameter("userId"));
	    User user = userService.getUserById(id);
	    Map<String, Object> map = new HashMap<String, Object>();
	    map.put("user", user);
	    model.addAttribute("user", user);
	 }  
	
	@RequestMapping("/updateUser")
	public String updateUser(UserModel userModel){
		Date date = new Date();
		User user = userService.getUserById(userModel.getId());
		if (Util.isNull(userModel.getPassword())) {
			userModel.setPassword(user.getPassword());
		}else {
			userModel.setPassword(Util.encryptMD5(userModel.getPassword()));
		}
		userModel.setCreateTime(user.getCreateTime());
		userModel.setUpdateTime(date);
		userModel.setCreateUser(Constants.LOGIN_USER);
		userModel.setUpdateUser(Constants.LOGIN_USER);
		BeanUtils.copyProperties(userModel, user);
		userService.updateUser(user);
		return "redirect:/user/index";
	}
	
	@RequestMapping("/deleteUser")
	public String deleteUser(HttpServletRequest request){
		  int id = Integer.parseInt(request.getParameter("userId"));
		  User user = userService.getUserById(id);
		  userService.deleteUser(user);
		  return "redirect:/user/index";
	}
	
	@RequestMapping("/exit")
	public String exit(){
		Constants.LOGIN_USER = null;
		return "redirect:/";
	}
	//返回json
	@RequestMapping("/getJsonUserList")
	@ResponseBody
	public ModelMap getJsonUserList(UserModel userModel, HttpServletRequest request, HttpServletResponse response) {
		ModelMap modelMap = new ModelMap();
		response.setHeader("Access-Control-Allow-Origin", "*");
		String sPage = request.getParameter("page");
		int page = 1;
		if (!Util.isNull(sPage)) {
			page = Integer.parseInt(sPage);
		}
		PageResultSet<User> userPageResult = userService.findPageUserList(userModel, page, Constants.PAGE_SIZE);
		
		modelMap.addAttribute("event",userPageResult.getList());
		modelMap.addAttribute("pageBean", userPageResult.getPage());
		modelMap.addAttribute("pageCount",userPageResult.getPage().getTotalPage());
		return modelMap;
	}
	  
}

代码还是挺多的,不贴了

DEMO源码到这里下载吧:http://download.csdn.net/detail/soanl/7391345

说明:在项目的doc下有数据库文件,

新建数据库名为 db_shf,编码设为utf-8,然后导入就行

运行 http://你的ip:端口port/WebApp  用户名:admin,密码:admin

下周开始把mina学习下,因为公司项目之间的通信都是用socket通信的,在这个管理平台也要用到socket同主服务器通信

http://blog.csdn.net/songanling/article/details/26732977 by 布丰(Bufoon)

Spring4 SpringMVC Hibernate4 Freemaker 整合例子,布布扣,bubuko.com

Spring4 SpringMVC Hibernate4 Freemaker 整合例子

标签:springmvc   freemaker   bootstrap   整合   

原文地址:http://blog.csdn.net/songanling/article/details/26732977

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!