crud springmvc

时间:2021-08-25 18:07:14

实体类:Student.java

  1. package demo.entity;
  2. public class Student
  3. {
  4. private int id;
  5. private String name;
  6. private String sex;
  7. private String address;
  8. public int getId()
  9. {
  10. return id;
  11. }
  12. public void setId(int id)
  13. {
  14. this.id = id;
  15. }
  16. public String getName()
  17. {
  18. return name;
  19. }
  20. public void setName(String name)
  21. {
  22. this.name = name;
  23. }
  24. public String getSex()
  25. {
  26. return sex;
  27. }
  28. public void setSex(String sex)
  29. {
  30. this.sex = sex;
  31. }
  32. public String getAddress()
  33. {
  34. return address;
  35. }
  36. public void setAddress(String address)
  37. {
  38. this.address = address;
  39. }
  40. }

IStudentDao.java

  1. package demo.dao;
  2. import java.util.List;
  3. import demo.entity.Student;
  4. public interface IStudentDao
  5. {
  6. public void insert(Student stu);
  7. public void delete(int id);
  8. public void update(Student stu);
  9. public List<Student> findAll();
  10. public Student findById(int id);
  11. }

StudentDaoImpl.java

  1. package demo.dao.impl;
  2. import java.util.List;
  3. import java.util.Map;
  4. import javax.annotation.Resource;
  5. import org.springframework.jdbc.core.BeanPropertyRowMapper;
  6. import demo.dao.IStudentDao;
  7. import demo.entity.Student;
  8. public class StudentDaoImpl implements IStudentDao
  9. {
  10. public static final String INSERT = "insert into student(name,sex,address) values(?,?,?)";
  11. public static final String DELETE = "delete from student where id=?";
  12. public static final String UPDATE = "update student set name=?,sex=?,address=? where id=?";
  13. public static final String FINDALL = "select * from student";
  14. public static final String FINDBYID = "select * from student where id=?";
  15. private org.springframework.jdbc.core.simple.SimpleJdbcTemplate simpleJdbcTemplate;
  16. @Resource
  17. public void setSimpleJdbcTemplate(
  18. org.springframework.jdbc.core.simple.SimpleJdbcTemplate simpleJdbcTemplate)
  19. {
  20. this.simpleJdbcTemplate = simpleJdbcTemplate;
  21. }
  22. public void delete(int id)
  23. {
  24. // TODO Auto-generated method stub
  25. this.simpleJdbcTemplate.update(DELETE, id);
  26. }
  27. @SuppressWarnings("deprecation")
  28. public List<Student> findAll()
  29. {
  30. // TODO Auto-generated method stub
  31. List<Student> stuList = this.simpleJdbcTemplate.query(FINDALL,new BeanPropertyRowMapper<Student>(Student.class));
  32. return stuList;
  33. }
  34. public Student findById(int id)
  35. {
  36. // TODO Auto-generated method stub
  37. Map<String, Object> stuMap = this.simpleJdbcTemplate.queryForMap(FINDBYID, id);
  38. Student stu = new Student();
  39. stu.setId(id);
  40. stu.setName(stuMap.get("name").toString());
  41. stu.setSex(stuMap.get("sex").toString());
  42. stu.setAddress(stuMap.get("address").toString());
  43. return stu;
  44. }
  45. public void insert(Student stu)
  46. {
  47. // TODO Auto-generated method stub
  48. this.simpleJdbcTemplate.update(INSERT, stu.getName(),stu.getSex(),stu.getAddress());
  49. }
  50. public void update(Student stu)
  51. {
  52. // TODO Auto-generated method stub
  53. this.simpleJdbcTemplate.update(UPDATE, stu.getName(),stu.getSex(),stu.getAddress(),stu.getId());
  54. }
  55. }

IStudentService.java

  1. package demo.service;
  2. import java.util.List;
  3. import demo.entity.Student;
  4. public interface IStudentService
  5. {
  6. public void insert(Student stu);
  7. public void delete(int id);
  8. public void update(Student stu);
  9. public List<Student> findAll();
  10. public Student findById(int id);
  11. }

