0
点赞
收藏
分享

微信扫一扫

基于javaweb+jsp的饮食营养健康管理系统

四月天2021 2022-03-30 阅读 74

JavaWeb JavaBean JSP MVC MySQL Tomcat JavaScript Bootstrap.

基础JSP+Servlet或JSP+SSM(Spring、SpringMVC、MyBatis)框架或JSP+SSM+Maven(pom.xml)框架或SpringBoot…均可

开发工具:eclipse/idea/myeclipse/sts等均可配置运行

适用

课程设计,大作业,毕业设计,项目练习,学习演示等

            vo.setUserSex(Util.decode(request, "userSex"));
            vo.setUserPhone(Util.decode(request, "userPhone"));
            vo.setUserText(Util.decode(request, "userText"));
            vo.setUserType(Util.decode(request, "userType"));
            UserService userService = new UserServiceImpl();
            //调用Service层更新方法(update),更新记录
            userService.update(vo);
            this.redirectList(request, response);
        } else if ("get".equalsIgnoreCase(action) || "editPre".equalsIgnoreCase(action)) {//根据主键ID,查询详情信息并跳转到详情页面或编辑页面
            Serializable id = Util.decode(request, "id");//取出页面传入的主键,用于查询详情
            UserService userService = new UserServiceImpl();
            User vo = userService.get(id);
            request.getSession().setAttribute("vo", vo);
                <td title="${vo.foodText}">
                <c:choose>
                    <c:when test="${fn:length(vo.foodText) > 19}">
                        <c:out value="${fn:substring(vo.foodText, 0, 19)}..."/>
                    </c:when>
                    <c:otherwise>
                        <c:out value="${vo.foodText}"/>
                    </c:otherwise>
                </c:choose>
                </td>
                <td>
                    <button class="btn btn-pill btn-primary btn-sm" style="padding: 0px 1px;" onclick="window.location.href='FoodServlet?action=get&id=${vo.id}'">详情</button>&nbsp;
                    <button class="btn btn-pill btn-info btn-sm" style="padding: 0px 1px;"
                            <c:if test="${loginUser.userType != '管理员'}">disabled="disabled" title="没有权限!!!"</c:if>
 * 该方法为通用的工具类,放置一些共用的方法
 */
public class Util {
    public static String DBDRIVER = "com.mysql.jdbc.Driver";
    public static String DBURL = "jdbc:mysql://localhost:3306/project_000000000000?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai&autoReconnect=true&failOverReadOnly=false&allowPublicKeyRetrieval=true";
    public static String DBUSER = "root";
    public static String PASSWORD = "123456";
    /**
     * 取得数据库连接对象
     *
     * @return 如果连接成功则返回连接对象,如果连接失败返回null
     */
    public static Connection getConnection() throws Exception {
        Class.forName(DBDRIVER);
        return DriverManager.getConnection(DBURL, DBUSER, PASSWORD);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //@Override
    public boolean delete(long id) {
        try {
            Connection c = Util.getConnection();
            Statement s = c.createStatement();
            String sql = "delete from `t_shiliao` where id = " + id;
            UserService userService = new UserServiceImpl();
            Map<String, Object> params = new HashMap();
            params.put("searchColumn", "username");//使用`username`字段进行模糊查询
            params.put("keyword", username);
            List<User> list = (List<User>) userService.list(params).get("list");
            for (User user : list) {
                if (user.getUsername().equals(username) && user.getPassword().equals(password)) {//找到这个管理员了
                    request.getSession().setAttribute("loginUser", user);
                    request.getRequestDispatcher("UserServlet").forward(request, response);
                    return;
                }
            }
            request.getSession().setAttribute("alert_msg", "错误:用户名或密码错误!");
            request.getRequestDispatcher("login.jsp").forward(request, response);
        } else if ("register".equalsIgnoreCase(action)) {//注册
            String username = Util.decode(request, "username");
            String password = Util.decode(request, "password");
            System.out.println("username=" + username);
            System.out.println("password=" + password);
            UserService userService = new UserServiceImpl();
            Map<String, Object> params = new HashMap();
            params.put("searchColumn", "username");//使用`username`字段进行模糊查询
        <input type="hidden" id="id" name="id" value="${vo.id}"/>
        
        <table class="index-content-table-add">
            <tr>
                <td width="12%">用户名:</td><td><input class="index-content-table-td-add" type="text" id="username" name="username" value="${vo.username}"/></td>
            </tr>
            <tr>
                <td width="12%">密码:</td><td><input class="index-content-table-td-add" type="text" id="password" name="password" value="${vo.password}"/></td>
            </tr>
            <tr>
                <td width="12%">姓名:</td><td><input class="index-content-table-td-add" type="text" id="realName" name="realName" value="${vo.realName}"/></td>
            </tr>
            <tr>
                <td width="12%">性别:</td>
     */
    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //过滤编码
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        String action = Util.decode(request, "action");
        if ("add".equals(action)) {//增加
            Notice vo = new Notice();
            //取出页面传进来的各个数据,并设置到Notice对象的属性里
            vo.setNoticeName(Util.decode(request, "noticeName"));
            vo.setNoticeText(Util.decode(request, "noticeText"));
            vo.setNoticeType(Util.decode(request, "noticeType"));
            vo.setCreateDate(Util.decode(request, "createDate"));
            NoticeService noticeService = new NoticeServiceImpl();
            //调用Service层增加方法(add),增加记录
            noticeService.add(vo);
            this.redirectList(request, response);
        } else if ("delete".equals(action)) {//删除
            //取出表要删除的公告记录的主键
            long id = Long.parseLong(Util.decode(request, "id"));
            NoticeService noticeService = new NoticeServiceImpl();
            //调用Service层删除方法(delete),将对应的记录删除
                return;
            }

            UserService userService = new UserServiceImpl();
            Map<String, Object> params = new HashMap();
            params.put("searchColumn", "username");//使用`username`字段进行模糊查询
            params.put("keyword", username);
            List<User> list = (List<User>) userService.list(params).get("list");
            for (User user : list) {
                if (user.getUsername().equals(username) && user.getPassword().equals(password)) {//找到这个管理员了
                    request.getSession().setAttribute("loginUser", user);
            ps.setString(2, vo.getFoodType());
            ps.setString(3, vo.getFoodPingjia());
            ps.setString(4, vo.getFoodMiaosu());
            ps.setString(5, vo.getFoodText());
            ps.setLong(6, vo.getId());
            ps.execute();
            ps.close();
            c.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 判断字符串是否是乱码
     *
     * @param strName
     * @return
     */
    public static boolean isMessyCode(String strName) {
        java.util.regex.Pattern p = java.util.regex.Pattern.compile("\\s*|\t*|\r*|\n*");
        java.util.regex.Matcher m = p.matcher(strName);
        String after = m.replaceAll("");
        String temp = after.replaceAll("\\p{P}", "");
        char[] ch = temp.trim().toCharArray();
        float chLength = 0;
        float count = 0;
        for (int i = 0; i < ch.length; i++) {
            char c = ch[i];
            if (!Character.isLetterOrDigit(c)) {
    </div>
    <br>
    <table class="table table-striped table-hover table-bordered">
        <thead>
        <tr class="index-content-table-th">
            <th>用户名</th>
            <th>姓名</th>
            <th>性别</th>
            <th>手机</th>
            <th>备注</th>
            <th>类型</th>
            <th>操作</th>
        </tr>
        </thead>
        <tbody>
        <c:forEach items="${list}" var="vo">
            <tr class="index-content-table-td">
                <td>${vo.username}</td>
            rs.close();
            ps.close();
            c.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        Map<String, Object> result = new HashMap();
        result.put("list", list);
        result.put("totalCount", totalCount);
        return result;
    }
}
package com.demo.dao.impl;

import com.demo.util.Util;
import com.demo.dao.FoodDAO;
import com.demo.vo.Food;

import java.io.Serializable;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //过滤编码
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        String action = Util.decode(request, "action");
        if ("add".equals(action)) {//增加
            User vo = new User();
            //取出页面传进来的各个数据,并设置到User对象的属性里
            vo.setUsername(Util.decode(request, "username"));
            vo.setPassword(Util.decode(request, "password"));
            vo.setRealName(Util.decode(request, "realName"));
            vo.setUserSex(Util.decode(request, "userSex"));
            vo.setUserPhone(Util.decode(request, "userPhone"));
            vo.setUserText(Util.decode(request, "userText"));
            vo.setUserType(Util.decode(request, "userType"));
            PreparedStatement ps = c.prepareStatement(sql);
            
            ps.setString(1, vo.getFoodName());
            ps.setString(2, vo.getFoodType());
            ps.setString(3, vo.getFoodPingjia());
            ps.setString(4, vo.getFoodMiaosu());
            ps.setString(5, vo.getFoodText());
            ps.setLong(6, vo.getId());
            ps.execute();
            ps.close();
            c.close();
            if (isMessyCode(str)) {
                str = new String(str.getBytes("GB2312"), "GBK");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(parameterName + "==" + str.trim());
        return str.trim();
    }
}
package com.demo.dao.impl;

import com.demo.util.Util;
import com.demo.dao.ShiliaoDAO;
        List<Food> list = new ArrayList();
        int totalCount = 0;
        String condition = "";
        String sqlList;
        if (params.get("searchColumn") != null && !"".equals(params.get("searchColumn"))) {
            condition += " and `" + params.get("searchColumn") + "` like '%" + params.get("keyword") + "%'";
        }
        try {
            Connection c = Util.getConnection();
            PreparedStatement ps;
            ResultSet rs;
        </table>
        <br>
        <br>
        <br>
        &nbsp;&nbsp;&nbsp;<button type="submit" class="btn btn-pill btn-danger btn-sm">提交</button>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<button type="button" class="btn btn-pill btn-primary btn-sm" onclick="javascript:history.back(-1);">取消</button>
    </form>
</div>

</body>
<script type="text/javascript">
    //提交之前进行检查,如果return false,则不允许提交
    function check() {
        //根据ID获取值
        if (document.getElementById("username").value.trim().length == 0) {
            alert("用户名不能为空!");
            return false;
        }
        if (document.getElementById("password").value.trim().length == 0) {
            alert("密码不能为空!");
            return false;
        }
        if (document.getElementById("realName").value.trim().length == 0) {
            alert("姓名不能为空!");
            return false;
                vo.setId(rs.getLong("id"));
                vo.setShiliaoName(rs.getString("shiliao_name"));
                vo.setShiliaoFangan(rs.getString("shiliao_fangan"));
                vo.setShiliaoText(rs.getString("shiliao_text"));
            }
            c.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return vo;
    }

    //@Override
    public Map<String, Object> list(Map<String, Object> params) {
            vo.setFoodText(Util.decode(request, "foodText"));
            FoodService foodService = new FoodServiceImpl();
            //调用Service层更新方法(update),更新记录
            foodService.update(vo);
            this.redirectList(request, response);
        } else if ("get".equalsIgnoreCase(action) || "editPre".equalsIgnoreCase(action)) {//根据主键ID,查询详情信息并跳转到详情页面或编辑页面
            Serializable id = Util.decode(request, "id");//取出页面传入的主键,用于查询详情
            FoodService foodService = new FoodServiceImpl();
            Food vo = foodService.get(id);
            request.getSession().setAttribute("vo", vo);
            String to = "get".equalsIgnoreCase(action) ? "info" : "edit";//判断是去详情显示页面还是编辑页面
            response.sendRedirect("food_" + to + ".jsp");
        } else {//默认去列表页面
            this.redirectList(request, response);
        }
    }

    /**
     * 处理Get请求
     *
     * @param request
                ps = c.prepareStatement(sqlList);
                rs = ps.executeQuery();
                while (rs.next()) {
                    Notice vo = new Notice();
                    vo.setId(rs.getLong("id"));
                    vo.setNoticeName(rs.getString("notice_name"));
                    vo.setNoticeText(rs.getString("notice_text"));
                    vo.setNoticeType(rs.getString("notice_type"));
                    vo.setCreateDate(rs.getString("create_date"));
                    list.add(vo);
                }
            String sqlCount = "select count(*) from `t_notice` where 1=1 " + condition;
            ps = c.prepareStatement(sqlCount);
            rs = ps.executeQuery();
            if (rs.next()) {
                totalCount = rs.getInt(1);
            }
            rs.close();
            ps.close();
            c.close();
        } catch (Exception e) {
        params.put("startIndex", pb.getStartIndex());
        params.put("pageSize", pb.getPageSize());
        List list = (List) foodService.list(params).get("list");//根据分页参数startIndex、pageSize查询出来的最终结果list
        pb.setServlet("FoodServlet");
        pb.setSearchColumn(searchColumn);
        pb.setKeyword(keyword);
        pb.setList(list);
        request.getSession().setAttribute("pageBean", pb);
        request.getSession().setAttribute("list", pb.getList());

        response.sendRedirect("food_list.jsp");
    }
     * @param response
     */
    private void redirectList(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //查询列和关键字
        String searchColumn = Util.decode(request, "searchColumn");
        String keyword = Util.decode(request, "keyword");
        Map<String, Object> params = new HashMap();//用来保存控制层传进来的参数(查询条件)
        params.put("searchColumn", searchColumn);//要查询的列
        params.put("keyword", keyword);//查询的关键字
        UserService userService = new UserServiceImpl();
        Map<String, Object> map = userService.list(params);
        request.getSession().setAttribute("list", map.get("list"));

        Integer totalRecord = (Integer) map.get("totalCount");//根据查询条件取出对应的总记录数,用于分页
        <tbody>
        <c:forEach items="${list}" var="vo">
            <tr class="index-content-table-td">
                <td>${vo.foodName}</td>
                <td>${vo.foodType}</td>
                <td>${vo.foodPingjia}</td>
                <td>${vo.foodMiaosu}</td>
                <td title="${vo.foodText}">
                <c:choose>
                    <c:when test="${fn:length(vo.foodText) > 19}">
                        <c:out value="${fn:substring(vo.foodText, 0, 19)}..."/>
                    </c:when>
 */
//@WebServlet("/UserServlet")
public class UserServlet extends HttpServlet {

    /**
     * 处理Post请求
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //过滤编码
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        String action = Util.decode(request, "action");
        if ("add".equals(action)) {//增加
            User vo = new User();
            //取出页面传进来的各个数据,并设置到User对象的属性里
            vo.setUsername(Util.decode(request, "username"));
            vo.setPassword(Util.decode(request, "password"));
            vo.setRealName(Util.decode(request, "realName"));
                    οnclick="window.location.href='UserServlet?action=editPre&id=${vo.id}'">编辑</button>&nbsp;
                    <button class="btn btn-pill btn-primary btn-sm" style="padding: 0px 1px;" <c:if test="${loginUser.userType != '管理员'}">disabled="disabled" title="没有权限!!!"</c:if> οnclick="if(window.confirm('将要删除:${vo.realName}?'))window.location.href='UserServlet?action=delete&id=${vo.id}'">删除</button>
                </td>
            </tr>
        </c:forEach>
        </tbody>
    </table>
    <div style="float: right;padding-right: 10px;color: #515151;"><jsp:include page="split.jsp"/></div>
</div>
</body>
<script>
    function searchList() {
        window.location.href = "UserServlet?action=list&searchColumn="+document.getElementById("searchColumn").value+"&keyword=" + document.getElementById("search_keyword").value;
    }
</script>
</html>
<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
                vo.setShiliaoName(rs.getString("shiliao_name"));
                vo.setShiliaoFangan(rs.getString("shiliao_fangan"));
                vo.setShiliaoText(rs.getString("shiliao_text"));
            }
            c.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return vo;
    }

    //@Override
    public Map<String, Object> list(Map<String, Object> params) {
            <th>内容</th>
            <th>类型</th>
            <th>创建时间</th>
            <th>操作</th>
        </tr>
        </thead>
        <tbody>
        <c:forEach items="${list}" var="vo">
            <tr class="index-content-table-td">
                <td>${vo.noticeName}</td>
                <td title="${vo.noticeText}">
                <c:choose>
                    <c:when test="${fn:length(vo.noticeText) > 19}">
        String searchColumn = Util.decode(request, "searchColumn");
        String keyword = Util.decode(request, "keyword");
        Map<String, Object> params = new HashMap();//用来保存控制层传进来的参数(查询条件)
        params.put("searchColumn", searchColumn);//要查询的列
        params.put("keyword", keyword);//查询的关键字
        FoodService foodService = new FoodServiceImpl();
        Map<String, Object> map = foodService.list(params);
        request.getSession().setAttribute("list", map.get("list"));

        Integer totalRecord = (Integer) map.get("totalCount");//根据查询条件取出对应的总记录数,用于分页
        String pageNum = Util.decode(request, "pageNum");//封装分页参数
        com.demo.util.PageBean<Object> pb = new com.demo.util.PageBean(Integer.valueOf(pageNum != null ? pageNum : "1"), totalRecord);
        params.put("startIndex", pb.getStartIndex());
        params.put("pageSize", pb.getPageSize());
        List list = (List) foodService.list(params).get("list");//根据分页参数startIndex、pageSize查询出来的最终结果list
        pb.setServlet("FoodServlet");
        pb.setSearchColumn(searchColumn);
        pb.setKeyword(keyword);
        pb.setList(list);

运行环境

Java≥6、Tomcat≥7.0、MySQL≥5.5

开发工具

eclipse/idea/myeclipse/sts等均可配置运行

技术框架

JavaWeb JavaBean JSP MVC MySQL Tomcat JavaScript Bootstrap.

基础JSP+Servlet或JSP+SSM(Spring、SpringMVC、MyBatis)框架或JSP+SSM+Maven(pom.xml)框架或SpringBoot…均可

适用

课程设计,大作业,毕业设计,项目练习,学习演示等

功能说明

登录、注册、退出、用户模块、公告模块、食材信息模块、食疗处方模块的增删改查管理

20220319003154

20220319003155

20220319003156

20220319003157

20220319003158

20220319003159

20220319003200

20220319003201

20220319003202

20220319003203

document

↖[获取源码方式]见左侧

举报

相关推荐

0 条评论