1. 程式人生 > >SSM中實現CRUD並配置輸出sql語句

SSM中實現CRUD並配置輸出sql語句

場景

前面SSM的專案整合以及分頁等參照

https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/85120936

使用log4j輸出sql語句參照:

https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/85159383

專案目錄結構

 

 

原始碼下載

https://download.csdn.net/download/badao_liumang_qizhi/10867006

 

實現

jsp頁面

listUser.jsp

開啟listUser.jsp,新增編輯以及刪除按鈕,以及新增的表單。

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
 
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<%
 pageContext.setAttribute("APP_PATH", request.getContextPath());
%>
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>查詢所有使用者</title>
</head>

<script type="text/javascript" src="${APP_PATH }/static/js/jquery-1.12.4.min.js"></script>
<link href="${APP_PATH }/static/bootstrap-3.3.7-dist/css/bootstrap.min.css" rel="stylesheet">
<script src="${APP_PATH }/static/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
<body>
<table align='center' border='1' cellspacing='0' class="table table-bordered"
    <th >
        <td>id</td>
        <td>name</td>
        <td>age</td>
        <td>編輯</td>
        <td>刪除</td>
    </th>
    <c:forEach items="${userList}" var="u">
        <tr class="active">
            <td >${u.id}</td>
            <td>${u.name}</td>
            <td>${u.age}</td>
            <td><a href="editUser?id=${u.id}">編輯</a></td>
	        <td><a href="deleteUser?id=${u.id}">刪除</a></td>
        </tr>
    </c:forEach>
</table>
<div style="text-align:center">
        <a href="?start=0">首  頁</a>
        <a href="?start=${page.start-page.count}">上一頁</a>
        <a href="?start=${page.start+page.count}">下一頁</a>
        <a href="?start=${page.last}">末  頁</a>
</div>
<form action="addUser" method="post">
  <div class="form-group">
    <label for="name">使用者名稱</label>
    <input type="text" class="form-control" id="name" name ="name" placeholder="name">
  </div>
  <div class="form-group">
    <label for="age">年齡</label>
    <input type="number" class="form-control" id="age"  name="age" placeholder="age">
  </div>
  <button type="submit" class="btn btn-default">新增使用者</button>
</form>

</body>
</html>

editUser.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" import="java.util.*"%>
 
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
 
 <div style="width:500px;margin:0px auto;text-align:center">
	
	
	<div style="text-align:center;margin-top:40px">
		
		<form method="post" action="updateUser">
			使用者名稱稱: <input name="name" value="${user.name}" type="text"> <br><br>
			使用者年齡: <input name="age" value="${user.age}" type="text"> <br><br>
			<input type="hidden" value="${user.id}" name="id">
			<input type="submit" value="編輯使用者">
		</form>

	</div>	
 </div>

 

點選新增或者編輯或者刪除時都會跳轉到後臺Controller

配置Controller

開啟userController

package com.badao.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.badao.pojo.User;
import com.badao.service.UserService;
import com.badao.util.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;




// 告訴spring mvc這是一個控制器類
@Controller
@RequestMapping("")
public class UserController {
 @Autowired
 UserService userService;

 @RequestMapping("listUser")
 public ModelAndView listUser(Page page){
  ModelAndView mav = new ModelAndView();
  //根據分頁物件,進行查詢獲取查詢物件集合
  //List<User> cs= userService.selectAllUser(page);
  //int total = userService.total();
  //根據總數,計算最後一頁的資訊
  
   PageHelper.offsetPage(page.getStart(),5);
      List<User> cs= userService.selectAllUser();
      int total = (int) new PageInfo<>(cs).getTotal();
      page.caculateLast(total);
  // 放入轉發引數
  mav.addObject("userList", cs);
  // 放入jsp路徑
  mav.setViewName("listUser");
  return mav;
 }
  
 @RequestMapping("addUser")
 public ModelAndView addUser(User user){
  System.out.println(user.getName());
  userService.addUser(user);
  ModelAndView mav = new ModelAndView("redirect:/listUser");
     return mav;
 } 
 @RequestMapping("deleteUser")
 public ModelAndView deleteUser(int id){
  userService.deleteUser(id);
  ModelAndView mav = new ModelAndView("redirect:/listUser");
  return mav;
 } 
 @RequestMapping("editUser")
 public ModelAndView editUser(User user){
     user= userService.selectUser(user.getId());
  ModelAndView mav = new ModelAndView("editUser");
  mav.addObject("user", user);
  return mav;
 } 
 @RequestMapping("updateUser")
 public ModelAndView updateUser(User user){
  userService.updateUser(user);
  ModelAndView mav = new ModelAndView("redirect:/listUser");
  return mav;
 } 

}