StudentServiceImpl.java

  1. package demo.service.impl;
  2. import java.util.List;
  3. import javax.annotation.Resource;
  4. import demo.dao.IStudentDao;
  5. import demo.entity.Student;
  6. import demo.service.IStudentService;
  7. public class StudentServiceImpl implements IStudentService
  8. {
  9. private IStudentDao stuDao;
  10. @Resource
  11. public void setStuDao(IStudentDao stuDao)
  12. {
  13. this.stuDao = stuDao;
  14. }
  15. public void delete(int id)
  16. {
  17. // TODO Auto-generated method stub
  18. stuDao.delete(id);
  19. }
  20. public List<Student> findAll()
  21. {
  22. // TODO Auto-generated method stub
  23. return stuDao.findAll();
  24. }
  25. public Student findById(int id)
  26. {
  27. // TODO Auto-generated method stub
  28. return stuDao.findById(id);
  29. }
  30. public void insert(Student stu)
  31. {
  32. // TODO Auto-generated method stub
  33. stuDao.insert(stu);
  34. }
  35. public void update(Student stu)
  36. {
  37. // TODO Auto-generated method stub
  38. stuDao.update(stu);
  39. }
  40. }

StudentController.java

  1. package demo.controller;
  2. import java.io.UnsupportedEncodingException;
  3. import java.util.List;
  4. import javax.annotation.Resource;
  5. import javax.servlet.http.HttpServletRequest;
  6. import javax.servlet.http.HttpServletResponse;
  7. import org.springframework.stereotype.Controller;
  8. import org.springframework.ui.ModelMap;
  9. import org.springframework.web.bind.annotation.PathVariable;
  10. import org.springframework.web.bind.annotation.RequestMapping;
  11. import org.springframework.web.bind.annotation.RequestMethod;
  12. import org.springframework.web.servlet.ModelAndView;
  13. import demo.entity.Student;
  14. import demo.service.IStudentService;
  15. @Controller
  16. @RequestMapping("/student")
  17. public class StudentController
  18. {
  19. private IStudentService stuService;
  20. @Resource
  21. public void setStuService(IStudentService stuService)
  22. {
  23. this.stuService = stuService;
  24. }
  25. /**
  26. * 全部
  27. */
  28. @RequestMapping(value = "/all", method = RequestMethod.GET)
  29. public ModelAndView findAll(HttpServletRequest request,
  30. HttpServletResponse response, ModelMap modelMap)
  31. {
  32. List<Student> stuList = stuService.findAll();
  33. modelMap.put("stuList", stuList);
  34. return new ModelAndView("allStudent", modelMap);
  35. }
  36. /**
  37. * 删除
  38. */
  39. @RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
  40. public String delete(HttpServletRequest request,
  41. HttpServletResponse response, @PathVariable("id")
  42. int id, ModelMap modelMap)
  43. {
  44. stuService.delete(id);
  45. return "redirect:/student/all.do";
  46. }
  47. /**
  48. * 添加
  49. */
  50. @RequestMapping(value = "/add", method = RequestMethod.POST)
  51. public String addStudent(HttpServletRequest request,
  52. HttpServletResponse response, Student stu)
  53. throws UnsupportedEncodingException
  54. {
  55. stuService.insert(stu);
  56. return "redirect:/student/all.do";
  57. }
  58. /**
  59. * pre4Update
  60. */
  61. @RequestMapping("/pre4Update/{id}")
  62. public ModelAndView pre4Update(HttpServletRequest request,
  63. HttpServletResponse response, @PathVariable("id")
  64. int id, ModelMap modelMap)
  65. {
  66. Student stu = stuService.findById(id);
  67. modelMap.put("stu", stu);
  68. return new ModelAndView("updateStudent", modelMap);
  69. }
  70. /**
  71. * updateStudent
  72. */
  73. @RequestMapping("/updateStudent")
  74. public String updateStudent(HttpServletRequest request,
  75. HttpServletResponse response, Student stu)
  76. {
  77. stuService.update(stu);
  78. return "redirect:/student/all.do";
  79. }
  80. /**
  81. * 跳转:用于跳转的过度
  82. */
  83. @RequestMapping(value = "/redir/{url}", method = RequestMethod.GET)
  84. public String sendRedirect(HttpServletRequest request,
  85. HttpServletResponse response, @PathVariable("url")
  86. String url)
  87. {
  88. return url;
  89. }
  90. }

================================================ 
配置文件: 
jdbc.properties

  1. jdbc.driverClassName=com.mysql.jdbc.Driver
  2. jdbc.url=jdbc:mysql://localhost:3306/demo?characterEncoding=utf-8
  3. jdbc.username=root
  4. jdbc.password=root

