springmvc 孔浩 hibernate code

model--User 

package model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;

@Entity
@Table(name="t_user")
public class User {
	private int id;
	private String username;
	private String password;
	private String nickname;
	private String email;
	
	@GeneratedValue
	@Id
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	@NotEmpty(message="用户名不能为空")
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	@NotEmpty(message="用户密码不能为空")
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public String getNickname() {
		return nickname;
	}
	public void setNickname(String nickname) {
		this.nickname = nickname;
	}
	@Email(message="邮件格式不正确")
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}	
	
}

注:添加@Entity, @Table, @GeneratedValue, @Id, 各种验证。

问题:有时候需要加construct,有时不需要。

model--UserException

extends RuntimeException

default serial ID

右键 source generate constructors form superclass

model--Pager

public class Pager<T> 类名后加<T>,表示任何数据都可以

model--IUserDao

package user.dao;

import java.util.List;

import org.springframework.stereotype.Repository;

import user.model.Pager;
import user.model.User;
@Repository("UserDao") public interface IUserDao { public void add(User user); public void update(User user); public void delete(User user); public User load(int id); public User loadByUsername(String username); public List<User> list(); public Pager<User> find(); }

model--UserDao

implements IUserDao 

extends HibernateDaoSupport

package user.dao;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;

import user.model.Pager;
import user.model.User;

//将dao类声明为bean @Repository("UserDao") public class UserDao extends HibernateDaoSupport implements IUserDao { @Resource public void setSuperSessionFactory(SessionFactory sessionFactory){ this.setSessionFactory(sessionFactory); } @Override public void add(User user) { // TODO Auto-generated method stub this.getHibernateTemplate().save(user); } @Override public void update(User user) { // TODO Auto-generated method stub this.getHibernateTemplate().update(user); } @Override public void delete(User user) { // TODO Auto-generated method stub this.getHibernateTemplate().delete(user); } @Override public User load(int id) { // TODO Auto-generated method stub return this.getHibernateTemplate().load(User.class, id); } @Override public User loadByUsername(String username) { // TODO Auto-generated method stub return (User)this.getSession().createQuery("form User where username=?").setParameter(0, username).uniqueResult(); } @Override public List<User> list() { // TODO Auto-generated method stub return this.getSession().createQuery("form User").list(); } @Override public Pager<User> find() { // TODO Auto-generated method stub return null; } }

实现类中加@Repository("UserDao")

hibernate常用的查询方法

return this.getHibernateTemplate().save(user);  //update,delete
return this.getHibernateTemplate().load(User.class, id);
return (User)this.getSession().createQuery("form User where username=?").setParameter(0, username).uniqueResult();
return this.getSession().createQuery("form User").list();

model-IUserService

package user.service;

import java.util.List;

import user.model.Pager;
import user.model.User;

public interface IUserService {
	public void add(User user);
	public void update(User user);
	public void delete(User user);
	public User load(int id);	
	public List<User> list();
	public Pager<User> find();
	public User login(String username, String password);
}

model--UserService

添加@Service("UserService")

注入IUserDao

package user.service;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import user.dao.IUserDao;
import user.model.Pager;
import user.model.User;
import user.model.UserException;

@Service("UserService")
public class UserService implements IUserService {
	
     //注入IUserDao private IUserDao userDao; public IUserDao getUserDao() { return userDao; } @Resource public void setUserDao(IUserDao userDao) { this.userDao = userDao; } @Override public void add(User user) { User u = userDao.loadByUsername(user.getUsername()); if(u!=null) throw new UserException("要添加的用户已存在"); userDao.add(user); } @Override public void update(User user) { userDao.update(user); } @Override public void delete(User user) { userDao.delete(user); } @Override public User load(int id) { return userDao.load(id); } @Override public List<User> list() { return userDao.list(); } @Override public Pager<User> find() { return userDao.find(); } @Override public User login(String username, String password) { User u = userDao.loadByUsername(username); if(u == null) throw new UserException("用户名不存在"); if(!u.getPassword().equals(password)) throw new UserException("登陆密码不正确"); return u; } }

service常用的方法

会注入IUserDao,如果dao和service的方法名相同,直接userDao.add(); //update, delete, load,  list, find
User u = userDao.loadByUsername(username);
if(u == null) throw new UserException("用户名不存在");
if(!u.getPassword().equals(password)) throw new UserException("登陆密码不正确");

web--UserController:应该很熟悉了

注入IUserService

model--SystemContext:不知道参数表示什么意思

package user.model;

public class SystemContext {
	private static ThreadLocal<Integer> offset = new ThreadLocal<Integer>();
	private static ThreadLocal<Integer> size = new ThreadLocal<Integer>();
	
