${pagecontext.request.contextpath}的意义、当前台数据获取的时间为String类型需要转化为Date类型插入到数据库时 (局部转换)

本文详细介绍了Java Web开发中常见的问题及解决方案,包括EL表达式的使用、解决输出乱码、前后台日期转换、复合主键配置、利用Session跨Controller传递数据等关键知识点。

          1.${pagecontext.request.contextpath}作用
${pageContext.request.contextPath}等价于<%=request.getContextPath()%> 
或者可以说是<%=request.getContextPath()%>的EL版 
意思就是取出部署的应用程序名或者是当前的项目名称
比如我的项目名称是quickstart在浏览器中输入为http://localhost:8080/quickstart/register.jsp 
${pageContext.request.contextPath}或<%=request.getContextPath()%>取出来的就是/quickstart,而"/"代表的含义就是http://localhost:8080
所以我们项目中应该这样写${pageContext.request.contextPath}/register.jsp
${pageContext.request.contextPath}用于解决使用相对路径时出现的问题,它的作用是取出所部署项目的名字。
      2.输出乱码(在页面内上显示信息)
例如
  result="<font color='red'>该用户名已经被使用</font>"
  response.setContentType("text/html");
  response.setCharacterEncoding("UTF-8");//response.setContentType("text/html;charset=UTF-8")
  response.getWriter().print(result);
   3.当前台数据获取的时间为String类型需要转化为Date类型插入到数据库时
(局部转换)
 @InitBinder
    public void initBinder(WebDataBinder binder, WebRequest request) {
        
        //转换日期
        DateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));// CustomDateEditor为自定义日期编辑器
    }

(全局转换)
1.创建CustomDate类实现WebBindingInitializer
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.support.WebBindingInitializer;
import org.springframework.web.context.request.WebRequest;
 
public class CustomDate implements WebBindingInitializer{
 
    @Override
    public void initBinder(WebDataBinder binder, WebRequest request) {
        // TODO Auto-generated method stub
        //转换日期
        DateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }
}

2.在Spring-MVC.xml中配置日期转换
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
     http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
     http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
     http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
     http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
    <context:component-scan base-package="com.gwd.shopping" use-default-filters="false">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
    
    <!-- 日期转换 -->
    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="webBindingInitializer">
            <bean class="com.gwd.shopping.core.web.CustomDate"/>
        </property>
    </bean>
    
    <bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/back_page/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>
4.Date日期的相加减
 Date d=new Date();   
 SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");   
 System.out.println("今天的日期:"+df.format(d));   
 System.out.println("两天前的日期:" + df.format(new Date(d.getTime() - (long)2 * 24 * 60 * 60 * 1000)));  
   System.out.println("三天后的日期:" + df.format(new Date(d.getTime() + (long)3 * 24 * 60 * 60 * 1000)));
获取某天的年月日:
int year =calendar.get(Calendar.YEAR);    
int month=calendar.get(Calendar.MONTH)+1;
int day =calendar.get(Calendar.DAY_OF_MONTH);    
int hour =calendar.get(Calendar.HOUR_OF_DAY);    
int minute =calendar.get(Calendar.MINUTE);    
int seconds =calendar.get(Calendar.SECOND);   
5.复合主键注意在映射hibernate时,注意无论只进行查询操作,都需要配好复合主键,否则查询就会出错。
6.在controller传给前台的list中,注意加上前缀,否则可能得不到其值。
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
7.利用Session在两个Controller中传递
@Controller
public class ManagerController {
 
    @Resource
    private ManagerService managerServiceImpl;
    
    @RequestMapping(value = "manager/login.do",method = RequestMethod.GET)  
    public ModelAndView login(ManagerModel managerModel,HttpSession httpSession){
        
        ManagerModel manager = managerServiceImpl.getManager(managerModel);
        if(manager!=null){
            manager.setPassword("");
            httpSession.setAttribute("manager", manager);
            return new ModelAndView(new RedirectView("../admin/main.jsp"));
        }else{
            return new ModelAndView(new RedirectView("../admin/login.jsp"));
        }
    }
    
