IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> Java知识库 -> SpringBoot整合Jsp项目 -> 正文阅读

[Java知识库]SpringBoot整合Jsp项目

springboot-jsp
│  pom.xml
│
├─src
│  └─main
│      ├─java
│      │  └─pers
│      │      └─ziv
│      │          └─demo
│      │              │  DemoApplication.java
│      │              │
│      │              ├─controller
│      │              │      DemoController.java
│      │              │
│      │              ├─dao
│      │              │      DemoRepository.java
│      │              │
│      │              ├─dto
│      │              │      SelectResultDto.java
│      │              │      UserDto.java
│      │              │
│      │              ├─entity
│      │              │      UserEntity.java
│      │              │
│      │              ├─from
│      │              │      UserForm.java
│      │              │
│      │              └─service
│      │                      DemoService.java
│      │
│      ├─resources
│      │  │  application.yml
│      │  │
│      │  └─mapping
│      │          UserRepostry.xml
│      │
│      └─webapp
│          └─WEB-INF
│              └─templates
│                      index.jsp

配置文件

application.yml

spring:
  mvc:
    view:
      prefix: /WEB-INF/templates/
      suffix: .jsp
  datasource:
    username: root
    password: 123456
    url: jdbc:mysql://192.168.136.134:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
    driver-class-name: com.mysql.jdbc.Driver
mybatis:
  mapper-locations: classpath:mapping/*.xml


logging:
  level:
    pers: debug

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://maven.apache.org/POM/4.0.0"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>pers.ziv</groupId>
    <artifactId>jsp</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.11</version>
        <relativePath/>
    </parent>

    <dependencies><dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>
        <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>1.3.2</version>
        </dependency>
        <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
        </dependency>
    </dependencies>

</project>

启动类

DemoApplication

package pers.ziv.demo;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * Description: 启动入口
 */
@SpringBootApplication
@MapperScan("pers.ziv.demo.dao")
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

}

Controller

DemoController

package pers.ziv.demo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import pers.ziv.demo.dto.SelectResultDto;
import pers.ziv.demo.dto.UserDto;
import pers.ziv.demo.entity.UserEntity;
import pers.ziv.demo.from.UserForm;
import pers.ziv.demo.service.DemoService;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;


@Controller
public class DemoController {
    @Autowired
    private DemoService demoService;

    @RequestMapping("index")
    public ModelAndView index(@ModelAttribute("userForm") UserForm userForm) {
        ModelAndView model = new ModelAndView("index");

        model.addObject("userNameList", demoService.getUserNames());
        return model;
    }

    @RequestMapping("index2")
    public ModelAndView index2(@ModelAttribute("userForm") UserForm userForm) {
        ModelAndView model = new ModelAndView("index");

        List<UserEntity> userNames = demoService.getUserNames2();

        Set<String> userNameList = new HashSet<>();
        Set<String> fatherNameList = new HashSet<>();

        for (UserEntity userName : userNames) {
            userNameList.add(userName.getUserName());
            fatherNameList.add(userName.getFatherName());
        }

        model.addObject("userNameList", userNameList);
        model.addObject("fatherNameList", fatherNameList);
        return model;
    }

    @RequestMapping("/selectResultForUserName")
    @ResponseBody
    public List<SelectResultDto> selectResultForUserName(@ModelAttribute("userForm") UserForm userForm, Model model) {
        // FORM -> DTO
        UserDto userDto = new UserDto();
        userDto.setUserName(userForm.getUserName());
        userDto.setFatherName(userForm.getFatherName());

        // 执行Service
        return demoService.selectResultForUserName(userDto);
    }
}

Mapper

DemoRepository

package pers.ziv.demo.dao;

import org.springframework.stereotype.Repository;
import pers.ziv.demo.dto.UserDto;
import pers.ziv.demo.entity.UserEntity;

import java.util.List;

@Repository
public interface DemoRepository {
    List<String> getUserNames();
    List<UserEntity> getUserNames2();
    List<UserEntity> selectResultForUserName(UserDto userDto);
}

