1. 首页 > IT综合教程 > 正文

it教程FG174-Java Web开发基础

1. Java Web开发概述

Java Web开发是使用Java技术构建Web应用程序的过程,主要涉及Servlet、JSP、过滤器、监听器等技术。Java Web应用通常运行在Web容器(如Tomcat、Jetty)中。更多学习教程www.fgedu.net.cn

生产环境风哥建议:选择稳定的Web容器版本,如Tomcat 9或Tomcat 10,确保与Java版本兼容。

2. Servlet基础

Servlet是Java Web的核心组件,用于处理HTTP请求和响应。

// 第一个Servlet
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;

public class HelloServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType(“text/html;charset=UTF-8”);
PrintWriter out = response.getWriter();
out.println(““);
out.println(“Hello Servlet“);
out.println(“”);
out.println(“

Hello, Servlet!

“);
out.println(“”);
out.close();
}
}





HelloServlet
HelloServlet


HelloServlet
/hello

3. JSP技术

JSP(JavaServer Pages)是一种动态网页技术,允许在HTML中嵌入Java代码。学习交流加群风哥微信: itpux-com


<%@ page contentType="text/html;charset=UTF-8" language="java" %>


Hello JSP

Hello, JSP!

<% String name = request.getParameter("name"); if (name == null) { name = "World"; } %>

Welcome, <%= name %>!

Current time: <%= new java.util.Date() %>

风哥风哥提示:在实际开发中,建议使用EL表达式和JSTL标签库替代直接在JSP中嵌入Java代码,提高代码的可维护性。

4. Filter和Listener

Filter用于拦截HTTP请求和响应,Listener用于监听Web应用的生命周期事件。

// 字符编码过滤器
import javax.servlet.*;
import java.io.IOException;

public class CharacterEncodingFilter implements Filter {
private String encoding;

@Override
public void init(FilterConfig filterConfig) throws ServletException {
encoding = filterConfig.getInitParameter(“encoding”);
if (encoding == null) {
encoding = “UTF-8”;
}
}

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
request.setCharacterEncoding(encoding);
response.setCharacterEncoding(encoding);
chain.doFilter(request, response);
}

@Override
public void destroy() {
}
}

// 上下文监听器
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class MyContextListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
System.out.println(“Web application initialized”);
// 初始化操作,如加载配置文件、连接池等
}

@Override
public void contextDestroyed(ServletContextEvent sce) {
System.out.println(“Web application destroyed”);
// 清理操作,如关闭连接池等
}
}

5. JDBC数据库操作

JDBC(Java Database Connectivity)是Java访问数据库的标准API。学习交流加群风哥QQ113257174

import java.sql.*;

