大数据正式34

大数据正式34

Spring+SpringMVC 小例子

  • 效果图
  • 功能说明
    • 利用Spring作为整体的架子,简化代码,用配置文件来解耦合
    • 利用SpringMVC简化经典三层架构,用配置文件和注解来简化
    • 这是一个展示数据库列表的demo(展示:与数据库有关;删除:Jquery写的,与数据库无关)

jar包

数据库

  • 数据库名
    • springmvc_db
  • 表名
    • user
  • 表结构
  • 表数据

项目结构

代码

  • com.peng.controller

    • UserController

      package com.peng.controller;
      
      import java.sql.Date;
      import java.text.SimpleDateFormat;
      import java.util.List;
      
      import org.springframework.beans.factory.annotation.Autowired;
      import org.springframework.beans.factory.annotation.Qualifier;
      import org.springframework.beans.propertyeditors.CustomDateEditor;
      import org.springframework.stereotype.Controller;
      import org.springframework.ui.Model;
      import org.springframework.web.bind.ServletRequestDataBinder;
      import org.springframework.web.bind.annotation.InitBinder;
      import org.springframework.web.bind.annotation.RequestMapping;
      
      import com.peng.pojo.User;
      import com.peng.service.UserService;
      
      @Controller
      public class UserController {
      
          // 注入service层对象
          @Autowired
          @Qualifier(value = "userService")
          private UserService userService;
      
          // 展示所有的用户
          @RequestMapping("showUsers.action")
          public String showUsers(Model model) {
              // 获得所有的用户
              List<User> user_list = userService.selectUsers();
              // 将所有的在用户封装在列表中
              model.addAttribute("user_list", user_list);
              return "users";
          }
      
          // 时间格式问题
          @InitBinder
          public void InitBinder(ServletRequestDataBinder srdb) {
              srdb.registerCustomEditor(Date.class, new CustomDateEditor(
                      new SimpleDateFormat("yyyy-MM-dd"), true));
          }
      }
      
  • com.peng.dao

    • UserDao

      package com.peng.controller;
      
      import java.sql.Date;
      import java.text.SimpleDateFormat;
      import java.util.List;
      
      import org.springframework.beans.factory.annotation.Autowired;
      import org.springframework.beans.factory.annotation.Qualifier;
      import org.springframework.beans.propertyeditors.CustomDateEditor;
      import org.springframework.stereotype.Controller;
      import org.springframework.ui.Model;
      import org.springframework.web.bind.ServletRequestDataBinder;
      import org.springframework.web.bind.annotation.InitBinder;
      import org.springframework.web.bind.annotation.RequestMapping;
      
      import com.peng.pojo.User;
      import com.peng.service.UserService;
      
      @Controller
      public class UserController {
      
          // 注入service层对象
          @Autowired
          @Qualifier(value = "userService")
          private UserService userService;
      
          // 展示所有的用户
          @RequestMapping("showUsers.action")
          public String showUsers(Model model) {
              // 获得所有的用户
              List<User> user_list = userService.selectUsers();
              // 将所有的在用户封装在列表中
              model.addAttribute("user_list", user_list);
              return "users";
          }
      
          // 时间格式问题
          @InitBinder
          public void InitBinder(ServletRequestDataBinder srdb) {
              srdb.registerCustomEditor(Date.class, new CustomDateEditor(
                      new SimpleDateFormat("yyyy-MM-dd"), true));
          }
      }
      
    • UserDaoImpl

      package com.peng.dao;
      
      import java.sql.ResultSet;
      import java.sql.SQLException;
      import java.util.List;
      
      import org.springframework.beans.factory.annotation.Autowired;
      import org.springframework.beans.factory.annotation.Qualifier;
      import org.springframework.jdbc.core.JdbcTemplate;
      import org.springframework.jdbc.core.RowMapper;
      import org.springframework.stereotype.Repository;
      
      import com.peng.pojo.User;
      
      @Repository(value = "userDao")
      public class UserDaoImpl implements UserDao {
          // 注入jdbcTemplate模板
          @Autowired
          @Qualifier(value = "db_template")
          private JdbcTemplate jdbcTemple;
      
          public List<User> selectUsers() {
              RowMapper<User> rm = new RowMapper<User>() {
      
                  public User mapRow(ResultSet rs, int rowNum) throws SQLException {
                      User user = new User();
                      user.setId(rs.getString("id"));
                      user.setName(rs.getString("name"));
                      user.setEmial(rs.getString("email"));
                      user.setMoney(rs.getString("money"));
                      return user;
                  }
              };
              List<User> list_users = jdbcTemple.query("select * from user", rm);
              return list_users;
          }
      }
      
  • com.peng.pojo

    • User

      package com.peng.pojo;
      
      public class User {
          private String id;
          private String name;
          private String email;
          private String money;
      
          public User() {
              super();
          }
      
          public User(String id, String name, String emial, String money) {
              super();
              this.id = id;
              this.name = name;
              this.email = emial;
              this.money = money;
          }
      
          public String getId() {
              return id;
          }
      
          public void setId(String id) {
              this.id = id;
          }
      
          public String getName() {
              return name;
          }
      
          public void setName(String name) {
              this.name = name;
          }
      
          public String getEmial() {
              return email;
          }
      
          public void setEmial(String emial) {
              this.email = emial;
          }
      
          public String getMoney() {
              return money;
          }
      
          public void setMoney(String money) {
              this.money = money;
          }
      
      }
      
  • com.peng.service

    • UserService

      package com.peng.service;
      
      import java.util.List;
      
      import com.peng.pojo.User;
      
      public interface UserService {
          /**
           * 查询所有的用户
           * 
           * @return
           */
          List<User> selectUsers();
      
      }
      
    • UserServiceImpl

      package com.peng.service;
      
      import java.util.List;
      
      import com.peng.pojo.User;
      
      public interface UserService {
          /**
           * 查询所有的用户
           * 
           * @return
           */
          List<User> selectUsers();
      
      }
      
  • 配置文件

    • applicationContext.xml

      <?xml version="1.0" encoding="UTF-8"?>
      <beans xmlns="http://www.springframework.org/schema/beans"
          xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
          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.2.xsd
          http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd 
          http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd 
           ">
          <!-- 包扫描器 -->
          <context:component-scan base-package="com.peng"></context:component-scan>
          <!-- springMVC的扫描器 -->
          <mvc:annotation-driven></mvc:annotation-driven>
      
          <!-- 资源解析器:前后缀 -->
          <bean
              class="org.springframework.web.servlet.view.InternalResourceViewResolver">
              <property name="prefix" value="/WEB-INF/">
              </property>
              <property name="suffix" value=".jsp"></property>
          </bean>
          <!-- 文件上传资源解析器 -->
          <bean id="multipartResolver"
              class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
              <property name="defaultEncoding" value="utf-8"></property>
              <property name="maxUploadSize" value="10485760000"></property>
              <property name="maxInMemorySize" value="40960"></property>
          </bean>
      
          <!-- 数据库的配置文件 -->
          <bean
              class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
              <property name="location" value="classpath:/db_config.properties"></property>
          </bean>
          <!-- c3p0配置 -->
          <bean id="c3p0_datasource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
              <property name="user" value="${jdbc.username}"></property>
              <property name="password" value="${jdbc.password}"></property>
              <property name="jdbcUrl" value="${jdbc.url}"></property>
              <property name="driverClass" value="${jdbc.driver}"></property>
              <property name="minPoolSize" value="3"></property>      <!--最小连接数 -->
              <property name="initialPoolSize" value="5"></property>  <!-- 初始化连接数 -->
              <property name="acquireIncrement" value="3"></property> <!-- 每次增长的个数 -->
          </bean>
          <!-- 数据库模板 -->
          <bean id="db_template" class="org.springframework.jdbc.core.JdbcTemplate">
              <property name="dataSource" ref="c3p0_datasource"></property>
          </bean>
      </beans>
      
    • db_config.properties

      jdbc.username=root
      jdbc.password=root
      jdbc.url=jdbc:mysql://localhost:3306/springmvc_db
      jdbc.driver=com.mysql.jdbc.Driver
      
    • jquery-1.4.2.js

    • user.jsp

      <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
      <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
      <!DOCTYPE HTML>
      <html>
      <head>
      <title>用户管理</title>
      <meta http-equiv="content-type" content="text/html; charset=UTF-8">
      <style type="text/css">
      body {
          font-family: "微软雅黑"
      }
      
      h2,h4 {
          text-align: center;
      }
      
      div#box1,div#box2 {
          text-align: center;
      }
      
      hr {
          margin: 20px 0;
      }
      
      table {
          margin: 0 auto;
          width: 70%;
          text-align: center;
          border-collapse: collapse;
      }
      
      td,th {
          padding: 7px;
          width: 20%;
      }
      
      th {
          background-color: #DCDCDC;
      }
      </style>
      
      <!--引入jquery的js库-->
      <script src="js/jquery-1.4.2.js"></script>
      <script type="text/javascript">
          $(function() {
              $("#add").click(
                      function() {
                          //获取输入信息
                          var id = $("#box1 input[name='id']").val().trim();
                          var name = $("#box1 input[name='name']").val().trim();
                          var email = $("#box1 input[name='email']").val().trim();
                          var salary = $("#box1 input[name='salary']").val().trim();
                          //校验
                          if (id == "" || name == "" || email == "" || salary == "") {
                              alert("员工信息不能为空");
                              return;
                          }
                          //员工id不能重复
                          var flag = false;
                          $("table tr").each(function() {
                              if ($(this).find("td:eq(1)").text() == id) {
                                  alert("ID已存在");
                                  flag = true;
                                  return false;
                              }
                          });
                          if (flag) {
                              return;
                          }
                          //将员工信息添加到列表中
                          var $tab = $("table");
                          var $tr = $("<tr></tr>");
                          var $td0 = $("<td><input type='checkbox'/></td>");
                          var $td1 = $("<td>" + id + "</td>");
                          var $td2 = $("<td>" + name + "</td>");
                          var $td3 = $("<td>" + email + "</td>");
                          var $td4 = $("<td>" + salary + "</td>");
                          $tr.append($td0).append($td1).append($td2).append($td3)
                                  .append($td4);
                          $tab.append($tr);
      
                      });
              //全选按钮
              $("#all").click(function() {
                  //获取全选状态
                  var check = $(this).attr("checked");
                  //将其他复选框状态与全选一致
                  $("table input").attr("checked", check);
              });
              //删除
              $("#del").click(function() {
                  $("input:checked:not(input[id='all'])").parents("tr").remove();
              });
              //修改
              $("#upd").click(function() {
                  //获取修改信息
                  var id = $("#box2 input[name='id']").val().trim();
                  var name = $("#box2 input[name='name']").val().trim();
                  var email = $("#box2 input[name='email']").val().trim();
                  var salary = $("#box2 input[name='salary']").val().trim();
      
                  //校验
                  if (id == "" || name == "" || email == "" || salary == "") {
                      alert("修改信息不能为空");
                      return;
                  }
                  //根据ID进行修改 
                  var flag = true;
                  $("table tr").each(function() {
                      if ($(this).find("td:eq(1)").text() == id) {
                          //进行修改
                          flag = false;
                          $(this).find("td:eq(2)").text(name);
                          $(this).find("td:eq(3)").text(email);
                          $(this).find("td:eq(4)").text(salary);
                          return false;
      
                      }
                  });
                  if (flag) {
                      alert("员工id不存在!");
                  }
      
              });
      
          });
      </script>
      </head>
      
      <body>
          <h2>=添加新员工</h2>
          <div id="box1">
              ID:<input type="text" name="id" /> 姓名:<input type="text" name="name" />
              邮箱:<input type="text" name="email" /> 工资:<input type="text"
                  name="salary" /> <input type="button" id="add" value="添加" />
          </div>
          <hr />
          <table border="1">
              <tr>
                  <th><input type="checkbox" id="all" /> <!--全选--></th>
                  <th>ID</th>
                  <th>姓名</th>
                  <th>邮箱</th>
                  <th>工资</th>
              </tr>
              <c:forEach items="${user_list}" var="item">
                  <tr>
                      <td><input type="checkbox" /></td>
                      <td>${item.id}</td>
                      <td>${item.name}</td>
                      <td>${item.emial}</td>
                      <td>${item.money}</td>
                  </tr>
              </c:forEach>
      
          </table>
          <p align="center">
              <a href="#" id="del">删除选中</a>
          </p>
      
          <hr />
          <div id="box2">
              ID:<input type="text" name="id" /> 姓名:<input type="text" name="name" />
              邮箱:<input type="text" name="email" /> 工资:<input type="text"
                  name="salary" /> <input type="button" id="upd" value="修改" />
          </div>
      </body>
      </html>
      
    • 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">
      
          <!-- 解决乱码过滤器(只能解决post的,get的需要手动解决) -->
          <!-- 乱码过滤器 -->
          <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>
              <init-param>
                  <param-name>forceEncoding</param-name>
                  <param-value>true</param-value>
              </init-param>
          </filter>
          <filter-mapping>
              <filter-name>characterFilter</filter-name>
              <url-pattern>/*</url-pattern>
          </filter-mapping>
          <!-- 分发器 -->
          <servlet>
              <servlet-name>springmvc_dispatcher</servlet-name>
              <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
              <init-param>
                  <param-name>contextConfigLocation</param-name>
                  <param-value>classpath:/applicationContext.xml</param-value>
              </init-param>
          </servlet>
          <!-- 分发器的映射 -->
          <servlet-mapping>
              <servlet-name>springmvc_dispatcher</servlet-name>
              <url-pattern>*.action</url-pattern>
          </servlet-mapping>
          <!-- 欢迎界面 -->
          <welcome-file-list>
              <welcome-file>index.jsp</welcome-file>
          </welcome-file-list>
      </web-app>
      
    • index.jsp

      <%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
      <%
      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>My JSP 'index.jsp' starting page</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">
          <!--
          <link rel="stylesheet" type="text/css" href="styles.css">
          -->
        </head>
      
        <body>
          This is my JSP page. <br>
        </body>
      </html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

乘风御浪云帆之上

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值