UserRepostry.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="pers.ziv.demo.dao.DemoRepository">

    <resultMap id="userResultMap" type="pers.ziv.demo.entity.UserEntity">
        <result column="USERID" jdbcType="INTEGER" property="userId"/>
        <result column="USERNAME" jdbcType="VARCHAR" property="userName"/>
        <result column="USERAGE" jdbcType="INTEGER" property="userAge"/>
        <result column="USERTEL" jdbcType="VARCHAR" property="userTel"/>
        <result column="FATHERID" jdbcType="INTEGER" property="fatherId"/>
        <result column="FATHERNAME" jdbcType="VARCHAR" property="fatherName"/>
    </resultMap>

    <select id="getUserNames" resultType="java.lang.String">
        SELECT NAME FROM USER
    </select>
    <select id="getUserNames2" resultType="pers.ziv.demo.entity.UserEntity">
        SELECT
          USER.NAME AS USERNAME
         ,FATHER.NAME AS FATHERNAME
         FROM USER INNER JOIN FATHER ON USER.NAME = FATHER.USERNAME
    </select>
    <select id="selectResultForUserName" parameterType="pers.ziv.demo.dto.UserDto" resultMap="userResultMap">
        SELECT USER.NAME AS USERNAME
        , USER.ID AS USERID
        , USER.AGE AS USERAGE
        , USER.TEL AS USERTEL
        , FATHER.NAME AS FATHERNAME
        , FATHER.ID AS FATHERID
        FROM USER INNER JOIN FATHER ON USER.NAME = FATHER.USERNAME
        WHERE USER.NAME = #{username}
        <where>
            <if test="userName != null">
                AND USER.NAME = #{userName}
            </if>
            <if test="fatherName != null">
                AND FATHER.NAME = #{fatherName}
            </if>
        </where>
    </select>
</mapper>

DTO

UserDto

package pers.ziv.demo.from;

public class UserForm {
    private String userName;
    private String fatherName;

    public String getFatherName() {
        return fatherName;
    }

    public void setFatherName(String fatherName) {
        this.fatherName = fatherName;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }
}

SelectResultDto

package pers.ziv.demo.dto;

public class SelectResultDto {
    private String userName;
    private Integer userAge;
    private String userTel;
    private String fatherName;

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public Integer getUserAge() {
        return userAge;
    }

    public void setUserAge(Integer userAge) {
        this.userAge = userAge;
    }

    public String getUserTel() {
        return userTel;
    }

    public void setUserTel(String userTel) {
        this.userTel = userTel;
    }

    public String getFatherName() {
        return fatherName;
    }

    public void setFatherName(String fatherName) {
        this.fatherName = fatherName;
    }
}

Entity

UserEntity

package pers.ziv.demo.entity;

public class UserEntity {
    private Integer userId;
    private String userName;
    private Integer userAge;
    private String userTel;
    private Integer fatherId;
    private String fatherName;

    public Integer getUserId() {
        return userId;
    }

    public void setUserId(Integer userId) {
        this.userId = userId;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public Integer getUserAge() {
        return userAge;
    }

    public void setUserAge(Integer userAge) {
        this.userAge = userAge;
    }

    public String getUserTel() {
        return userTel;
    }

    public void setUserTel(String userTel) {
        this.userTel = userTel;
    }

    public Integer getFatherId() {
        return fatherId;
    }

    public void setFatherId(Integer fatherId) {
        this.fatherId = fatherId;
    }

    public String getFatherName() {
        return fatherName;
    }

    public void setFatherName(String fatherName) {
        this.fatherName = fatherName;
    }
}

From

UserForm

package pers.ziv.demo.from;

public class UserForm {
    private String userName;
    private String fatherName;

    public String getFatherName() {
        return fatherName;
    }

    public void setFatherName(String fatherName) {
        this.fatherName = fatherName;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }
}

Service

DemoService

package pers.ziv.demo.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import pers.ziv.demo.dao.DemoRepository;
import pers.ziv.demo.dto.SelectResultDto;
import pers.ziv.demo.dto.UserDto;
import pers.ziv.demo.entity.UserEntity;

import java.util.ArrayList;
import java.util.List;

@Service
public class DemoService {
    @Autowired
    private DemoRepository demoRepository;

    public List<String> getUserNames() {
        List<String> nameList = demoRepository.getUserNames();
        return nameList;
    }

    public List<UserEntity> getUserNames2() {
        List<UserEntity> nameList = demoRepository.getUserNames2();
        return nameList;
    }

