天天看点

技术干货|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、数据库操作、自定义标签和其他各种功能。实际开发中,根据具体需求可能会有更多的代码逻辑和功能实现。

继续阅读