public class JdbcExample {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;

try {
// 加载驱动
Class.forName(“com.mysql.cj.jdbc.Driver”);

// 建立连接
conn = DriverManager.getConnection(
“jdbc:mysql://fgedudb:3306/test”,
“root”,
“password”
);

// 创建Statement
stmt = conn.createStatement();

// 执行查询
rs = stmt.executeQuery(“SELECT * FROM users”);

// 处理结果集
while (rs.next()) {
int id = rs.getInt(“id”);
String name = rs.getString(“name”);
String email = rs.getString(“email”);
System.out.println(“ID: ” + id + “, Name: ” + name + “, Email: ” + email);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 关闭资源
try {
if (rs != null) rs.close();
if (stmt != null) stmt.close();
if (conn != null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}

6. MVC设计模式

MVC(Model-View-Controller)是一种软件设计模式,用于分离应用程序的业务逻辑、数据和界面。

// Model
public class User {
private int id;
private String name;
private String email;

// 构造方法、getter和setter方法
public User() {}

public User(int id, String name, String email) {
this.id = id;
this.name = name;
this.email = email;
}

// getter和setter方法
public int getId() { return id; }
public void setId(int id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getEmail() { return email; }
public void setEmail(String email) { this.email = email; }
}

// Controller
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;

public class UserController extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 模拟获取用户数据
User user = new User(1, “John Doe”, “john@fgedu.net.cn”);

// 将数据设置到请求属性
request.setAttribute(“user”, user);

// 转发到视图
RequestDispatcher dispatcher = request.getRequestDispatcher(“user.jsp”);
dispatcher.forward(request, response);
}
}

// View (user.jsp)
<%@ page contentType="text/html;charset=UTF-8" language="java" %>


User Detail

User Detail

ID: ${user.id}

Name: ${user.name}

Email: ${user.email}

7. Servlet容器配置

Servlet容器(如Tomcat)需要正确配置以支持Java Web应用的运行。更多学习教程公众号风哥教程itpux_com

# 安装Tomcat 9
# wget https://archive.apache.org/dist/tomcat/tomcat-9/v9.0.85/bin/apache-tomcat-9.0.85.tar.gz
# tar -zxvf apache-tomcat-9.0.85.tar.gz -C /usr/local/
# ln -s /usr/local/apache-tomcat-9.0.85 /usr/local/tomcat

# 配置环境变量
# vi /etc/profile
export CATALINA_HOME=/usr/local/tomcat
export PATH=$CATALINA_HOME/bin:$PATH

# 启动Tomcat
# $CATALINA_HOME/bin/startup.sh

# 查看Tomcat状态
# ps aux | grep tomcat

# 访问Tomcat管理界面
# 浏览器访问: http://fgedudb:8080

8. Web应用安全

Web应用安全是Java Web开发的重要组成部分,包括认证、授权、防止SQL注入等。

// 防止SQL注入示例
import java.sql.*;

public class SecureJdbcExample {
public static void getUserById(int id) {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;

try {
// 加载驱动
Class.forName(“com.mysql.cj.jdbc.Driver”);

// 建立连接
conn = DriverManager.getConnection(
“jdbc:mysql://fgedudb:3306/test”,
“root”,
“password”
);

// 使用PreparedStatement防止SQL注入
String sql = “SELECT * FROM users WHERE id = ?”;
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, id);

// 执行查询
rs = pstmt.executeQuery();

// 处理结果集
while (rs.next()) {
System.out.println(“ID: ” + rs.getInt(“id”) + “, Name: ” + rs.getString(“name”));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 关闭资源
try {
if (rs != null) rs.close();
if (pstmt != null) pstmt.close();
if (conn != null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}

生产环境风哥建议:使用HTTPS协议加密传输数据,实现强密码策略,定期更新依赖库以修复安全漏洞。

9. Web开发最佳实践

Java Web开发的最佳实践包括代码组织、性能优化、错误处理等方面。

// 代码组织示例
/src
/main
/java
/com
/example
/controller // 控制器
/service // 业务逻辑
/dao // 数据访问
/model // 数据模型
/util // 工具类
/webapp
/WEB-INF
/classes // 编译后的类
/lib // 依赖库
web.xml // 配置文件
/css // 样式文件
/js // JavaScript文件
/images // 图片文件
index.jsp // 首页

10. Java Web框架简介

Java Web框架可以简化开发过程,提高开发效率,常用的框架包括Spring MVC、Struts2、JSF等。author:www.itpux.com







// Spring MVC控制器示例
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class HelloController {

@GetMapping(“/hello”)
public String hello(@RequestParam(name = “name”, defaultValue = “World”) String name, Model model) {
model.addAttribute(“name”, name);
return “hello”;
}
}

风哥风哥提示:选择合适的Java Web框架可以大大提高开发效率,Spring MVC是目前最流行的Java Web框架之一。

生产环境风哥建议:使用Spring Boot简化配置,集成Spring Security处理安全问题,使用Spring Data JPA简化数据库操作。

本文由风哥教程整理发布,仅用于学习测试使用,转载注明出处:http://www.fgedu.net.cn/10327.html

联系我们

在线咨询:点击这里给我发消息

微信号:itpux-com

工作日:9:30-18:30,节假日休息