从一开始的网络编程(TCP编程对Socket进行监听,到HTTP编程),现在终于可以使用强大的API进行JavaEE编程了,Servlet底层封装了各种网络协议的处理,使我们不再深陷于对协议的编程,我们只需要处理请求和返回响应就行了。这次是个简单的用Servlet类来处理对用户的简单的增删改查,我们通过对实体类与数据库的映射来将数据传送到JSP页面上进行展示。
一、Jar包的引入
一开始使用Servlet编程时需要引入ServletAPI这个Jar包,但是我们是Web应用只需要将应用放在Tomcat服务器上运行就行了,而Tomcat里面继承了Servlet接口所以这边不再引入,我们只需要引入利于开发和调试内嵌式TomcatJar包以及Mysql的Jar包就可以:
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-core</artifactId>
<version>${tomcat.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<version>${tomcat.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.46</version>
</dependency>
二、Service层核心代码
这边我们使用的是纯JDBC编程啊:
public class UserService {
public static final String url = "jdbc:mysql://127.0.0.1:3306/test";
public static final String username = "root";
public static final String password = "root";
public User getUserById(int id) {
try(Connection connection = DriverManager.getConnection(url, username, password)){
try(PreparedStatement preparedStatement = connection.prepareStatement("select id, email, name, password from user where id = ?")){
preparedStatement.setObject(1, 1);
ResultSet rs = preparedStatement.executeQuery();
rs.next();
int id1 = rs.getInt("id");
String email = rs.getString("email");
System.out.println(email);
String name1 = rs.getString("name");
String password1 = rs.getString("password");
return new User(id1, email, name1, password1);
}
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return null;
}
public List<User> getAllOrderByAsc(int begin){
try(Connection connection = DriverManager.getConnection(url, username, password)){
try(PreparedStatement preparedStatement = connection.prepareStatement("select id, email, name, password from user order by id asc limit ?, 5")){
preparedStatement.setObject(1, begin);
ResultSet rs = preparedStatement.executeQuery();
List<User> list = new ArrayList<User>();
while(rs.next()) {
int id1 = rs.getInt("id");
String email = rs.getString("email");
System.out.println(email);
String name1 = rs.getString("name");
String password1 = rs.getString("password");
list.add(new User(id1, email, name1, password1));
}
return list;
}
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return null;
}
public void deleteById(int id){
try(Connection connection = DriverManager.getConnection(url, username, password)){
try(PreparedStatement preparedStatement = connection.prepareStatement("delete from user where id = ?")){
preparedStatement.setObject(1, id);
preparedStatement.execute();
}
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
三、Controller层设计
我们将入口返回到list进行列表的展示,然后通过点击删除等操作传入URL进行处理,处理后返回到list列表核心代码如下:
@WebServlet(urlPatterns = "/")
public class UserServlet extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
UserService userService = new UserService();
String pi = req.getParameter("begin");
int pageinfo = 0;
if(pi != null) {
pageinfo = Integer.valueOf(pi);
}
List<User> list = userService.getAllOrderByAsc(pageinfo);
req.setAttribute("users", list);
req.setAttribute("begin", pageinfo);
req.getRequestDispatcher("/WEB-INF/user.jsp").forward(req, resp);
}
}
@WebServlet(urlPatterns = "/deleteById")
public class UserDeleteServlet extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
int id = Integer.valueOf(req.getParameter("id"));
UserService userService = new UserService();
userService.deleteById(id);
resp.sendRedirect("/");
}
}
以上代码还进行了物理分页利用Sql语句在后端直接返回分页的行数。
四、JSP设计
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" import="java.util.*"%>
<%@page import="cn.pojo.*"%>
<%List<User> users = (List<User>)request.getAttribute("users"); %>
<%int begin = (int)request.getAttribute("begin")+5; %>
<%int end = (int)request.getAttribute("begin")-5; %>
<html>
<body>
<h1>Welcome to my first Web !</h1>
<table>
<tr>
<td>id</td>
<td>email</td>
<td>name</td>
<td>password</td>
<td>编辑</td>
<td>删除</td>
</tr>
<% for(User user : users){
out.print("<tr>");
out.print("<td>" + user.id + "</td>");
out.print("<td>" + user.email + "</td>");
out.print("<td>" + user.name + "</td>");
out.print("<td>" + user.password + "</td>");
out.print("<td>" + "编辑" + "</td>");
out.print("<td><a href = \"/deleteById?id="+ user.id +"\">" + "删除" + "</a></td>");
out.print("</tr>");
}
%>
</table>
<p><a href = "/?begin=<%= end %>">上一页</a> <a href = "/?begin=<%= begin %>">下一页</a></p>
</body>
</html>
五、内嵌式Tomcat启动服务器
public static void main(String[] args) throws LifecycleException {
// TODO Tomcat start at port: 8080
Tomcat tomcat = new Tomcat();
tomcat.setPort(Integer.getInteger("port", 8101));
tomcat.getConnector();
Context context = tomcat.addWebapp("", new File("src/main/webapp").getAbsolutePath());
WebResourceRoot resources = new StandardRoot(context);
resources.addPreResources(
new DirResourceSet(resources, "/WEB-INF/classes", new File("target/classes").getAbsolutePath(), "/"));
context.setResources(resources);
tomcat.start();
tomcat.getServer().await();
}
版权声明:本文为a1192900925原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。