关于${ctxPath}和@webServlet

本文探讨了在login.jsp表单中的数据如何通过LoginServlet处理,重点解析了¥{ctxPath}

在login.jsp的form表单中:

对应的LoginServlet.java中:
@WebServlet("/doLogin.action")

1.¥{ctxPath}是一种寻址方式。这里用的是绝对路径。
2.@WebServlet(“路径”)
该注解的作用等价于 在web.xml中配置的该servlet的元素中的配置

package common.servlet; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpSession; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; import security.MenuDisp; import util.StringUtil; import common.CommonMethod; import common.constant.BizExceptionMsg; import common.exception.BizException; @WebServlet("/mainmenu") public class MainMenu extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 1. コンテキストパスとパラメータを取得する String ctxPath = request.getContextPath(); HttpSession ses = request.getSession(true); String userId = StringUtil.toString(ses.getAttribute("APP_USER")); // 2. 処理前のログイン時間 Date sysLastLoginDateTime = (Date) ses.getAttribute("sysLastLoginDateTime"); String lastLoginTime = ""; if (sysLastLoginDateTime != null) { lastLoginTime = StringUtil.seirekiToWareki(sysLastLoginDateTime, StringUtil.WarekiFormat.LONG_DATETIME); } // 3. メニュー関連の変数を初期化する String strMenuNm6 = ""; String strMenuNm12 = ""; String strMenuNm14 = ""; String strNone = "none"; String strMenuDisp6 = strNone; String strMenuDisp12 = strNone; String strMenuDisp14 = strNone; String strRootUrl6 = ""; String strRootUrl12 = ""; String strRootUrl14 = ""; // 4. メニューデータを取得する List<Map<String, Object>> resultList = new ArrayList<>(); try { resultList = MenuDisp.getGyoumuAndKanriMenu(userId); } catch (Exception e) { BizException.throwException(BizExceptionMsg.AUTH_ERROR); } String userName = ""; String userShozoku = ""; if (!resultList.isEmpty()) { userName = StringUtil.toString(resultList.get(0).get("氏名")); userShozoku = StringUtil.toString(resultList.get(0).get("所属")); ses.setAttribute("APP_USERNAME", resultList.get(0).get("氏名")); ses.setAttribute("APP_SHOZOKUNAME", resultList.get(0).get("所属")); for (Map<String, Object> map : resultList) { String menuOrder = StringUtil.toString(map.get("メニュー順")); String strMenuNm = StringUtil.toString(map.get("メニュー名称")); String strMenuId = StringUtil.toString(map.get("メニューID")); if ("PS".equals(strMenuId)) { strMenuNm14 = strMenuNm; strMenuDisp14 = ""; strRootUrl14 = strMenuId; } else { switch (menuOrder) { case "6": strMenuNm6 = strMenuNm; strMenuDisp6 = ""; strRootUrl6 = strMenuId; break; case "12": strMenuNm12 = strMenuNm; strMenuDisp12 = ""; strRootUrl12 = strMenuId; break; } } } } // 5. 通知情報を取得する List<Map<String, Object>> infoList = new ArrayList<>();; try { infoList = CommonMethod.getInformation("CM"); } catch (Exception e) { BizException.throwException(BizExceptionMsg.AUTH_ERROR); } // 6. リクエストスコープに保存 request.setAttribute("ctxPath", ctxPath); request.setAttribute("lastLoginTime", lastLoginTime); request.setAttribute("strMenuNm6", strMenuNm6); request.setAttribute("strMenuDisp6", strMenuDisp6); request.setAttribute("strRootUrl6", strRootUrl6); request.setAttribute("strMenuNm12", strMenuNm12); request.setAttribute("strMenuDisp12", strMenuDisp12); request.setAttribute("strRootUrl12", strRootUrl12); request.setAttribute("strMenuNm14", strMenuNm14); request.setAttribute("strMenuDisp14", strMenuDisp14); request.setAttribute("strRootUrl14", strRootUrl14); request.setAttribute("userName", userName); request.setAttribute("userShozoku", userShozoku); request.setAttribute("infoList", infoList); // 7. JSPに転送 request.getRequestDispatcher("/page/menu.jsp").forward(request, response); } }给我将这段代码中的“”字符串变成常量
最新发布
10-21
信息: 至少有一个JAR被扫描用于TLD但尚未包含TLD。 为此记录器启用调试日志记录,以获取已扫描但未在其中找到TLD的完整JAR列表。 在扫描期间跳过不需要的JAR可以缩短启动时间JSP编译时间。 六月 16, 2025 11:24:05 上午 org.apache.coyote.AbstractProtocol start 信息: 开始协议处理句柄["http-nio-8282"] 六月 16, 2025 11:24:05 上午 org.apache.catalina.startup.Catalina start 信息: [1940]毫秒后服务器启动package com.taobao.servlet; import java.io.IOException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.gson.Gson; import com.taobao.util.DBUtil; @WebServlet("/rebuyPrediction") public class RebuyPredictionServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 设置响应编码为 UTF-8 并指定 JSON 格式 response.setCharacterEncoding("UTF-8"); response.setContentType("application/json;charset=UTF-8"); List<Map<String, Object>> predictions = new ArrayList<>(); String sql = "SELECT score, label FROM rebuy LIMIT 50"; try (Connection conn = DBUtil.getConnection(); PreparedStatement pstmt = conn.prepareStatement(sql); ResultSet rs = pstmt.executeQuery()) { while (rs.next()) { Map<String, Object> prediction = new HashMap<>(); prediction.put("score", rs.getString("score")); prediction.put("label", rs.getString("label")); predictions.add(prediction); } // 将预测数据转换为 JSON 并写入响应 response.getWriter().write(new Gson().toJson(predictions)); } catch (Exception e) { e.printStackTrace(); // 创建一个包含错误信息的 Map(兼容 Java 8) Map<String, String> errorResponse = new HashMap<>(); errorResponse.put("error", "服务器内部错误"); // 返回错误信息的 JSON 响应 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); response.getWriter().write(new Gson().toJson(errorResponse)); } } }function loadRebuyData() { $('#rebuyChart').html('<div class="loading">正在加载复购预测数据...</div>'); $.ajax({ url: ctxPath + '/rebuyPrediction', type: 'GET', dataType: 'json', success: function(data) { if (!data || !Array.isArray(data)) { // 检查 data 是否为数组 $('#rebuyChart').html('<div class="error-display">数据格式错误</div>'); return; } if (data.length === 0) { $('#rebuyChart').html('<div class="error-display">未获取到复购预测数据</div>'); } else { initRebuyChart(data); } }, error: function(jqXHR, textStatus, errorThrown) { console.error('加载复购预测数据失败:', textStatus, errorThrown); $('#rebuyChart').html('<div class="error-display">请求失败: ' + textStatus + '</div>'); } }); } // 初始化复购预测图表 function initRebuyChart(rebuyData) { const chartDom = document.getElementById('rebuyChart'); chartDom.innerHTML = ''; const myChart = echarts.init(chartDom); // 分类数据 const scores = rebuyData.map(r => parseFloat(r.score)); const labels = rebuyData.map(r => r.label === '1.0' ? '是' : '否'); const option = { tooltip: { trigger: 'axis' }, legend: { data: ['预测评分'] }, xAxis: { type: 'category', data: labels }, yAxis: { type: 'value' }, series: [{ data: scores, type: 'bar' }] }; myChart.setOption(option); window.addEventListener('resize', function() { myChart.resize(); }); } $(document).ready(function() { loadRebuyData(); });不出预测图
06-17
<%@ page contentType="text/html; charset=UTF-8" import="jakarta.servlet.http.HttpSession" import="java.util.*" import="jakarta.servlet.http.HttpSession" import="jp.co.canon_soft.wp.runtime.util.*" import="security.MenuDisp" import="util.StringUtil" import="org.apache.commons.lang.*" import="jp.co.canon_soft.wp.runtime.AppContext" import="common.CommonMethod"%> <% String ctxPath = request.getContextPath(); String pAction = request.getParameter("action"); HttpSession ses = request.getSession(true); String userId = StringUtil.toString(ses.getAttribute("APP_USER")); Date sysLastLoginDateTime = (Date) ses.getAttribute("sysLastLoginDateTime"); String lastLoginTime = ""; //前回ログイン日時暦形式 if (sysLastLoginDateTime != null) { lastLoginTime = StringUtil.seirekiToWareki(sysLastLoginDateTime, StringUtil.WarekiFormat.LONG_DATETIME); } String strMenuNm6 = ""; String strMenuNm12 = ""; String strMenuNm14 = ""; String strNone = "none"; String strMenuDisp6 = strNone; String strMenuDisp12 = strNone; String strMenuDisp14 = strNone; String strRootUrl6 = ""; String strRootUrl12 = ""; String strRootUrl14 = ""; //表示メニュー情報取得 List<Map<String, Object>> resultList = MenuDisp.getGyoumuAndKanriMenu(userId); String userName = StringUtil.toString(resultList.get(0).get("氏名")); String userShozoku = StringUtil.toString(resultList.get(0).get("所属")); if (resultList.size() > 0) { ses.setAttribute("APP_USERNAME", resultList.get(0).get("氏名")); ses.setAttribute("APP_SHOZOKUNAME", resultList.get(0).get("所属")); for (int i = 0; i < resultList.size(); i++) { Map<String, Object> map = resultList.get(i); String menuOrder = StringUtil.toString(map.get("メニュー順")); String strMenuNm = StringUtil.toString(map.get("メニュー名称")); String strMenuId = StringUtil.toString(map.get("メニューID")); if ("PS".equals(strMenuId)) { strMenuNm14 = strMenuNm; strMenuDisp14 = ""; strRootUrl14 = strMenuId; } else { switch (menuOrder) { case "6" : strMenuNm6 = strMenuNm; strMenuDisp6 = ""; strRootUrl6 = strMenuId; break; case "12" : strMenuNm12 = strMenuNm; strMenuDisp12 = ""; strRootUrl12 = strMenuId; break; } } } } List<Map<String, Object>> infoList = CommonMethod.getInformation("CM"); %>我想将上面的代码放到servlet中 给我修改下
10-15
帮我把这里的java代码提出来 放在一个servlet中 <%@ page contentType="text/html; charset=UTF-8" import="jakarta.servlet.http.HttpSession" import="java.util.*" import="jakarta.servlet.http.HttpSession" import="jp.co.canon_soft.wp.runtime.util.*" import="security.MenuDisp" import="util.StringUtil" import="org.apache.commons.lang.*" import="jp.co.canon_soft.wp.runtime.AppContext" import="common.CommonMethod"%> <% String ctxPath = request.getContextPath(); String pAction = request.getParameter("action"); HttpSession ses = request.getSession(true); String userId = StringUtil.toString(ses.getAttribute("APP_USER")); Date sysLastLoginDateTime = (Date) ses.getAttribute("sysLastLoginDateTime"); String lastLoginTime = ""; //前回ログイン日時暦形式 if (sysLastLoginDateTime != null) { lastLoginTime = StringUtil.seirekiToWareki(sysLastLoginDateTime, StringUtil.WarekiFormat.LONG_DATETIME); } String strMenuNm6 = ""; String strMenuNm12 = ""; String strMenuNm14 = ""; String strNone = "none"; String strMenuDisp6 = strNone; String strMenuDisp12 = strNone; String strMenuDisp14 = strNone; String strRootUrl6 = ""; String strRootUrl12 = ""; String strRootUrl14 = ""; //表示メニュー情報取得 List<Map<String, Object>> resultList = MenuDisp.getGyoumuAndKanriMenu(userId); String userName = StringUtil.toString(resultList.get(0).get("氏名")); String userShozoku = StringUtil.toString(resultList.get(0).get("所属")); if (resultList.size() > 0) { ses.setAttribute("APP_USERNAME", resultList.get(0).get("氏名")); ses.setAttribute("APP_SHOZOKUNAME", resultList.get(0).get("所属")); for (int i = 0; i < resultList.size(); i++) { Map<String, Object> map = resultList.get(i); String menuOrder = StringUtil.toString(map.get("メニュー順")); String strMenuNm = StringUtil.toString(map.get("メニュー名称")); String strMenuId = StringUtil.toString(map.get("メニューID")); if ("PS".equals(strMenuId)) { strMenuNm14 = strMenuNm; strMenuDisp14 = ""; strRootUrl14 = strMenuId; } else { switch (menuOrder) { case "6" : strMenuNm6 = strMenuNm; strMenuDisp6 = ""; strRootUrl6 = strMenuId; break; case "12" : strMenuNm12 = strMenuNm; strMenuDisp12 = ""; strRootUrl12 = strMenuId; break; } } } } List<Map<String, Object>> infoList = CommonMethod.getInformation("CM"); %> <!DOCTYPE html> <html lang="ja"> <head> <meta charset="UTF-8"> <meta http-equiv="Pragma" content="no-cache"> <meta http-equiv="Content-Script-Type" content="text/javascript"> <meta http-equiv="Content-Style-Type" content="text/css"> <title>財務会計システム</title> <link rel="stylesheet" href="<%=ctxPath%>/style/global.css"> <link rel="stylesheet" href="<%=ctxPath%>/style/body_global.css"> <link rel="stylesheet" href="<%=ctxPath%>/style/login2.css"> <link rel="stylesheet" href="<%=ctxPath%>/font-awesome/css/font-awesome.css" /> <script src="<%=AppContext.getContextPath()%>/components/searchView/script/jquery-3.7.1.min.js" type="text/javascript"></script> <style> </style> </head> <% Date now = new Date(); String historicalTime = StringUtil.seirekiToWareki(now, StringUtil.WarekiFormat.SHORT_DATE); %> <body class="topBody"> <div class="topHeader topHeaderWide"> <div> <h1 class="topHeaderTitle">財務会計システム</h1> </div> <div class="topHeaderMenu"> <div id="downloadDiv" class="btnManual">マニュアル</div> <div class="btnLogout" onclick="login()">ログアウト</div> </div> <div class="topHeaderUserdata" id="divUserInfo"> <dl> <dt class="userOrganization" style="font-size: 16px;">所属</dt> <dd class="userOrganizationData"> <span style="font-size: 16px;"><%=userShozoku%></span> </dd> <dt class="userName" style="font-size: 16px;">氏名</dt> <dd class="userNameData"> <span style="font-size: 16px;"><%=userName%></span> </dd> </dl> </div> <div class="topHeaderDate"><%=historicalTime%></div> </div> <div class="topContainerWide" style="padding: 1px 0px;"> <div class="topContainerInner"> <div class="topContainerLogindate"> <span style="color: #148FC7; font-size: 12px;">前回ログイン日時:<%=lastLoginTime%></span> </div> <div class="topContainerColFlex"> <div class="topContainerCol" style="width: 49%;"> <h2>業務システム</h2> <div style="padding: 0; margin: 0; width: 100%;"> <div class="portalMenulist listCol2" style="float: left; width: 50%"> <div style="padding-left:15px;display:;width: max-content;<%=strMenuDisp6%>;" id="div表示メニュー6"> <a onclick="opensayibu('<%=strRootUrl6%>');" target='hgnew' id="hpl表示メニュー6"> <span class="right-icon">></span><span id="lbl表示メニュー6" style="font-size: 18px;"> <%=strMenuNm6%></span> </a> </div> </div> <div class="portalMenulist listCol2" style="float: left; width: 50%"> <div style="padding-left:100px;display:;width: max-content;<%=strMenuDisp12%>;" id="div表示メニュー12"> <a onclick="opensayibu('<%=strRootUrl12%>');" target='hgnew' id="hpl表示メニュー12" style="margin-left: -50px;"> <span class="right-icon">></span><span id="lbl表示メニュー12" style="font-size: 18px;"> <%=strMenuNm12%></span> </a> </div> </div> </div> </div> <div class="topContainerCol" style="width: 49%;"> <h2>管理</h2> <div class="portalMenulist listCol2" style="float: left; width: 50%"> <div style="margin-left: -122px;display:<%=strMenuDisp14%>;" id="div表示メニュー14"> <a onclick="opensayibu('<%=strRootUrl14%>');" target='hgnew' id="hpl表示メニュー14" style="margin-left: 166px;"> <span class="right-icon">></span><span id="lbl表示メニュー14" style="font-size: 18px;"> <%=strMenuNm14%></span> </a> </div> </div> </div> </div> <form name="myLogin" method="POST" action="<%=ctxPath%>/page/Login.jsp"> <input type="hidden" name="action" value="doMenulogin"> <input type="hidden" name="menuId" id="menuId" value=""> <div style="display: flex; gap: 20px; height: 130px;"></div> </form> <hr> <div> <h3>・お知らせ・</h3> </div> <div class="topContainerCautionBox" style="padding-right: 50px;"> <div class="topContainerCautionBox" style="overflow-y: auto; height: 120px; width: 100%; margin: 0;"> <table> <tr> <td></td> </tr> <% for (int i = 0; i < infoList.size(); i++) { Map<String, Object> map = infoList.get(i); String display = ("1".equals(map.get("優先フラグ"))) ? "" : "none"; %> <tr> <td><span class="warning-icon" style=" display:<%=display%>;">!</span></td> <td><%=map.get("お知らせ")%></td> </tr> <% } %> </table> </div> </div> <div class="cautionList" style="margin-left: 200px;"> <li>※財務会計システムでは誤作動防止のため、以下のブラウザ標準機能を制御しておりますのでご注意ください。 <br> ・マウス操作による右クリック・メニューが表示されません。<br> ・キーボードのBS(バックスペース)キーで前画面に戻れません。 </li> </div> <hr> </div> <div class="cautionList"> <div style="margin-right: 443px;"></div> </div> <div style="width: 100%; display: flex;"> <div style="width: 50%; text-align: left; margin-left: 50px; font-size: 13px"> Ver.1.0.0</div> <div style="width: 50%; text-align: right; margin-right: 50px; font-size: 13px"> 画面ID:CMM010DB</div> </div> </div> <script> /* * メニューIDに応じてサブ画面処理を開く */ function opensayibu(menuID) { const width = 1920; const height = 1080; const screenWidth = window.screen.width; const screenHeight = window.screen.height; let left = (screenWidth - width) / 2; let top = (screenHeight - height) / 2; document.getElementById("menuId").value = menuID; const origin = window.location.origin; // 該当パスを取得 const pathname = window.location.pathname; // プロジェクトを取得 const projectName = pathname.split('/')[1]; const newURL = origin + "/" + projectName + "/_link.do"; const childUrl = origin + "/" + projectName + "/_link.do"; openWindow = window.open('', 'hgnew', 'width=1920,height=1080,top=' + top + ',left=' + left + ',status=yes,resizable=yes,scrollbars=yes,toolbar=no'); const form = document.createElement('form'); form.method = 'POST'; form.action = newURL; form.target = 'hgnew'; if (menuID == "RS") { let input = document.createElement('input'); input.type = 'hidden'; input.name = 'SYSKBN'; input.value = 'RS'; form.appendChild(input); } else if (menuID == "KI") { let input = document.createElement('input'); input.type = 'hidden'; input.name = 'SYSKBN'; input.value = 'KI'; form.appendChild(input); } else if (menuID == "KS") { let input = document.createElement('input'); input.type = 'hidden'; input.name = 'SYSKBN'; input.value = 'KS'; form.appendChild(input); } else if (menuID == "DK") { let input = document.createElement('input'); input.type = 'hidden'; input.name = 'SYSKBN'; input.value = 'DK'; form.appendChild(input); } else if (menuID == "ZK") { let input = document.createElement('input'); input.type = 'hidden'; input.name = 'SYSKBN'; input.value = 'ZK'; form.appendChild(input); } else if (menuID == "PS") { let input = document.createElement('input'); input.type = 'hidden'; input.name = 'SYSKBN'; input.value = 'PS'; form.appendChild(input); } document.body.appendChild(form); form.submit(); document.body.removeChild(form); // 100ミリ秒間隔で子画面の状態を監視 const interval = setInterval(function() { // 子画面が閉じていたら if (!openWindow || openWindow.closed) { // Intervalを破棄 clearInterval(interval); } else { // 子画面にフォーカスを当てる if (!openWindow.document.hasFocus()) { openWindow.focus(); } } }, 100); } //マニュアルボタン押下プロセス const downloadDiv = document.getElementById('downloadDiv'); const resourceUrl = '/FinancialCoreSystem/file/manual.zip'; const notFoundUrl = '/FinancialCoreSystem/file/manual.zip'; const fileName = 'manual.zip'; downloadDiv.onclick = function () { fetch(resourceUrl, { method: 'HEAD' }) .then(response => { if (!response.ok) { window.location.href = notFoundUrl; return; } const a = document.createElement('a'); a.href = resourceUrl; a.download = fileName; document.body.appendChild(a); a.click(); document.body.removeChild(a); }) .catch(() => { window.location.href = notFoundUrl; }); }; //ログアウトボタン押下プロセス function login() { window.location.href = "/FinancialCoreSystem/page/login.jsp"; } </script> </body> </html>
10-15
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值