    public List<SelectResultDto> selectResultForUserName(UserDto userDto) {
        // DTO -> Entity
        List<UserEntity> selectResultEntitys = demoRepository.selectResultForUserName(userDto);
        return getSelectResult(selectResultEntitys);
    }

    private List<SelectResultDto> getSelectResult(List<UserEntity> selectResultEntitys) {
        List<SelectResultDto> result = new ArrayList<>();
        selectResultEntitys.forEach(entity -> {
            SelectResultDto dto = new SelectResultDto();
            dto.setFatherName(entity.getFatherName());
            dto.setUserTel(entity.getUserTel());
            dto.setUserAge(entity.getUserAge());
            dto.setUserName(entity.getUserName());
            result.add(dto);
        });
        return result;
    }
}

JSP

index.jsp

<%@ page pageEncoding="UTF-8" %>
<%@ page contentType="text/html;charset=UTF-8" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<html>
<head>
    <title>jsp</title>
</head>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
<script src="https://unpkg.com/@ag-grid-community/all-modules@26.0.0/dist/ag-grid-community.min.js"></script>
<body style="text-align: center;line-height: 30px">
<form:form modelAttribute="userForm">
<div>
    <div>
        <label>学生姓名:</label>
        <form:select path="userName" items="${userNameList}"></form:select>
    </div>
    <div>
        <label>老爸姓名:</label>
        <form:select path="fatherName" items="${fatherNameList}"></form:select>
    </div>
    <div>
        <input id="selectResult" type="button" value="检索"/>
    </div>
    </form:form>
    <div id="myGrid"></div>
</body>
</html>
<style>
    #myGrid {
        flex: 1 1 0px;
        width: 800px;
        height: 8000px;
    }
</style>
<script>
    var gridOptions = {
        columnDefs: [
            {
                headerName: 'select',
                field: 'select',
                minWidth: 180,
                headerCheckboxSelection: true,
                headerCheckboxSelectionFilteredOnly: true,
                checkboxSelection: true,
            },
            {field: 'userName', minWidth: 15},
            {field: 'userAge', minWidth: 15},
            {field: 'userTel', minWidth: 15},
            {field: 'fatherName', minWidth: 15},
        ],
        defaultColDef: {
            flex: 1,
            minWidth: 25,
            resizable: true,
        },
        suppressRowClickSelection: true,
        rowSelection: 'multiple',
    };
    document.addEventListener('DOMContentLoaded', function () {
        var gridDiv = document.querySelector('#myGrid');
        new agGrid.Grid(gridDiv, gridOptions);
    });
    /**
     * ajax Result Data to Ag-grid
     */
    var resultDate = {};
    /**
     * 检索按下后的场合
     */
    $(document).ready(function () {
        // 检索按钮点击事件
        $("#selectResult").click(function () {
            // 给后端发送请求 url:/selectResultForUserName 数据:"name": $("#name").val()
            htmlobj = $.ajax({
                    url: "/selectResultForUserName"
                    , async: false
                    , data: {
                        "userName": $("#userName").val(),
                        "fatherName": $("#fatherName").val()
                    }
                    /* 请求后成功的场合 */
                    , success: function (result) {
                        resultDate = result;
                        if (resultDate.length > 0) {
                            gridOptions.api.setRowData(resultDate);
                        } else {
                            gridOptions.api.setRowData({});
                        }
                    }
                    /* 请求后失败的场合 */
                    , error: function (data) {
                        gridOptions.api.setRowData({});
                        alert("出错了!");
                    }
                }
            )
        });
    });

</script>
  Java知识库 最新文章
计算距离春节还有多长时间
系统开发系列 之WebService(spring框架+ma
springBoot+Cache(自定义有效时间配置)
SpringBoot整合mybatis实现增删改查、分页查
spring教程
SpringBoot+Vue实现美食交流网站的设计与实
虚拟机内存结构以及虚拟机中销毁和新建对象
SpringMVC---原理
小李同学: Java如何按多个字段分组
打印票据--java
上一篇文章      下一篇文章      查看所有文章
加:2021-09-26 10:01:22  更:2021-09-26 10:04:08 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年4日历 -2024/4/26 11:15:19-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码