zoukankan      html  css  js  c++  java
  • 实习小结(二)--- SSM框架搭建

    SSM项目框架搭建

      前几天做了一个学生信息管理的项目,使用纯控制台输入,查询数据库,将信息在控制台中打印,功能完善得差不多之后,老师让将这个项目移植到Web中,使用Spring+SpringMVC+MyBatis将项目做成网页,借此机会熟悉一下SSM框架的搭建流程。

    项目的目录结构如下:

    SSM框架搭建流程:

    1、项目所需要的jar包

      图片中的jar包可能一些多于的包,另外在开发中遇到没有导入的包的时候再去下载

    2、配置文件

    (1)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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 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">
      
      <!-- 该监听器监听应用的启动,加载Spring的配置文件,默认加载WEB-INF下的名字为applicationContext.xml文件
          并创建Spring容器 -->
      <listener>
          <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
      </listener>
      
      <!-- 告诉ContextLoaderListener下面配置的文件也是需要加载的 -->
      <context-param>
          <param-name>contextConfigLocation</param-name>
          <param-value>classpath:applicationContext.xml</param-value>
      </context-param>
      
      <!-- 拦截器用于解决post请求中请求参数值可能出现乱码的情况 -->
      <filter>
          <filter-name>characterEncoding</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>characterEncoding</filter-name>
          <url-pattern>/*</url-pattern>
      </filter-mapping>
      
      <!-- 配置SpringMVC中的分发控制器DispatcherServlet     默认加载WEB-INF下的springmvc-servlet.xml -->
      <servlet>
          <servlet-name>springmvc</servlet-name>
          <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
          <load-on-startup>1</load-on-startup>
      </servlet>
      <servlet-mapping>
          <servlet-name>springmvc</servlet-name>
          <url-pattern>*.do</url-pattern>
      </servlet-mapping>
      
      <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
      </welcome-file-list>
    </web-app>

    (2)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.xsd
      http://www.springframework.org/schema/mvc
      http://www.springframework.org/schema/mvc/spring-mvc.xsd
      ">
      
      <!-- 让Spring识别注解 -->
      <context:component-scan base-package="com.sysystem.controller"></context:component-scan>
      <!-- 让SpringMVC识别注解 -->
      <mvc:annotation-driven></mvc:annotation-driven>
      
      <!-- 配置视图解析器  如果是显式转发,则可以不需要视图解析器-->
      <bean id="resourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
          <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
          <property name="prefix" value="/"/>
          <property name="suffix" value=".jsp"/>
      </bean> 
        
        <!-- 配置文件上传解析器 -->
        <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>
        
    </beans>

    (3)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"
        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.xsd
      ">
      
        
        <!-- 让Spring识别注解 -->
        <context:component-scan base-package="com.sysystem"></context:component-scan>
        
        <!-- 配置数据源,指出连接数据库需要的驱动、url、用户名和密码以及连接池相关信息 -->
        <bean id="dbcpdataSource" class="org.apache.commons.dbcp.BasicDataSource">
            <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
            <property name="url" value="jdbc:mysql://localhost:3306/traineeinfo"></property>
            <property name="username" value="root"></property>
            <property name="password" value="root"></property>
            <property name="initialSize" value="20"></property>
            <property name="maxActive" value="10"></property>
            <property name="maxIdle" value="3"></property>
            <property name="minIdle" value="2"></property>
        </bean>
    
        <bean id="SqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <property name="configLocation" value="classpath:mybatis-config.xml"/>
            <property name="dataSource" ref="dbcpdataSource"/>
        </bean>
        
        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer" >
            <property name="basePackage" value="com.sysystem.model.dao"/>
            <property name="sqlSessionFactory" ref="SqlSessionFactory"></property>
        </bean>
    
    </beans>

    (4)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.sysystem.model.entity"/>
        </typeAliases>
        
      <!-- 注册映射文件 -->
      <mappers>
        <package name="com.sysystem.model.dao"/>
      </mappers>
    </configuration>

    3、测试

    student.java  Student学生类,标准的JavaBean,属性私有,提供setter/getter方法

    dao层

      IStudentDao.java  数据操作对象接口

    package com.sysystem.model.dao;
    
    import java.util.List;
    import java.util.Map;
    
    import com.sysystem.model.entity.Student;
    
    public interface IStudentDao {
        // 获取所有的学生信息
        List<Student> getAllStudentWithPage(Map<String,Object> map);
        // 根据学生id查询学生信息
        Student getSingleStudent(int stu_id);
        // 获得学生表的记录个数
        int getStuRows();
        // 新增学生信息
        boolean addStu(Student stu);
        // 修改学生信息
        boolean updateStu(Student stu);
        
        
    }

      IStudentDao.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.sysystem.model.dao.IStudentDao">
        <select id="getSingleStudent" parameterType="int" resultType="Student">
            select stu_name,birthday,sex,school from stu_info where stu_id = #{stu_id}
        </select>
    
        <select id="getStuRows" resultType="int">
            select count(1) from (SELECT
            s.stu_id FROM (stu_info s LEFT JOIN stu_pro_relation spr ON s.stu_id = spr.stu_id)
            LEFT JOIN project p ON p.pro_id = spr.pro_id) temp
        </select>
    
        <select id="getAllStudentWithPage" parameterType="java.util.Map" resultType="Student">
            SELECT s.stu_id,s.stu_name,CEIL(DATEDIFF(CURDATE(), s.birthday) /
            365.2422) age,
            s.sex,s.school,p.pro_id,p.pro_name,p.`code`
            FROM
            (stu_info s LEFT JOIN stu_pro_relation spr ON s.stu_id = spr.stu_id)
            LEFT JOIN project p ON p.pro_id = spr.pro_id
            LIMIT
            #{pageStart},#{pageSize}
        </select>
        
        <insert id="addStu" parameterType="Student">
            insert into stu_info (stu_name,birthday,sex,school) 
            values (#{stu_name},#{birthday},#{sex},#{school})
        </insert>
        
        <update id="updateStu" parameterType="Student">
            update stu_info set stu_name = #{stu_name},birthday = #{birthday},sex = #{sex},school = #{school} where stu_id = #{stu_id}
        </update>
    
    </mapper>

    service层

      IStudentService.java   

    package com.sysystem.model.service;
    
    import java.util.List;
    import java.util.Map;
    
    import com.sysystem.model.entity.Student;
    
    public interface IStudentService {
        // 获取所有的学生信息
        List<Student> getAllStudentWithPage(Map<String,Object> map);
        // 根据学生id查询学生信息
        Student getSingleStudent(int stu_id);
        // 获得学生表的记录个数
        int getStuRows();
        // 新增学生信息
        boolean addStu(Student stu);
        // 修改学生信息
        boolean updateStu(Student stu);
    }

      StudentServiceImpl.java  通过Dao获取对象,然后进行业务逻辑实现

    package com.sysystem.model.service.impl;
    
    import java.util.List;
    import java.util.Map;
    
    import javax.annotation.Resource;
    
    import org.springframework.stereotype.Service;
    
    
    import com.sysystem.model.dao.IStudentDao;
    import com.sysystem.model.entity.Student;
    import com.sysystem.model.service.IStudentService;
    
    @Service("stuService")
    public class StudentServiceImpl implements IStudentService {
        @Resource
        private IStudentDao stuDao;
        
        @Override
        public Student getSingleStudent(int stu_id) {
            return stuDao.getSingleStudent(stu_id);
        }
    
        @Override
        public int getStuRows() {
            return stuDao.getStuRows();
        }
    
        @Override
        public List<Student> getAllStudentWithPage(Map<String,Object> map) {
            return stuDao.getAllStudentWithPage(map);
        }
    
        @Override
        public boolean addStu(Student stu) {
            return stuDao.addStu(stu);
        }
    
        @Override
        public boolean updateStu(Student stu) {
            return stuDao.updateStu(stu);
        }
    
    }

    控制层Controller

      BaseController.java

    package com.sysystem.controller;
    
    import java.io.IOException;
    import java.io.PrintWriter;
    
    import javax.servlet.http.HttpServletResponse;
    
    import com.google.gson.Gson;
    
    public class BaseController {
        
        /**
         * 向响应的输出流写文本数据
         * @param response 响应
         * @param str 文本数据
         */
        public void writeToRes (HttpServletResponse response, String str){
            // 设置输出的字符集
            response.setContentType("text/html;charset=utf-8");
            // 定义输出流对象
            PrintWriter out = null;
            try {
                out = response.getWriter();
                out.print(str);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                out.close();
            }
        }
        
        /**
         * 向响应的输出流写json数据
         * @param response 响应
         * @param obj json数据
         */
        public void writeToRes (HttpServletResponse response, Object obj){
            response.setContentType("text/html;charset=utf-8");
            PrintWriter out = null;
            try {
                out = response.getWriter();
                String json = new Gson().toJson(obj);
                out.print(json);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                out.close();
            }
        }
        
    }

      StudentController.java

    package com.sysystem.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 org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    import com.sysystem.model.entity.Student;
    import com.sysystem.model.service.IStudentService;
    import com.sysystem.model.util.ChangeDate;
    import com.sysystem.model.util.Page;
    
    @Controller
    @RequestMapping("/student")
    public class StudentController extends BaseController{
        @Resource
        private IStudentService studentService;
    
        /**
         * 根据学生的id获取学生信息
         * @param request 请求
         * @param response 响应
         * @param stu_id 学生id
         * @return 指定页面前缀
         * @throws Exception
         */
        @RequestMapping("/getSingleStudent")
        public String getSingleStudent(HttpServletRequest request,HttpServletResponse response, int stu_id) throws Exception  {
            Student student = studentService.getSingleStudent(stu_id);
            // 将CST类型的时间转换为字符串
            String date = ChangeDate.cst2String(student.getBirthday());
            
            request.setAttribute("date", date);
            request.setAttribute("stu", student);
            return "updateStu";
        }
        
        /**
         * 分页获得学生的记录信息 
         * @param request 请求
         * @param response 响应
         * @param curpage 当前页
         * @return 指定页面的前缀
         * @throws Exception
         */
        @RequestMapping("/getAllStudentWithPage")
        public String getAllStudentWithPage(HttpServletRequest request,HttpServletResponse response,int curpage) throws Exception  {
            // 定义每页记录个数
            int pageSize = 3;
            // 获得总记录个数
            int total = studentService.getStuRows();
            // 创建Page对象
            Page page = new Page(curpage, pageSize, total);
            // 获得总页数
            int totalpage = page.gettotalpage();
            // 得到真实的当前页
            curpage = page.getcurpage();
            // 得到Limit的第一个参数
            int pageStart = page.getStart();
            
            // 将参数存放在map集合中(MyBatis中传递多个参数使用的方法)
            Map<String,Object> map = new HashMap<String,Object>();
            map.put("pageStart", pageStart);
            map.put("pageSize", pageSize);
            
            // 获得查询到的记录集合
            List<Student> stulist = studentService.getAllStudentWithPage(map);
            
            // 将集合,当前页,总页数存放在request中
            request.setAttribute("stulist", stulist);
            request.setAttribute("curpage", curpage);
            request.setAttribute("totalpage", totalpage);
            
            return "allStu";
        }
        
        @RequestMapping("/addStu")
        public String addStu(HttpServletRequest request,HttpServletResponse response,Student stu) throws Exception  {
            boolean flag = studentService.addStu(stu);
            if (flag) {
                return "index";
            }else{
                return null;
            }
            
            
        }
        
        @RequestMapping("/updateStu")
        public void updateStu(HttpServletRequest request,HttpServletResponse response,Student stu) throws Exception  {
            boolean flag = studentService.updateStu(stu);
            if (flag) {
                writeToRes(response, "1");
            }else{
                writeToRes(response, "0");
            }
        }
    
    }

    工具类

      ChangeDate.java

    package com.sysystem.model.util;
    
    import java.text.DateFormat;
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.Locale;
    
    public class ChangeDate { 
        /**
         * 将java.util包下的Date对象转为java.sql包下的date
         * @param date java.util.Date
         * @return java.sql.Date
         */
        public static java.sql.Date utilDateToSqlDate(Date date) {
            // 获取了毫秒值ֵ
            long millisTime = date.getTime();
            // 根据毫秒值来获取java.sql包下的Date对象
            java.sql.Date pubTime = new java.sql.Date(millisTime);
            return pubTime;
        }
        
        /**
         * 将字符串转换成Date类型
         * @param time String类型的时间字符串
         * @return Date
         */
        public static Date strDate(String time) {
            Date date = null;
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            try {
                date = df.parse(time);
            } catch (ParseException e) {
                System.out.println("日期格式输入不正确 ");
            }
            return date;
        }
        
        /**
         * 将CST格式的日期转换为String字符串
         * @param date 日期
         * @return 字符串
         */
        public static String cst2String(Date date){
            String datestr = date.toString();
            SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US);  
            Date d =null;
            try {
                d = sdf.parse(datestr);
            } catch (ParseException e) {
                e.printStackTrace();
            }  
            String formatDate = new SimpleDateFormat("yyyy-MM-dd").format(d);
            
            return formatDate;
        }
        
        
    }

      Page.java  进行分页的方法

    package com.sysystem.model.util;
    
    public class Page {
        // 当前页
        private int curpage;
        // 每页记录个数
        private int pageSize;
        // 总记录数
        private int total;
    
        public Page(int curpage, int pageSize, int total) {
            this.curpage = curpage;
            this.pageSize = pageSize;
            this.total = total;
        }
    
        public Page() {
    
        }
    
        /**
         * 获得总页数的方法
         * 
         * @return 总页数
         */
        public int gettotalpage() {
            int totalpage = 0;
            // 记录总页数分别对每页记录个数进行除法和取余
            int m = total / pageSize;
            int n = total % pageSize;
            // 当结果存在余数时则进行+1
            totalpage = (n == 0) ? m : m + 1;
    
            return totalpage;
        }
    
        /**
         * 获得当前页的方法
         * 
         * @return 当前页
         */
        public int getcurpage() {
            // 获得总页数
            int totalpage = gettotalpage();
            // 当当前页小于1时重置为1
            if (curpage < 1) {
                curpage = 1;
            }
            // 当当前页大于总页数时重置为总页数
            if (curpage > totalpage) {
                curpage = totalpage;
            }
            return curpage;
        }
    
        /**
         * 获得LIMIT的第一个参数的方法
         * 
         * @return 返回第一个参数
         */
        public int getStart() {
            // 获得总页数
            int curpage = getcurpage();
            int pageStart = (curpage - 1) * pageSize;
            return pageStart;
        }
    
    }

    allStu.jsp

    <body>
          <h1 align="center" >学生信息表</h1>
        <table width="100%" height="30%" border="1" >
            <tr>
                <td>学生姓名</td>
                <td>年龄</td>
                <td>性别</td>
                <td>学校</td>
                <td>项目名</td>
                <td>代码量</td>
            </tr>
            <c:forEach var="stu" items="${stulist }">
                <tr>
                    <td>${stu.stu_name }</td>
                    <td>${stu.age }</td>
                    <td>${stu.sex }</td>
                    <td>${stu.school }</td>
                    <td>${stu.pro_name }</td>
                    <td>${stu.code }</td>
                </tr>
            </c:forEach>
        </table>
        <a href="<%=path %>/student/getAllStudentWithPage.do?curpage=1">首页</a>
        <a href="<%=path %>/student/getAllStudentWithPage.do?curpage=${curpage-1 }">上一页</a>
        <a href="<%=path %>/student/getAllStudentWithPage.do?curpage=${curpage+1 }">下一页</a>
        <a href="<%=path %>/student/getAllStudentWithPage.do?curpage=${totalpage }">尾页</a>
      </body>

    在浏览器地址栏输入:

    http://localhost:8080/studentManager/student/getAllStudentWithPage.do?curpage=0

  • 相关阅读:
    BestCoder Round #65 hdu5590(水题)
    codeforces Ebony and Ivory(水题)
    codeforces 630B Moore's Law
    BestCoder Round #69 (div.2)(hdu5611)
    BestCoder Round #73 (div.2)(hdu 5630)
    codeforces 630A Again Twenty Five!
    codeforces 630C Lucky Numbers
    codeforces 630D Hexagons!
    Codeforces243C-Colorado Potato Beetle(离散化+bfs)
    hdu4453-Looploop(伸展树)
  • 原文地址:https://www.cnblogs.com/ghq120/p/8596586.html
Copyright © 2011-2022 走看看