servlet.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:mvc="http://www.springframework.org/schema/mvc"
  5. xmlns:context="http://www.springframework.org/schema/context"
  6. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  7. http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
  8. http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
  9. <context:component-scan base-package="demo.controller"></context:component-scan>
  10. <!-- 内部资源视图解析器 (用于支持Servlet、JSP视图解析) -->
  11. <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  12. <property name="prefix" value="/WEB-INF/jsp/"/>
  13. <property name="suffix" value=".jsp"/>
  14. </bean>
  15. <!-- 数据库连接配置文件路径及读取方式 -->
  16. <bean id="propertyConfigurer"
  17. class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
  18. <property name="locations">
  19. <list>
  20. <value>classpath:jdbc.properties</value>
  21. </list>
  22. </property>
  23. </bean>
  24. <!-- 数据库连接池 -->
  25. <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
  26. destroy-method="close">
  27. <property name="driverClassName" value="${jdbc.driverClassName}" />
  28. <property name="url" value="${jdbc.url}" />
  29. <property name="username" value="${jdbc.username}" />
  30. <property name="password" value="${jdbc.password}" />
  31. </bean>
  32. <bean id="simpleJdbcTemplate"
  33. class="org.springframework.jdbc.core.simple.SimpleJdbcTemplate">
  34. <constructor-arg><ref bean="dataSource"/></constructor-arg>
  35. </bean>
  36. <!-- spring JDBC -->
  37. <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
  38. <property name="dataSource" ref="dataSource" />
  39. </bean>
  40. </beans>

applicationContext-dao.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" " http://www.springframework.org/dtd/spring-beans.dtd">
  3. <beans>
  4. <bean id="stuDao" class="demo.dao.impl.StudentDaoImpl">
  5. <property name="simpleJdbcTemplate"
  6. ref="simpleJdbcTemplate" />
  7. </bean>
  8. </beans>

applicationContext-service.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" " http://www.springframework.org/dtd/spring-beans.dtd">
  3. <beans>
  4. <bean id="stuService" class="demo.service.impl.StudentServiceImpl">
  5. <property name="stuDao" ref="stuDao"/>
  6. </bean>
  7. </beans>

web.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
  5. http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  6. <welcome-file-list>
  7. <welcome-file>index.jsp</welcome-file>
  8. </welcome-file-list>
  9. <servlet>
  10. <servlet-name>demo2</servlet-name>
  11. <servlet-class>
  12. org.springframework.web.servlet.DispatcherServlet
  13. </servlet-class>
  14. <init-param>
  15. <param-name>contextConfigLocation</param-name>
  16. <param-value>/WEB-INF/classes/spring/*.xml</param-value>
  17. </init-param>
  18. <load-on-startup>1</load-on-startup>
  19. </servlet>
  20. <servlet-mapping>
  21. <servlet-name>demo2</servlet-name>
  22. <url-pattern>*.do</url-pattern>
  23. </servlet-mapping>
  24. <!-- 处理乱码 -->
  25. <filter>
  26. <filter-name>encodingFilter</filter-name>
  27. <filter-class>
  28. org.springframework.web.filter.CharacterEncodingFilter
  29. </filter-class>
  30. <init-param>
  31. <param-name>encoding</param-name>
  32. <param-value>utf-8</param-value>
  33. </init-param>
  34. <init-param>
  35. <param-name>forceEncoding</param-name>
  36. <param-value>true</param-value>
  37. </init-param>
  38. </filter>
  39. <filter-mapping>
  40. <filter-name>encodingFilter</filter-name>
  41. <url-pattern>/*</url-pattern>
  42. </filter-mapping>
  43. </web-app>

================== 
allStudent.jsp

    1. <%@ page language="java" pageEncoding="utf-8"%>
    2. <%@ taglib uri="http://java.sun.com/jstl/core_rt" prefix="e"%>
    3. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    4. <html>
    5. <head>
    6. <title>Student列表</title>
    7. </head>
    8. <table width="50%" border="1">
    9. <tr>
    10. <td>id</td>
    11. <td>姓名</td>
    12. <td>性别</td>
    13. <td>地址</td>
    14. <td>操作</td>
    15. </tr>
    16. <e:forEach items="${requestScope.stuList}" var="stu">
    17. <tr>
    18. <td>${stu.id}</td>
    19. <td>${stu.name}</td>
    20. <td>${stu.sex}</td>
    21. <td>${stu.address}</td>
    22. <td><a href="pre4Update/${stu.id}.do">修改</a>||<a href="delete/${stu.id}/${stu.name}.do">删除</a></td>
    23. </tr>
    24. </e:forEach>
    25. </table>
    26. <a href="redir/addStudent.do">添加</a>
    27. <body>
    28. </body>
    29. </html>