controller呼叫service方法

配置service

package com.badao.service;

import java.util.List;

import com.badao.pojo.User;
import com.badao.util.Page;

public interface UserService {
 List<User> selectAllUser();

 User selectUser(Integer id);

 void updateUser(User user);

 void deleteUser(int id);

 void addUser(User user);
 
 //List<User> selectAllUser(Page page);
 //int total();

}

配置serviceImpl

package com.badao.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.badao.mapper.UserMapper;
import com.badao.pojo.User;
import com.badao.service.UserService;
import com.badao.util.Page;
@Service
public class UserServiceImpl implements UserService {

 @Autowired
 UserMapper userMapper;
 public List<User> selectAllUser() {
  // TODO Auto-generated method stub
  return userMapper.selectAllUser();
 }
/* @Override
 public List<User> selectAllUser(Page page) {
  // TODO Auto-generated method stub
  return userMapper.selectAllUser(page);
 }
 @Override
 public int total() {
  // TODO Auto-generated method stub
  return userMapper.total();
 }*/
 @Override
 public User selectUser(Integer id) {
  // TODO Auto-generated method stub
  return userMapper.selectUser(id);
 }
 @Override
 public void updateUser(User user) {
  // TODO Auto-generated method stub
      userMapper.updateUser(user);
 }
 @Override
 public void deleteUser(int id) {
  // TODO Auto-generated method stub
  userMapper.deleteUser(id);
 }
 @Override
 public void addUser(User user) {
  // TODO Auto-generated method stub
  userMapper.addUser(user);
 }

}

配置mapper

開啟mapper下的usermapper.java

package com.badao.mapper;

import java.util.List;
import com.badao.pojo.User;
import com.badao.util.Page;



public interface UserMapper {
 public int addUser(User user);
 public User selectUser(int id);
 public int updateUser(User user);
 public void deleteUser(int id);
 public List<User> selectAllUser();
 //public List<User> selectAllUser(Page page);
 //public int total();
 
}

開啟mapper下的usermapper.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.badao.mapper.UserMapper">
        <insert id="addUser" parameterType="User" >
            insert into user ( name,age ) values (#{name},#{age})  
        </insert>
        
        <delete id="deleteUser" parameterType="_int" >
            delete from user where id= #{id} 
        </delete>
        
        <select id="selectUser" parameterType="_int" resultType="User">
            select * from   user  where id= #{id}  
        </select>
 
        <update id="updateUser" parameterType="User" >
            updateusersetname=#{name},age=#{age} where id=#{id}  
        </update>
        <select id="selectAllUser" resultType="User">
            select * from   user    
           <!--<iftest="start!=null and count!=null">
             limit #{start},#{count}
            </if> -->
        </select>
        <!-- <select id="total" resultType="int">
         select count(*) from user
        </select>     -->
    </mapper>

配置POJO

package com.badao.pojo;


public class User {
 private Integer id;
 private String name;
 private Integer age;
 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 Integer getAge() {
  return age;
 }
 public void setAge(Integer age) {
  this.age = age;
 }


}

配置web.xml

加入編碼過濾器

<filter>
     <filter-name>encodingFilter</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>encodingFilter</filter-name>
     <url-pattern>/*</url-pattern>
 </filter-mapping>

完整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"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
 <filter>
     <filter-name>encodingFilter</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>encodingFilter</filter-name>
     <url-pattern>/*</url-pattern>
 </filter-mapping>
 <!-- spring的配置檔案-->
 <context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>classpath:applicationContext.xml</param-value>
 </context-param>
 <listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
 </listener>
 
 
 <!-- spring mvc核心:分發servlet -->
 <servlet>
  <servlet-name>mvc-dispatcher</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <!-- spring mvc的配置檔案 -->
  <init-param>
   <param-name>contextConfigLocation</param-name>
   <param-value>classpath:springMVC.xml</param-value>
  </init-param>
  <load-on-startup>1</load-on-startup>
 </servlet>
 <servlet-mapping>
  <servlet-name>mvc-dispatcher</servlet-name>
  <url-pattern>/</url-pattern>
 </servlet-mapping>
 
</web-app>

 

執行

將原始碼下載下來,或者自己搭建專案,部署到Tomcat嗎,啟動伺服器。

開啟瀏覽器輸入:

http://localhost:8080/ssmJarTemplate/listUser

效果