SSH整合之入门级例子:简易留言板(完整源码)

一.环境说明


  • Windows 10 ver 1703
  • IDEA 2017 2.5
  • JDK 1.8
  • MySQL 5.7
  • Maven 3.5

二.框架说明


  • ※Spring 4.3.11
  • ※SpringMVC 4.3.11
  • ※Hibernate 5.2.11
  • ※Bootstrap 3.3.7
  • ※Flat UI 2.3

三.项目说明


利用SSH三大框架,实现一个留言页面,可以展示留言以及添加留言,基于注解.

四.源码


项目结构:
SSH整合之入门级例子:简易留言板(完整源码)_第1张图片

实体类:
Msg.class

package com.cs.qsx.domain;

import com.alibaba.fastjson.annotation.JSONField;

import javax.persistence.*;
import java.util.Date;

@Entity
@Table(name = "tb_msg")
public class Msg {
    @Id //主键
    @GeneratedValue(strategy = GenerationType.IDENTITY) //自增
    private Integer id;
    @Column(length = 10)
    private String name;
    @Column(length = 100)
    private String context;
    @Column(columnDefinition = "DATE") //指定属性在表中的字段类型
    @JSONField(format = "yyyy-MM-dd")  //指定json格式化时如何格式化date
    private Date createDate;

    public Msg() {
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getContext() {
        return context;
    }

    public void setContext(String context) {
        this.context = context;
    }

    public Date getCreateDate() {
        return createDate;
    }

    public void setCreateDate(Date createDate) {
        this.createDate = createDate;
    }
}

数据库连接配置
dbconfig.properties

jdbc.driverclass=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/Msg_Test?characterEncoding=UTF-8
jdbc.username=root
jdbc.password=123456

Spring配置文件
applicationContext.xml






	
	

	
	
	
	
		
		
		
		
		

		
		

		
		
		
		

		
		

		
		

		
		

		
		
		

		
		
		
	
	
	
		
		
		
		
			
				
				org.hibernate.dialect.MySQL57Dialect
				
				false
				
				false
				
				update
				
				
				org.springframework.orm.hibernate5.SpringSessionContext
				
			
		
		
		
			com.cs.qsx.domain
		
	
	
	
		
	
	
	
	
	

SpringMVC配置文件
springmvc.xml




    
        
            
            
                
            
            
            
                
                
                    
                        application/json
                        text/html;charset=UTF-8
                    
                
                
            
        
    

    
    
        
        
        
        
        
            
                WriteNullListAsEmpty
            
        
    
    

    
    

    
    

    
    
        
        
    

     
		
        
            10485760
        
        
        
        	UTF-8
        
    


项目配置文件
web.xml



    
    
        org.springframework.web.context.ContextLoaderListener
    
    
        contextConfigLocation
        /WEB-INF/applicationContext*.xml
    


    
    
        springmvc
        
            org.springframework.web.servlet.DispatcherServlet
        
        
            contextConfigLocation
            /WEB-INF/springmvc-config.xml
        
        1
    
    
        springmvc
        /
    
    
    
    
        characterEncodingFilter
        org.springframework.web.filter.CharacterEncodingFilter
        
            encoding
            UTF-8
        
    
    