    @RequestMapping(value = "manager/logout.do",method = RequestMethod.GET)
    public String logout(HttpSession httpSession){
        httpSession.getAttribute("manager");
        return "success";
    }
}
8.
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:mvc="http://www.springframework.org/schema/mvc" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
                        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd 
                        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"
    default-autowire="byName">

Sep 8, 2018 12:00:00 AM
 

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ page import="javax.servlet.*,java.text.*" %> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="renderer" content="webkit"> <title>收入综合分析平</title> <link rel="stylesheet" href="${pageContext.request.contextPath}/resources/bootstrap-3.3.7-dist/css/bootstrap.min.css"> <%-- 右击菜单样式 --%> <link href="${pageContext.request.contextPath}/resources/ruoyi/ruoyi/css/jquery.contextMenu.min.css" rel="stylesheet"/> <%-- <link href="${pageContext.request.contextPath}/resources/ruoyi/ruoyi/css/animate.min.css" rel="stylesheet"/>--%> <link href="${pageContext.request.contextPath}/resources/ruoyi/ruoyi/css/style.min.css" rel="stylesheet"/> <link href="${pageContext.request.contextPath}/resources/ruoyi/ruoyi/css/skins.css" rel="stylesheet"/> <link href="${pageContext.request.contextPath}/resources/ruoyi/ruoyi/css/ry-ui.css?v=4.6.1" rel="stylesheet"/> <%-- 图标库 --%> <link href="${pageContext.request.contextPath}/resources/ruoyi/ruoyi/css/font-awesome.min.css" rel="stylesheet"/> <script src="${pageContext.request.contextPath}/resources/js/jquery-1.11.3.min.js?v=<%=System.currentTimeMillis()%>"></script> <script src="${pageContext.request.contextPath}/resources/bootstrap-3.3.7-dist/js/bootstrap.min.js?v=<%=System.currentTimeMillis()%>"></script> <script src="${pageContext.request.contextPath}/resources/global/global.js?v=<%=System.currentTimeMillis()%>"></script> <script type="text/javascript"> $(function(){ $.ajax({ type: 'get', url: "dic/getUrlByUser", async: false, dataType: 'json', success: function (data) {//返回list数据并循环获取 var ht = ""; var arr = ['desktop','calculator','leanpub','map','send','bar-chart','line-chart','train','american-sign-language-interpreting','gears','user-circle-o','paper-plane','firefox']; for(var i=0;i<data.length;i++){ //循环一级菜单 ht = ht +'<li>'+ '<a href="#">' + '<i class="fa fa-'+arr[i]+'"></i> ' + '<span class="nav-label">'+data[i].mkName+'</span>' + '<span class="fa arrow"></span>' + '</a>'+ '<ul class="nav nav-second-level collapse">'; var obj = data[i].obj; if(obj[0].cdlb == ""){//该模块不存在二级菜单 for(var j=0;j<obj.length;j++){ ht = ht + '<li>\n' + '<a class="menuItem" href="'+obj[j].cdUrl+'">'+ obj[j].cdName +'</a>' + '</li>'; } ht = ht + '</ul></li>'; }else{ var cdlbArr = new Array(); for(var j=0;j<obj.length;j++){ cdlbArr.push(obj[j].cdlb); } cdlbArr = uniqueArr(cdlbArr); for(var k=0;k<cdlbArr.length;k++){ ht = ht + '<li>\n' + '<a href="#"><i class="fa fa-pied-piper"></i> '+cdlbArr[k]+'<span class="fa arrow"></span></a>\n' + '<ul class="nav nav-third-level collapse">'; for(var m=0;m<obj.length;m++){ if(cdlbArr[k] == obj[m].cdlb){ ht = ht + '<li>\n' + '<a class="menuItem" href="'+obj[m].cdUrl+'">'+ obj[m].cdName +'</a>' + '</li>'; } } ht = ht + '</ul></li>'; } } ht = ht + '</ul></li>'; } $("#side-menu").append(ht); } }); }) /* * 用于解决浏览器关闭后Cookie未失效,攻击者可在用户关闭浏览器后,通过同一cookie直接访问网站(无需重新登录),窃取用户会话; * 由于ajax是异步 使用会造成发送不过去的现象 需要使用同步请求 * 另外 如果只是使用 window.addEventListener('beforeunload'来判断 会出现 刷野也会消除session 所以只能通过一下方法来实现 * */ window.addEventListener('beforeunload', function(e) { // 获取导航类型(替代废弃的performance.navigation.type) console.log(JSON.stringify(performance.getEntriesByType("navigation")[0].toJSON().type)) const navType = performance.getEntriesByType("navigation")[0].toJSON().type; sendLogoutRequest(navType) // 排除刷新行为,仅在离开/关闭触发逻辑 if (navType !== 'reload') { console.log('离开页面,执行逻辑') //sendLogoutRequest() return '111'; } }); /*class PageLeaveHandler { constructor() { this.isRefreshing = false; this.pendingUnload = false; this.pendingUnloadnum = 0;//默认值 this.init(); } init() { // 监听刷新快捷键 window.addEventListener('keydown', (e) => { if (e.key === 'F5' || (e.ctrlKey && e.key === 'F5')) { this.isRefreshing = true; } }); // 监听beforeunload事件 window.addEventListener('beforeunload', this.handleBeforeUnload.bind(this)); } handleBeforeUnload(e) { if (this.isRefreshing) { this.pendingUnload = false; return; } //sendLogoutRequest(this.isRefreshing) this.pendingUnload = true; return 1; } } new PageLeaveHandler();*/ function sendLogoutRequest(navType) { const logoutUrl = '${pageContext.request.contextPath}/sys/loginoutall?navType='+navType; if (navigator.sendBeacon) { navigator.sendBeacon(logoutUrl, 'loginoutall'); } else { const xhr = new XMLHttpRequest(); xhr.open('GET', logoutUrl, false); // 同步请求 xhr.timeout = 2000; try { xhr.send(); } catch (e) { // 忽略错误 } } } /*window.addEventListener('beforeunload', function(e) { // 取消事件的默认行为(部分浏览器需要) e.preventDefault(); if(!e.isTrusted){ // 2. 拼接正确的上下文路径(关键:避免404) const logoutUrl = '${pageContext.request.contextPath}/sys/loginoutall'; // 3. 用sendBeacon发送请求,浏览器会优先保证发送完成 if (navigator.sendBeacon) { navigator.sendBeacon(logoutUrl, 'loginoutall'); } else { const xhr = new XMLHttpRequest(); xhr.open('GET', logoutUrl, false); // 同步请求 xhr.timeout = 2000; try { xhr.send(); } catch (e) { } } } });*/ </script> </head> <body class="fixed-sidebar full-height-layout gray-bg skin-blue theme-light" style="overflow: hidden"> <div id="wrapper"> <!--左侧导航开始--> <nav class="navbar-default navbar-static-side" role="navigation"> <div class="nav-close"> <i class="fa fa-times-circle"></i> </div> <a href=""> <li class="logo hidden-xs"> <span class="logo-lg">欢迎${user.username}</span> </li> </a> <div class="sidebar-collapse"> <ul class="nav" id="side-menu"> <li> <div class="user-panel"> <%-- 该位置换谁个人中心地址 --%> <a class="menuItem noactive" title="个人中心" href=""> <div class="hide" text="个人中心"></div> <div class="pull-left image"> <%--<img src="resources/ruoyi/favicon.ico" class="img-circle" alt="User Image">--%> <img src="resources/image/eee.png" class="img-circle" alt="User Image"> </div> </a> <div class="pull-left info"> <%-- 该位置可以加上el表达式 然后读取成登录名即可 --%> <p></p> <a href="#"><i class="fa fa-circle text-success"></i> 在线</a> <%-- 该位置发起退出请求 换上即可 --%> <a href="sys/loginout" style="padding-left:5px;"><i class="fa fa-sign-out text-danger"></i> 注销</a> </div> </div> </li> <li> <a class="menuItem" href="web/main/sy.jsp"><i class="fa fa-home"></i> <span class="nav-label">首页</span></a> </li> </ul> </div> </nav> <!--左侧导航结束--> <!--右侧部分开始--> <div id="page-wrapper" class="gray-bg dashbard-1"> <div class="row border-bottom"> <nav class="navbar navbar-static-top" role="navigation" style="margin-bottom: 0"> <div class="navbar-header"> <a class="navbar-minimalize minimalize-styl-2" style="color:#FFF;" href="#" title="收起菜单"> <i class="fa fa-bars"></i> </a> </div> <ul class="nav navbar-top-links navbar-right welcome-message"> <%--<li><a data-toggle="tooltip" data-trigger="hover" data-placement="bottom" title="开发文档" href="http://doc.ruoyi.vip/ruoyi" target="_blank"><i class="fa fa-question-circle"></i> 文档</a></li> <li><a data-toggle="tooltip" data-trigger="hover" data-placement="bottom" title="锁定屏幕" href="#" id="lockScreen"><i class="fa fa-lock"></i> 锁屏</a></li>--%> <li><a data-toggle="tooltip" data-trigger="hover" data-placement="bottom" title="全屏显示" href="#" id="fullScreen"><i class="fa fa-arrows-alt"></i> 全屏</a></li> <%--<li class="dropdown user-menu"> <a href="javascript:void(0)" class="dropdown-toggle" data-hover="dropdown"> <img src="resources/image/eee.png" class="user-image"> <%– 该位置用el表达式读取登录名 –%> <span class="hidden-xs">海来怡天</span> </a> <ul class="dropdown-menu"> <li class="mt5"> <%– 该位置是个人中心超链接 –%> <a href="" class="menuItem noactive"> <i class="fa fa-user"></i> 个人中心</a> </li> <li> <a onclick="resetPwd()"> <i class="fa fa-key"></i> 修改密码</a> </li> <li> <a onclick="switchSkin()"> <%–<a id="btn" >–%> <i class="fa fa-dashboard"></i> 切换主题 </a> </li> <li class="divider"></li> <li> <%– 该位置是推出登录请求 –%> <a href=""> <i class="fa fa-sign-out"></i> 退出登录</a> </li> </ul> </li>--%> </ul> </nav> </div> <div class="row content-tabs"> <button class="roll-nav roll-left tabLeft"> <i class="fa fa-backward"></i> </button> <nav class="page-tabs menuTabs"> <div class="page-tabs-content"> <a href="javascript:" class="active menuTab" data-id="web/main/sy.jsp">首页</a> </div> </nav> <button class="roll-nav roll-right tabRight"> <i class="fa fa-forward"></i> </button> <a href="javascript:void(0);" class="roll-nav roll-right tabReload"><i class="fa fa-refresh"></i> 刷新</a> </div> <a id="ax_close_max" class="ax_close_max" href="#" title="关闭全屏"> <i class="fa fa-times-circle-o"></i> </a> <div class="row mainContent" id="content-main" > <iframe class="RuoYi_iframe" name="iframe0" width="100%" height="100%" data-id="web/main/sy.jsp" src="web/main/sy.jsp" frameborder="0" seamless></iframe> </div> </div> <!--右侧部分结束--> </div> <!-- 全局js --> <script type="text/javascript" src="${pageContext.request.contextPath}/resources/ruoyi/js/plugins/metisMenu/jquery.metisMenu.js?v=<%=System.currentTimeMillis()%>"></script> <script type="text/javascript" src="${pageContext.request.contextPath}/resources/ruoyi/js/plugins/slimscroll/jquery.slimscroll.min.js?v=<%=System.currentTimeMillis()%>"></script> <script type="text/javascript" src="${pageContext.request.contextPath}/resources/ruoyi/js/jquery.contextMenu.min.js?v=<%=System.currentTimeMillis()%>"></script> <%--<script src="${pageContext.request.contextPath}/resources/ruoyi/ajax/libs/layui/layui.js?v=<%=System.currentTimeMillis()%>"></script>--%> <%-- 该方法用于将页面加载到本页面 --%> <script type="text/javascript" src="${pageContext.request.contextPath}/resources/ruoyi/ajax/libs/blockUI/jquery.blockUI.js?v=<%=System.currentTimeMillis()%>"></script> <script type="text/javascript" src="${pageContext.request.contextPath}/resources/ruoyi/ajax/libs/layer/layer.min.js?v=<%=System.currentTimeMillis()%>"></script> <script type="text/javascript" src="${pageContext.request.contextPath}/resources/ruoyi/ruoyi/js/ry-ui.js?v=<%=System.currentTimeMillis()%>"></script> <script type="text/javascript" src="${pageContext.request.contextPath}/resources/ruoyi/ruoyi/js/common.js?v=<%=System.currentTimeMillis()%>"></script> <script type="text/javascript" src="${pageContext.request.contextPath}/resources/ruoyi/ruoyi/index.js?v=<%=System.currentTimeMillis()%>"></script> <script type="text/javascript" src="${pageContext.request.contextPath}/resources/ruoyi/ajax/libs/fullscreen/jquery.fullscreen.js?v=<%=System.currentTimeMillis()%>"></script> <script> /*window.history.forward(1); var ctx = "/zhfx"; // 皮肤缓存 var skin = storage.get("skin");*/ // history(表示去掉地址的#)否则地址以"#"形式展示 var mode = "history"; // 历史访问路径缓存 var historyPath = storage.get("historyPath"); // 是否页签与菜单联动 var isLinkage = true; /* * 这个js如果删了 按下F12编辑 页面会不起作用 * */ $(function() { var lockPath = storage.get('lockPath'); if($.common.equals("history", mode) && window.performance.navigation.type == 1) { var url = storage.get('publicPath'); if ($.common.isNotEmpty(url)) { applyPath(url); } } else if($.common.isNotEmpty(lockPath)) { applyPath(lockPath); storage.remove('lockPath'); } else { var hash = location.hash; if ($.common.isNotEmpty(hash)) { var url = hash.substring(1, hash.length); applyPath(url); } else { if($.common.equals("history", mode)) { storage.set('publicPath', ""); } } } $("[data-toggle='tooltip']").tooltip(); }); </script> </body> </html> 为什么 一个刷新 一个跳转 这俩 点刷新是reload 再点跳转还是reload 必须第二下才是navigate 但是这样点了navigate之后 再点刷新还是navigate 必须再点刷新才是reload 这可不能这样
最新发布
11-12
这是我的表结构: DROP TABLE IF EXISTS `animalphotos`; CREATE TABLE `animalphotos` ( `photo_id` int NOT NULL AUTO_INCREMENT COMMENT ' 照片ID', `animal_id` int NULL DEFAULT NULL COMMENT ' 所属动物ID', `photo_url` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '图片路径或URL', PRIMARY KEY (`photo_id`) USING BTREE, INDEX `animal_id`(`animal_id` ASC) USING BTREE, CONSTRAINT `animalphotos_ibfk_1` FOREIGN KEY (`animal_id`) REFERENCES `animals` (`animal_id`) ON DELETE RESTRICT ON UPDATE RESTRICT ) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic; -- ---------------------------- -- Table structure for animals -- ---------------------------- DROP TABLE IF EXISTS `animals`; CREATE TABLE `animals` ( `animal_id` int NOT NULL AUTO_INCREMENT COMMENT '动物唯一标识', `name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '名称', `species` varchar(25) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT ' 种类', `gender` enum('雄','雌') CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT ' 性别', `age` int NULL DEFAULT NULL COMMENT ' 年龄', `user_id` int NULL DEFAULT NULL COMMENT ' 关联饲养者/管理者(Users.user_id)', `zone` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '动物位置', PRIMARY KEY (`animal_id`) USING BTREE, INDEX `caretaker_id`(`user_id` ASC) USING BTREE, INDEX `species_id`(`species` ASC) USING BTREE, CONSTRAINT `animals_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`user_id`) ON DELETE RESTRICT ON UPDATE RESTRICT ) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic; -- ---------------------------- -- Table structure for animaltraits -- ---------------------------- DROP TABLE IF EXISTS `animaltraits`; CREATE TABLE `animaltraits` ( `trait_id` int NOT NULL AUTO_INCREMENT COMMENT ' 特征ID', `animal_id` int NULL DEFAULT NULL COMMENT '动物ID(Animals)', `nature` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '性格 ', `favourite` text CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL COMMENT ' 喜好描述', PRIMARY KEY (`trait_id`) USING BTREE, INDEX `animal_id`(`animal_id` ASC) USING BTREE, CONSTRAINT `animaltraits_ibfk_1` FOREIGN KEY (`animal_id`) REFERENCES `animals` (`animal_id`) ON DELETE RESTRICT ON UPDATE RESTRICT ) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic; -- ---------------------------- -- Table structure for users -- ---------------------------- DROP TABLE IF EXISTS `users`; CREATE TABLE `users` ( `user_id` int NOT NULL AUTO_INCREMENT COMMENT ' 用户唯一标识', `username` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '用户名', `password` varchar(30) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '密码(加密)', `role` enum('游客','饲养者','管理员') CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT ' 角色:游客/饲养者/管理员', `status` enum('在线','离线') CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '用户状态(是否在线)', PRIMARY KEY (`user_id`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 9 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic; SET FOREIGN_KEY_CHECKS = 1; 这是我的实体类: // User 类 public class User { private int user_id; private String username; private String password; private String role; private String status; private List<Animals> animals; // 用户与动物是一对多关系 // getter 和 setter 方法 } // Animals 类 public class Animals { private int animal_id; private String name; private String gender; // 雄/雌 private Integer age; private String species; private String zone; private User user; // 动物与用户是一对多关系(反向关联) private List<AnimalPhoto> animalPhotos; // 动物与照片是一对多关系 // getter 和 setter 方法 } // AnimalPhoto 类 public class AnimalPhoto { private int photo_id; private Animals animal; // 照片与动物是一对多关系(反向关联) private String photo_url; // getter 和 setter 方法 } // AnimalTrait 类 public class AnimalTrait { private int trait_id; private Animals animal; // 特征与动物是一对一关系(反向关联) private String nature; // 性格 private String favourite; // 喜好描述 // getter 和 setter 方法 } 用户 (users) 与动物 (animals) 之间是一对多关系。 动物 (animals) 与照片 (animalphotos) 之间是一对多关系。 动物 (animals) 与特征 (animaltraits) 之间是一对一关系。 这是我登录注册代码: package com.cxy.Controller; import com.cxy.Pojo.User; import com.cxy.Service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpSession; import java.text.SimpleDateFormat; import java.util.Date; @Controller public class UserController { @Autowired private UserService userService; // 显示登录页面 @GetMapping("/login") public String loginPage(@RequestParam(value = "error", required = false) String error, Model model) { if (error != null) { model.addAttribute("error", true); } return "/login/login.jsp"; // 返回登录页面 } // 处理登录请求 @PostMapping("/login") public String login(@RequestParam String username, @RequestParam String password, HttpSession session, Model model) { User user = userService.login(username, password); if (user != null) { // 更新数据库中的在线状态 userService.updateUserStatus(user.getUserId(), "在线"); // 将用户信息存入 session session.setAttribute("user", user); session.setAttribute("username", user.getUsername()); // 存储用户名 session.setAttribute("role", user.getRole()); // 存储角色 session.setAttribute("status", "在线"); // 存储状态 session.setAttribute("loginTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); // 登录时间 return "redirect:/index.jsp"; // 登录成功,跳转到主页 } // 登录失败,返回登录页面并传递错误信息 model.addAttribute("loginError", "用户名或密码错误,请重新尝试。"); return "login/login.jsp"; } // 显示注册页面 @GetMapping("/register") public String registerPage() { return "/login/register.jsp"; // 返回注册页面 } // 处理注册请求 @PostMapping("/register") public String register(User user, Model model) { if (userService.register(user)) { return "/login/login.jsp"; // 注册成功,跳转到登录页面 } model.addAttribute("registerError", "用户名已存在"); // 用户名已存在 return "/login/register.jsp"; // 注册失败,返回注册页面 } // 处理退出登录 @GetMapping("/logout") public String logout(HttpSession session) { User user = (User) session.getAttribute("user"); if (user != null) { userService.updateUserStatus(user.getUserId(), "离线"); } session.invalidate(); // 清除session return "redirect:/login/login.jsp"; // 返回登录页面 } } 这是我实现登录注册的配置: <?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.cxy.Mapper.UserMapper"> <!-- 查询用户 --> <select id="findByUsername" resultType="com.cxy.Pojo.User"> SELECT * FROM users WHERE username = #{username} </select> <!-- 插入新用户 --> <insert id="insertUser" parameterType="com.cxy.Pojo.User"> INSERT INTO users (username, password, role) VALUES (#{username}, #{password}, #{role}) </insert> <!-- 更新在线状态 --> <update id="updateStatus"> UPDATE users SET status = #{status} WHERE user_id = #{user_id} </update> </mapper> application-dao.xml:<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <context:property-placeholder location="classpath:jdbc.properties"/> <!-- 配置数据源 --> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> <property name="driverClassName" value="${jdbc.driverClassName}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </bean> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> </bean> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.cxy.Mapper"/> </bean> </beans> application-service.xml:<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 配置组件扫描 --> <context:component-scan base-package="com.cxy.Service"/> </beans> spring-mvc.xml:<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" 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.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <context:component-scan base-package="com.cxy.Controller"/> <mvc:annotation-driven/> <mvc:resources mapping="/css/**" location="/css/" /> </beans> web.xml:<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.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> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:application-*.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- Spring DispatcherServlet --> <servlet> <servlet-name>Dispatcher</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <!-- 配置 Spring DispatcherServlet 映射 --> <servlet-mapping> <servlet-name>Dispatcher</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> index.jsp: <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ page import="java.util.Date" %> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <!DOCTYPE html> <html> <head> <title>动物园数字档案管理系统</title> <link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/css/index.css"> </head> <body> <!-- 顶部导航栏 --> <header> <div class="logo"> <img src="<%= request.getContextPath() %>/images/zoo-logo.png" alt="Zoo Logo"> </div> <nav> <ul> <li><a href="${pageContext.request.contextPath}/index.jsp">首页</a></li> <li><a href="${pageContext.request.contextPath}/animal.jsp">动物信息</a></li> <li><a href="${pageContext.request.contextPath}/activities.jsp">活动预约</a></li> <li><a href="${pageContext.request.contextPath}/forum.jsp">用户交流</a></li> <% String username = (String) session.getAttribute("username"); String userRole = (String) session.getAttribute("role"); String userStatus = (String) session.getAttribute("status"); if ("饲养者".equals(userRole)) { out.println("<li><a href='" + request.getContextPath() + "/animal/list'>我的动物</a></li>"); } else if ("管理员".equals(userRole)) { out.println("<li><a href='" + request.getContextPath() + "/animal/list'>所有动物</a></li>"); } if (username == null) { out.println("<li><a href='" + request.getContextPath() + "/login/login.jsp'>登录/注册</a></li>"); } else { out.println("<li><a href='" + request.getContextPath() + "/logout'>退出登录</a></li>"); out.println("<li><span>登录时间: " + session.getAttribute("loginTime") + "</span></li>"); } %> </ul> </nav> </header> <!-- 主要内容 --> <div class="content"> <% if ("游客".equals(userRole)) { %> <div class="animal-search"> <h2>探索动物世界</h2> <input type="text" placeholder="搜索动物..."> <button onclick="window.location.href='${pageContext.request.contextPath}/activities.jsp'">立即预约活动</button> </div> <% } else if ("饲养者".equals(userRole)) { %> <div class="manage-animals"> <h2>饲养者面板</h2> <p>欢迎,<%= username %>!您当前状态:<%= userStatus %></p> </div> <% } else if ("管理员".equals(userRole)) { %> <div class="admin-panel"> <h2>管理员面板</h2> <p>欢迎,<%= username %>!您当前状态:<%= userStatus %></p> </div> <% } else { %> <div class="welcome-message"> <h2>欢迎来到动物园数字档案管理系统</h2> <p>请登录或注册以获取更多功能。</p> <button onclick="window.location.href='${pageContext.request.contextPath}/login/login.jsp'">登录/注册</button> </div> <% } %> </div> <!-- 底部信息栏 --> <footer> <div class="footer-content"> <p>©2023 动物园数字档案管理系统</p> <p>联系我们:info@zoodatabase.com</p> </div> </footer> </body> </html> add_animal.jsp: <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <!DOCTYPE html> <html> <head> <title>添加动物 - 动物园数字档案管理系统</title> <link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/css/animal_form.css"> </head> <body> <jsp:include page="/header.jsp"/> <div class="container"> <h1>添加新动物</h1> <form action="${pageContext.request.contextPath}/animal/add" method="post" enctype="multipart/form-data"> <div class="form-group"> <label for="name">动物名称:</label> <input type="text" id="name" name="name" required> </div> <div class="form-group"> <label for="species">种类:</label> <input type="text" id="species" name="species" required> </div> <div class="form-group"> <label for="gender">性别:</label> <select id="gender" name="gender" required> <option value="">请选择</option> <option value="雄">雄</option> <option value="雌">雌</option> </select> </div> <div class="form-group"> <label for="age">年龄:</label> <input type="number" id="age" name="age" min="0" required> </div> <div class="form-group"> <label for="zone">位置:</label> <input type="text" id="zone" name="zone" required> </div> <div class="form-group"> <label for="photo_url">上传照片:</label> <input type="file" id="photo_url" name="photo_url" multiple> </div> <div class="form-group"> <label for="nature">性格:</label> <input type="text" id="nature" name="nature" required> </div> <div class="form-group"> <label for="favourite">喜好描述:</label> <textarea id="favourite" name="favourite"></textarea> </div> <div class="form-actions"> <button type="submit" class="btn btn-primary">添加动物</button> <a href="${pageContext.request.contextPath}/animal/list" class="btn btn-secondary">取消</a> </div> </form> </div> 注意:查询查的是动物完整的信息(包括图片),添加也要添加动物完整的信息,可以对数据库插入动物图片。这需要对表进行关联。 请根据我的配置和我给出的添加动物页面add_aniaml.jsp,用javaee的ssm整合框架实现饲养者和管理者对动物的增删改查,,以及写出对应的jsp页面:在/animal/目录内,并修改index页面。包括(controller接口,mapper接口,service,serviceimpl和Mapper新配置)。其中饲养者登录:显示我的动物导航栏,点击进入页面只能对自己添加的动物进行修改数据和删除,也可以在该页面添加新的动物。而管理者登录:显示所有动物导航栏,点击进入页面,可以对全部动物信息增删改。饲养者和管理者可以对动物所有信息进行写入。
05-29
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值