天天看點

技術幹貨|JSP(Java Server Pages) Web應用程式開發中的常見代碼用法

作者:運維木子李

#暑期創作大賽#

技術幹貨|JSP(Java Server Pages) Web應用程式開發中的常見代碼用法

建立一個JSP頁面:

<!DOCTYPE html>
<html>
<head>
    <title>My JSP Page</title>
</head>
<body>
    <h1>Welcome to my JSP page!</h1>
</body>
</html>           

在JSP頁面中使用Java代碼:

<% 
    String message = "Hello, JSP!";
    out.println(message);
%>           

在JSP頁面中使用JSTL标簽庫:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<c:set var="name" value="John" />
<c:if test="${name eq 'John'}">
    <p>Welcome, ${name}!</p>
</c:if>           

在JSP頁面中使用EL表達式:

<p>Today is ${today}</p>           

建立一個Servlet類:

@WebServlet("/hello")
public class HelloServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.getWriter().append("Hello, Servlet!");
    }
}           

在JSP頁面中引用Servlet:

<a href="${pageContext.request.contextPath}/hello">Click here</a> to say hello!           

擷取請求參數:

String name = request.getParameter("name");           

設定Session屬性:

request.getSession().setAttribute("username", "John");           

擷取Session屬性:

String username = (String) request.getSession().getAttribute("username");           

轉發請求到另一個頁面:

RequestDispatcher dispatcher = request.getRequestDispatcher("/anotherPage.jsp");
dispatcher.forward(request, response);           

重定向請求到另一個頁面:

response.sendRedirect("http://www.example.com");           

使用JDBC連接配接資料庫:

Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "username", "password");           

執行SQL查詢:

Statement statement = conn.createStatement();
ResultSet resultSet = statement.executeQuery("SELECT * FROM users");           

處理SQL查詢結果:

while (resultSet.next()) {
    String username = resultSet.getString("username");
    int age = resultSet.getInt("age");
    // 處理結果
}           

插入資料到資料庫:

PreparedStatement statement = conn.prepareStatement("INSERT INTO users (username, age) VALUES (?, ?)");
statement.setString(1, "John");
statement.setInt(2, 25);
statement.executeUpdate();           

更新資料庫中的資料:

PreparedStatement statement = conn.prepareStatement("UPDATE users SET age = ? WHERE username = ?");
statement.setInt(1, 30);
statement.setString(2, "John");
statement.executeUpdate();           

删除資料庫中的資料:

PreparedStatement statement = conn.prepareStatement("DELETE FROM users WHERE username = ?");
statement.setString(1, "John");
statement.executeUpdate();           

使用JSP自定義标簽庫:

<%@ taglib prefix="mytags" uri="/WEB-INF/mytags.tld" %>

<mytags:customTag />           

建立自定義JSP标簽:

public class CustomTag extends SimpleTagSupport {
    public void doTag() throws JspException, IOException {
        JspWriter out = getJspContext().getOut();
        out.println("This is a custom tag.");
    }
}           

在JSP頁面中使用自定義标簽:

<mytags:customTag />           

使用JSP表達式和腳本片段:

<%-- JSP表達式 --%>
<p>2 + 2 = <%= 2 + 2 %></p>

<%-- JSP腳本片段 --%>
<% int count = 0; %>           

在JSP頁面中使用條件語句:

JSP複制<% if (condition) { %>
    <p>This is true.</p>
<% } else { %>
    <p>This is false.</p>
<% } %>           

在JSP頁面中使用循環語句:

<% for (int i = 0; i < 5; i++) { %>
    <p>Iteration <%= i+1 %></p>
<% } %>           

在JSP頁面中處理異常:

<% try {
    // 代碼塊
    } catch (Exception e) {
        out.println("An error occurred: " + e.getMessage());
    }
%>           

在JSP頁面中使用包含檔案:

<%@ include file="header.jsp" %>           

在JSP頁面中使用JavaBean:

<jsp:useBean id="user" class="com.example.User" scope="request" />           

在JSP頁面中調用JavaBean的方法:

<p>Hello, <%= user.getName() %>!</p>           

使用JSP頁面重用片段:

<%@ include file="header.jsp" %>
<p>This is the content.</p>
<%@ include file="footer.jsp" %>           

在JSP頁面中設定響應頭:

<%
    response.setHeader("Content-Type", "text/plain");
    response.setHeader("Cache-Control", "no-cache");
%>           

在JSP頁面中擷取用戶端IP位址:

<%    String ipAddress = request.getRemoteAddr();%>           

在JSP頁面中處理表單送出:

<form action="processForm.jsp" method="post">
    <input type="text" name="name" />
    <input type="submit" value="Submit" />
</form>           

在JSP頁面中處理檔案上傳:

<form action="upload.jsp" method="post" enctype="multipart/form-data">
    <input type="file" name="file" />
    <input type="submit" value="Upload" />
</form>           

在JSP頁面中使用會話跟蹤:

<p>Your session ID is <%= session.getId() %></p>           

在JSP頁面中使用Cookie:

<%
    Cookie cookie = new Cookie("username", "John");
    response.addCookie(cookie);
%>           

在JSP頁面中重複使用片段:

<jsp:include page="common.jsp">
    <jsp:param name="name" value="John" />
</jsp:include>           

這些示例展示了JSP Web應用程式開發中的一些常見代碼用法,涵蓋了JSP頁面、Servlet、資料庫操作、自定義标簽和其他各種功能。實際開發中,根據具體需求可能會有更多的代碼邏輯和功能實作。

繼續閱讀