        characterEncodingFilter
        /*
    

    
        index.jsp
    

Maven依赖
pom.xml


  4.0.0
  com.cs.qsx
  SSH_Msg
  war
  1.0-SNAPSHOT
  SSH_Msg Maven Webapp
  http://maven.apache.org
  
    
      junit
      junit
      3.8.1
      test
    
    
    
      org.springframework
      spring-aspects
      4.3.11.RELEASE
    
    
    
      org.springframework
      spring-orm
      4.3.11.RELEASE
    
    
      org.springframework
      spring-webmvc
      4.3.11.RELEASE
    
    
    
      org.hibernate
      hibernate-core
      5.2.11.Final
    
    
    
      com.alibaba
      druid
      1.1.3
    
    
    
      mysql
      mysql-connector-java
      5.1.44
    
    
    
      javax.servlet
      javax.servlet-api
      3.1.0
      provided
    
    
      junit
      junit
      RELEASE
    
    
    
      javax.servlet
      jstl
      1.2
    
    
    
      javax.servlet.jsp
      javax.servlet.jsp-api
      2.3.1
      provided
    
    
    
      commons-fileupload
      commons-fileupload
      1.3.3
    
    
    
      com.alibaba
      fastjson
      1.2.38
    
  

  
    SSH_Msg
    
    
      
        org.apache.maven.plugins
        maven-compiler-plugin
        3.7.0
        
          1.8
          1.8
          UTF-8
        
      
    
  


页面
leaveMessage.jsp

<%--
  Created by IntelliJ IDEA.
  User: 17535
  Date: 2017/10/11
  Time: 8:31
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    留言板
    
    
    
    




请输入留言

业务逻辑层(接口)
MsgService.class

package com.cs.qsx.service;

import com.cs.qsx.domain.Msg;

import java.util.List;

public interface MsgService {
    //查询
    public List findAll();
    //新增
    public void addMsg(Msg msg);
}

业务逻辑层(实现类)
MsgServiceImpl.class

package com.cs.qsx.service.impl;

import com.cs.qsx.dao.MsgDao;
import com.cs.qsx.domain.Msg;
import com.cs.qsx.service.MsgService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class MsgServiceImpl implements MsgService {

    @Autowired
    private MsgDao msgDao;

    @Override
    public List findAll() {
        return msgDao.queryAll();
    }

    @Override
    public void addMsg(Msg msg) {
        msgDao.insertMsg(msg);
    }
}

数据持久层(接口)
MsgDao.class

package com.cs.qsx.dao;

import com.cs.qsx.domain.Msg;

import java.util.List;

public interface MsgDao {
    //查询
    public List queryAll();
    //新增
    public void insertMsg(Msg msg);
}

数据持久层(实现类)
MsgDaoImpl.class

package com.cs.qsx.dao.impl;

import com.cs.qsx.dao.MsgDao;
import com.cs.qsx.domain.Msg;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;

import javax.annotation.PostConstruct;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Repository("msgDao")
public class MsgDaoImpl extends HibernateDaoSupport implements MsgDao {

    @Autowired
    private SessionFactory sessionFactory;

    @PostConstruct
    protected void injectSessionFactory() {
        super.setSessionFactory(sessionFactory);
    }

    @Override
    public List queryAll() {
        return (List) getHibernateTemplate().find("from Msg");
    }

    @Override
    public void insertMsg(Msg msg) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date date = null;
        try {
            date = simpleDateFormat.parse(simpleDateFormat.format(new Date()));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        msg.setCreateDate(date);
        getHibernateTemplate().save(msg);
    }
}

控制器
MsgController.class

package com.cs.qsx.controller;

import com.cs.qsx.domain.Msg;
import com.cs.qsx.service.MsgService;
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.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Controller
public class MsgController {

    @Autowired
    private MsgService msgService;

    @RequestMapping("/msg")
    public String showMsg() {
        return "leaveMessage";
    }

    @ResponseBody
    @RequestMapping("/api/msg")
    public List msgapi(HttpServletResponse response) {
        List msgs = msgService.findAll();
        return msgs;
    }

    @RequestMapping("/addMsg")
    public String addMsg(Msg msg){
        msgService.addMsg(msg);
        return "leaveMessage";
    }

}

过滤器
HibernateFlushFilter.class

package com.cs.qsx.filter;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.dao.DataAccessResourceFailureException;
import org.springframework.orm.hibernate5.support.OpenSessionInViewFilter;

import javax.persistence.FlushModeType;
import javax.servlet.annotation.WebFilter;

/**
 * Servlet Filter implementation class HibernateFlushFilter
 * 为了解决Spring二次修改Hibernate的FlushMode
 *
 */
@WebFilter("/*")
public class HibernateFlushFilter extends OpenSessionInViewFilter {
	@Override
	protected Session openSession(SessionFactory sessionFactory) throws DataAccessResourceFailureException {
		// TODO Auto-generated method stub
		Session session=sessionFactory.openSession();
		session.setFlushMode(FlushModeType.AUTO);
		return session;
	}

}

字符过滤器
EncodingFilter.class

package com.cs.qsx.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Map;

@WebFilter(filterName = "EncodeFilter", urlPatterns = "/*")
public class EncodeFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        //获取请求
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletRequest myRequest = new MyRequest(request);

        //处理响应乱码
        resp.setContentType("text/html;charset=utf-8");

        //放行
        chain.doFilter(myRequest,resp);

    }

    //自定义一个请求
    class MyRequest extends HttpServletRequestWrapper {
        private HttpServletRequest request;
        private boolean hasEncode = false;

        public MyRequest(HttpServletRequest request) {
            super(request);
            this.request = request;
        }

        @Override
        public String getParameter(String s) {
            //通过自己定义的已经处理过字符编码问题的方法获取map
            Map parameterMap = getParameterMap();
            //根据map获取值,值是数组
            String[] values = parameterMap.get(s);
            if (values == null){
                return null;
            }
            //取一个值,这个值就是数组的第0个元素
            return values[0];
        }

        @Override
        public String[] getParameterValues(String s) {
            Map parameterMap = getParameterMap();
            String[] values = parameterMap.get(s);
            return values;
        }


        //重写getParmeterMap方法,在内部把map中的中文乱码处理掉
        @Override
        public Map getParameterMap() {
            //处理中文乱码,区别对待get和post
            String method = request.getMethod();
            if ("post".equalsIgnoreCase(method)) {
                //处理post乱码
                try {
                    request.setCharacterEncoding("utf-8");
                    return request.getParameterMap();
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            } else if ("get".equalsIgnoreCase(method)) {
                //处理get乱码
                Map parameterMap = request.getParameterMap();
                //对于每一个内容都要重新编码再解码
                /*
                说明:tomcat8之前的版本,默认编码格式是iso-8859-1
                在8之后,就是utf-8了,所以只需要对Tomcat8之前的版本进行处理即可
                 */
                String servletInfo = request.getServletContext().getServerInfo();
                if (!hasEncode) {
                    if (servletInfo.substring(servletInfo.lastIndexOf(File.separator) + 1).charAt(0) < 56) {
                        for (String parameterName : parameterMap.keySet()) {
                            //根据键拿到值,这个值并不确定是几个值
                            String[] values = parameterMap.get(parameterName);
                            if (values != null) {
                                for (int i = 0; i < values.length; i++) {
                                    try {
                                        values[i] = new String(values[i].getBytes("ISO-8859-1"), "UTF-8");
                                    } catch (UnsupportedEncodingException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }
                        }
                        hasEncode = true;
                    }
                }
                return parameterMap;
            }
            return super.getParameterMap();
        }
    }

    public void init(FilterConfig config) throws ServletException {

    }

}

附:

Flat UI 官网:
Flat UI 官网

效果图:
SSH整合之入门级例子:简易留言板(完整源码)_第2张图片

成功的路上,总有坎坷,走过去,迎接你的将是—下一个坎坷.

2017/10/11
Slicenfer

你可能感兴趣的:(记录)