记得3年前,初识javaee,当时给人的感觉就是,javascript+servlet+jdbc。现在看来仍然是这些,不知道以后会给人是什么感觉,会有不一样的吗?
一个简单的例子,回顾一下所谓的javaee的皮毛。
需求:一个简单的用户注册与登录
第一步,封装javabean。用户的注册与登录涉及到的属性有,id,name,password,email。简单的封装一下。
public class User {
private int id;
private String name;
private String password;
private String email;
public User() {
super();
}
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 getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", password=" + password + ", email=" + email + "]";
}
}
第二步,对外提供一个接口,用于业务逻辑的实现。
public interface UserDao {
// 保存用户对象
void save(User user);
// 根据用户名查询用户
User getUserByName(String name);
// 查询所用用户
List<User> getAllUser();
}
第三步,JDBC的实现,需要db.properties与jar包的支撑
public class UserDaoImpl implements UserDao {
/**
* 保存用户
*/
@Override
public void save(User user) {
// 获得连接
Connection conn = JDBCUtils.getConnection();
// 准备sql
String sql = " INSERT INTO " + " `user`.`management` (`name`, `password`, `email`)"
+ " VALUES " + " (?, ?, ?) ";
// 获得PrepareStatement对象
PreparedStatement ps = null;
try {
ps = conn.prepareStatement(sql);
// 设置参数
ps.setString(1, user.getName());
ps.setString(2, user.getPassword());
ps.setString(3, user.getEmail());
// 执行sql
int result = ps.executeUpdate();
if (result != 1) {
throw new RuntimeException("保存用户失败!");
}
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException("保存用户失败!");
} finally {
// 关闭资源
JDBCUtils.close(conn, ps, null);
}
}
/**
* 根据用户名查询用户
*/
@Override
public User getUserByName(String name) {
// 获取连接
Connection conn = JDBCUtils.getConnection();
// 书写sql
String sql = "select * from management where name=?";
// 获得PrepareStatement
PreparedStatement ps = null;
User user = null;
ResultSet rs = null;
try {
ps = conn.prepareStatement(sql);
// 设置参数
ps.setString(1, name);
// 执行查询
rs = ps.executeQuery();
// 将结果集中的信息封装到User对象中
if (rs.next()) {
// 有数据
user = new User();
user.setId(rs.getInt("id"));
user.setName(rs.getString("name"));
user.setPassword(rs.getString("password"));
user.setEmail(rs.getString("email"));
}
return user;
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException("查询用户失败!");
} finally {
// 关闭资源
JDBCUtils.close(conn, ps, rs);
}
}
/**
* 获取所用用户
*/
@Override
public List<User> getAllUser() {
List<User> list = new ArrayList<User>();
//1 获得连接
Connection conn = JDBCUtils.getConnection();
//2 书写sql
String sql = "select * from management ";
PreparedStatement ps = null;
ResultSet rs = null;
try {
//3 获得PrepareStatement
ps = conn.prepareStatement(sql);
//4 执行查询
rs = ps.executeQuery();
//6 将结果集中的信息封装到User对象中
while(rs.next()){
//有数据
User u = new User();
u.setId(rs.getInt("id"));
u.setName(rs.getString("name"));
u.setPassword(rs.getString("password"));
u.setEmail(rs.getString("email"));
list.add(u);
}
return list;
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException("查询用户列表失败!");
}finally{
//7 关闭资源, 返回User
JDBCUtils.close(conn, ps, rs);
}
}
}
第四步,编写regiser.jsp与login.jsp就是简单的表单
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!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=ISO-8859-1">
<title>注冊</title>
</head>
<body>
<form action="/management/RegistServlet" method="post" name="form1" >
<table border="1" width="30%" >
<tr>
<th colspan="2" align="center" >
用户注册
</th>
</tr>
<tr>
<td>用户名:</td>
<td><input type="text" name="name" /><font color="red" >${requestScope.errors.name}</font></td>
</tr>
<tr>
<td>密码:</td>
<td><input type="password" name="password" /><font color="red" >${requestScope.errors.password}</font></td>
</tr>
<tr>
<td>邮箱:</td>
<td><input type="text" name="email" /><font color="red" ></font></td>
</tr>
<tr>
<td colspan="2" align="center" >
<input type="submit" value="注册" />
</td>
</tr>
</table>
</form>
<font color="red">${requestScope.error }</font>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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>登录</title>
</head>
<body>
<form action="/management/LoginServlet" method="post" name="form1" >
<table border="1" width="30%" >
<tr>
<th colspan="2" align="center" >
用户登录
</th>
</tr>
<tr>
<td>用户名:</td>
<td><input type="text" name="name" /><font color="red" >${requestScope.errors.name}</font></td>
</tr>
<tr>
<td>密码:</td>
<td><input type="password" name="password" /><font color="red" >${requestScope.errors.password}</font></td>
</tr>
<tr>
<td colspan="2" align="center" >
<input type="submit" value="登录" />
</td>
</tr>
</table>
</form>
<font color="red">${requestScope.error }</font>
</body>
</html>
第五步,编写一个UserService,用于根据User的业务逻辑
public class UserService {
public void regist(User user) {
UserDao dao = new UserDaoImpl();
User u = dao.getUserByName(user.getName());
if (u != null) {
throw new RuntimeException("用户名已存在!");
}
dao.save(user);
}
public User login(User user) {
UserDao dao = new UserDaoImpl();
User u = dao.getUserByName(user.getName());
// 用户名不存在
if (u == null) {
throw new RuntimeException("用户名不存在");
}
// 密码错误
if (!u.getPassword().equals(user.getPassword())) {
throw new RuntimeException("密码错误");
}
return u;
}
public List<User> getAllUser() {
UserDao ud = new UserDaoImpl();
return ud.getAllUser();
}
}
第六步,RegisterServlet的实现
/**
* Servlet implementation class RegistServlet
*/
@WebServlet("/RegistServlet")
public class RegistServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public RegistServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
// response.getWriter().append("Served at: ").append(request.getContextPath());
User user = new User();
// 封装参数到User对象中
try {
BeanUtils.populate(user, request.getParameterMap());
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
// 校验
Map<String, String> errors = CheckUtils.checkUser(user);
if(errors.size()>0){
// 有错误
request.setAttribute("errors", errors);
request.getRequestDispatcher("/regist.jsp").forward(request, response);
return;
}
// 调用Service保存
UserService service = new UserService();
try {
service.regist(user);
} catch (Exception e) {
e.printStackTrace();
request.setAttribute("error", e.getMessage());
request.getRequestDispatcher("/regist.jsp").forward(request, response);
return;
}
// 跳转到登录页面
response.sendRedirect(request.getContextPath()+"/login.jsp");
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
第七步,LoginServlet的实现
/**
* Servlet implementation class LoginServlet
*/
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public LoginServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
User user = new User();
try {
BeanUtils.populate(user, request.getParameterMap());
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
Map<String, String> errors = CheckUtils.checkUser(user);
if(errors.size()>0){
request.setAttribute("errors", errors);
request.getRequestDispatcher("/login.jsp").forward(request, response);
return;
}
// 调用UserService
UserService us = new UserService();
try {
us.login(user);
} catch (Exception e) {
e.printStackTrace();
request.setAttribute("error", e.getMessage());
request.getRequestDispatcher("/login.jsp").forward(request, response);
return;
}
// 向session中加入登录标识
request.getSession().setAttribute("user", user);
// 重定向的ListServlet
response.sendRedirect(request.getContextPath()+"/ListServlet");
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
第八步,LogoutServlet的实现
/**
* Servlet implementation class LogoutServlet
*/
@WebServlet("/LogoutServlet")
public class LogoutServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public LogoutServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setCharacterEncoding("utf-8");
// 1 销毁session
request.getSession().invalidate();
// 2 重定向到登录页面
response.sendRedirect(request.getContextPath() + "/login.jsp");
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
第九步,用户的展示ListServlet
/**
* Servlet implementation class ListServlet
*/
@WebServlet("/ListServlet")
public class ListServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public ListServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setCharacterEncoding("UTF-8");
//1 校验用户是否登录
User u = (User) request.getSession().getAttribute("user");
//未登录=> 重定向到登录页面
if(u==null){
response.sendRedirect(request.getContextPath()+"/login.jsp");
return;
}
//2 调用Service查询用户列表.
UserService us = new UserService();
List<User> list = us.getAllUser();
//3将用户列表放入request域,转发到列表页面
request.setAttribute("list", list);
request.getRequestDispatcher("/WEB-INF/page/list.jsp").forward(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}