JavaWeb项目查询数据库获得数据显示在jsp页面上

先来简单的例子吧。大概如下:index.jsp页面中只有一个按钮,用来跳转到Servlet操作数据,Servlet中对数据库查询操作后将信息保存在request对象中通过转发传递到showinfo.jsp页面(如果你对数据的操作也是在jsp中,java代码逻辑部分其实是一样的,注意跳转路径即可;用了@Controllor同理,跳转的逻辑也是一样的)

把数据库建好

CREATE TABLE `User` (
  `id` int(11) NOT NULL,
  `username` varchar(255) DEFAULT NULL,
  `password` varchar(255) DEFAULT NULL,
  `address` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) 

插入一个数据

insert into User values(1,"Martin","12345","zjut")

建立一个Dynamic Web Project,目录如下:

User.java

package com.entity;

public class User {
	private int id;
	private String username;
	private String password;
	private String address;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	@Override
	public String toString() {
		return "User [id=" + id + ", username=" + username + ", password=" + password + ", address=" + address + "]";
	}

	public User(int id, String username, String password, String address) {
		super();
		this.id = id;
		this.username = username;
		this.password = password;
		this.address = address;
	}

	public User() {
		super();
	}

}

DBHelper.java

package com.utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DBHelper {
	private static final String driver = "com.mysql.cj.jdbc.Driver";
	private static final String url = "jdbc:mysql://localhost:3306/webtest?useUnicode=true&characterEncoding=UTF-8";
	private static final String username = "root";
	private static final String password = "123456";
	
	private static Connection conn=null;
	
	static {
		try {
			Class.forName(driver);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
	
	public static Connection getConnection() {
		if(conn==null) {
			try {
				conn = DriverManager.getConnection(url,username,password);
				System.out.println("数据库初始化成功");
			} catch (SQLException e) {
				e.printStackTrace();
				System.out.println("数据库初始化失败");
			}
			return conn;
		}else {
			return conn;
		}
	}
	
}

 ServletDemo.java

package com.servlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

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.entity.User;
import com.utils.DBHelper;


@WebServlet("/servlet/ServletDemo")
public class ServletDemo extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public ServletDemo() {
        super();
    }


	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Connection conn = DBHelper.getConnection();
		String sql="select * from User";
		try {
			Statement st = conn.createStatement();
			ResultSet rs = st.executeQuery(sql);
			User user = new User();
			while(rs.next()) {
				user.setId(rs.getInt("id"));
				user.setUsername(rs.getString("username"));
				user.setPassword(rs.getString("password"));
				user.setAddress(rs.getString("address"));
			}
			//将数据库中查询到的信息封装在user对象中,use对象保存在request中,之后将通过request对象将数据传递到页面
			//需要的话也可以只传递一个参数request.setAttribute("id", user.getId());
			request.setAttribute("user", user);
			//这里是转发,从Servlet跳转到showinfo.jsp页面,并且带上request和response对象中原有的参数
			request.getRequestDispatcher("/showinfo.jsp").forward(request, response);
					
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}

这里用的是转发,可以保存request对象中的数据;至于重定向则是另外一个新的request,所以原有的数据会消失,在jsp获取不到。

 index.jsp,只一个按钮

<body>
<form action="servlet/ServletDemo" method="get">
  <input type="submit" >
</form>
</body>

showinfo.jsp,这里需要注意的是导入类:import="com.entity.User"

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" import="com.entity.User"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
User user = (User)request.getAttribute("user");
%>

id:<%=user.getId() %>
username:<%=user.getUsername() %>
password:<%=user.getPassword() %>
address:<%=user.getAddress() %>

<!-- 
也可以用el表达式,但是同样需要servlet先将值存放在request中,但是用el表达式的话需要在上面加上:
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
如下,获取id这样写就可以
${user.getId()}
 -->
</body>
</html>

启动tomcat操作点击按钮即可结果如下


ps:分界线以上是原创,以下是在某原博主的内容之后的补充

转载原文及源代码链接:https://blog.csdn.net/qq_23994787/article/details/73612870

 showall.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>  
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<base href="<%=basePath%>">
<title>所有用户页面</title>
</head>
<body>
<h1>${xiaoxi}</h1>
  <table  width="600" border="1" cellpadding="0" >
  		<tr>
  			<th>ID</th>
	  		<th>姓名</th>
	  		<th>性别</th>
	  		<th>密码</th>
	  		<th>家乡</th>
	  		<th>备注</th>
	  		<th>操作</th>
  		</tr>
     
	<c:forEach var="U" items="${userAll}" > 
	<form action="UpdateServlet" method="post">
       <tr>
	       <td><input type="text" value="${U.id}" name="id" ></td>
	       <td><input type="text" value="${U.name}" name="name"></td>
	       <td><input type="text" value="${U.sex}" name="sex"></td>
	       <td><input type="text" value="${U.pwd}" name="pwd"></td>
	       <td><input type="text" value="${U.home}" name="home"></td>
	       <td><input type="text" value="${U.info}" name="info"></td>
	       <td><a href="DeleteServlet?id=${U.id}">删除</a>  <input type="submit" value="更新"/></td>
	   </tr>
	</form>
    </c:forEach>  

     
    </table>

</body>
</html>

SearchAllServlet.java程序如下,导包之类的略

public class SearchAllServlet extends HttpServlet{

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request,response);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		UserDao ud = new UserDaoImpl();
		List<User> userAll = ud.getUserAll();
		request.setAttribute("userAll", userAll);
		request.getRequestDispatcher("/showall.jsp").forward(request, response);
	}
	
}

 

数据库查询到的所有用户数据保存在List集合userAll中,通过request.setAttribute("userAll",userAll)传入jsp

jsp通过<c:forEach var="U" items="${userAll}" >取出数据并进行遍历

以上,需要注意的是showall中用到了<c:forEach>标签,并且传值的时候使用了el表达式${...},因此还需要导入包jstl.jar和standard.jar并且在showall.jsp中增加:

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

发布了34 篇原创文章 · 获赞 57 · 访问量 9万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览