	public static Integer getOffset() {
		return offset.get();
	}
	public static void setOffset(Integer _offset) {		
		offset.set(_offset);
	}
	public static void removeOffset(){
		offset.remove();
	}
	public static Integer getSize() {
		return size.get();
	}
	public static void setSize(Integer _size) {
		size.set(_size);
	}
	public static void removeSize(){
		size.remove();
	}	
}

web--SystemContextFilter

implements Filter(javax servlet)

package user.web;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import user.model.SystemContext;

public class SystemContextFilter implements Filter {

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse resp,
			FilterChain chain) throws IOException, ServletException {
		int offset = 0;
		try{
			offset = Integer.parseInt(req.getParameter("pager.offset"));
		}catch(NumberFormatException e){
			
		}
		try{
              //获取这两个参数 SystemContext.setOffset(offset); SystemContext.setSize(15); chain.doFilter(req, resp); }finally{ SystemContext.removeOffset(); SystemContext.removeSize(); } } @Override public void init(FilterConfig arg0) throws ServletException { // TODO Auto-generated method stub } }

  

user-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:p="http://www.springframework.org/schema/p"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        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-3.0.xsd">
    <mvc:annotation-driven />
	<context:component-scan base-package="zttc.itat.web" />    
      
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
    
    <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver" >
    <!-- 配置这个属性 -->
    <property name="exceptionMappings">
        <props>
            <!-- 如果发现的是UserException,就到error页面 -->
            <prop key="user.model.UserException">error</prop>
        </props>
    </property>
    </bean>
</beans>

web.xml:添加了很多filter

<?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_3_0.xsd" id="WebApp_ID" version="3.0">
	<display-name>springmvc_user</display-name>
	<!-- 编码方式 -->
	<filter>
	    <filter-name>CharacterFilter</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>CharacterFilter</filter-name>
	    <url-pattern>/*</url-pattern>
	</filter-mapping>
	
	<servlet>
	    <servlet-name>user</servlet-name>
	    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
	    <load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
	    <servlet-name>user</servlet-name>
	    <url-pattern>/</url-pattern>
	</servlet-mapping>
	
      <!-- 创建Spring的监听器 -->
      <listener>
    	  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  	</listener>
  	<!-- Spring 的监听器可以通过这个上下文参数来获取beans.xml的位置 -->
  	<context-param>
    	  <param-name>contextConfigLocation</param-name>
    	  <param-value>classpath*:beans.xml</param-value>	    
  	</context-param>
  	<!-- Spring中提供了  org.springframework.orm.hibernate3.support.OpenSessionInViewFilter;这个类来实现OpenSessionInViewer的操作 -->  	
  	<filter>
		<filter-name>openSessionInViewerFilter</filter-name>
		<filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>openSessionInViewerFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	<!-- 获取分页参数 -->
	<filter>
	<filter-name>SystemContextFilter</filter-name>
	<filter-class>zttc.itat.web.SystemContextFilter</filter-class>		
	</filter>
	
	<filter-mapping>
		<filter-name>SystemContextFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	<!-- login -->
	<filter>
		<filter-name>LoginFilter</filter-name>
		<filter-class>zttc.itat.web.LoginFilter</filter-class>		
	</filter>
	
	<filter-mapping>
		<filter-name>LoginFilter</filter-name>
		<url-pattern>/user/*</url-pattern>
	</filter-mapping>
	<!-- sitemesh -->  
       <filter>
    	  <filter-name>sitemesh</filter-name>
    	  <filter-class>com.opensymphony.sitemesh.webapp.SiteMeshFilter</filter-class>
  	</filter>
  	<filter-mapping>
    	  <filter-name>sitemesh</filter-name>
    	  <url-pattern>/*</url-pattern>
  	</filter-mapping>
</web-app> 

decorators.xml

<?xml version="1.0" encoding="UTF-8"?>

<decorators  defaultdir = "/WEB-INF/decorators">
	<excludes>
		<pattern>/exclude.jsp</pattern>
		<pattern>/exclude/*</pattern>
	</excludes>
	
	<decorator name="main" page="main.jsp">
		<pattern>/*</pattern>
	</decorator>
</decorators>

WEB-INF--decorators--main.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://www.opensymphony.com/sitemesh/decorator" prefix="decorator" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title><decorator:title default="欢迎使用用户管理系统"/></title>
<link rel="stylesheet" type="text/css" href="<%=request.getContextPath()%>/css/main.css"/>
<decorator:head/>
</head>
<body>
<h1><decorator:title /></h1>
<decorator:body />
<div align="center" style="width:100%;border-top:1px solid; float:left;margin-top:10px;">
	CopyRight@2012-2015<br/>
	开发培训教学项目
</div>
</body>
</html>

在jsp页面获取根目录:request.getContextPath()

list.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>用户列表</title>
</head>
<body>
<table width="700" align="center" border="1">
	<th>
	<td>id</td><td>用户名</td><td>密码</td><td>昵称</td><td>email</td>
	</th>
	<c:if test="${pagers.total le 0 }">
	<tr>
	<td colspan="6">没有用户数据</td>
	</tr>
	</c:if>
	<c:if test="${pagers.total gt 0 }">
	<c:forEach items="${pagers.datas }" var="u">
	<tr>
	<td>${u.id }</td>
	<td>${u.username }</td>
	<td>${u.password }</td>
	<td><a href="${u.id}">${u.nickname }</a></td>
	<td><a href="${u.id}/update">update</a><a href="${u.id}/delete">delete</a></td>
	</tr>
	</c:forEach>
	<tr>
	<td colspan="6">
     //引入分页 <jsp:include page="/inc/pager.jsp"> <jsp:param value="users" name="url"/> <jsp:param value="${pagers.total }" name="items"/> </jsp:include> </td> </tr> </c:if> </table> </body> </html>

webcontent--inc--pager.jsp 看不懂

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib prefix="pg" uri="http://jsptags.com/tags/navigation/pager" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<pg:pager maxPageItems="15" items="${param.items }" export="curPage=pageNumber" url="${param.url }">
<c:forEach items="${param.params }" var="p">
	<pg:param name="${p }"/>
</c:forEach>
<pg:last>
共${items }记录,共${pageNumber }页,
</pg:last>
当前第${curPage }页
<pg:first>
	<a href="${pageUrl }">首页</a>
</pg:first>
<pg:prev>
	<a href="${pageUrl }">上一页</a>
</pg:prev>
<pg:pages>

<c:if test="${curPage eq pageNumber }">
	[${pageNumber }]
</c:if>
<c:if test="${curPage ne pageNumber }">
	<a href="${pageUrl }">${pageNumber }</a>
</c:if>
</pg:pages>
<pg:next>
	<a href="${pageUrl }">下一页</a>
</pg:next>
<pg:last>
	<a href="${pageUrl }">尾页</a>
</pg:last>
</pg:pager>

总结:

分页用的是pager这种方法,以后不知道会不会用

sitemesh差不多了

springmvc hibernate的整合,也熟悉了。分层架构,dao注入service,service注入controller  

 

 

 

 

 

posted on 2015-06-19 15:56  j.w  阅读(330)  评论(0编辑  收藏  举报