解决服务端接收数据乱码问题。服务器默认采用 ISO8859-1 编码响应内容。
// 1req.setCharacterEncoding("utf-8");// 2 byte[] bytes = req.getParameter("username").getBytes("iso-8859-1"); System.out.println("username:" + new String(bytes,0,bytes.length,"utf-8"));
解决服务端发送到客户端数据乱码问题。
// 1 text/html,响应数据类型; resp.setContentType("text/html;charset=utf8;"); // 2 resp.setCharacterEncoding("utf-8"); resp.setHeader("Content-type","text/html;charset=utf8");
单元测试。
src 同级目录创建 test 文件夹,右键 -> Mark Directory as ->Sources Root,文件名采用测试的模块名 + Test。
转发。转发的作用在服务器端,将请求发送给服务器上的其他资源,以共同完成一次请求的处理。使用forward跳转时,是在服务器内部跳转,地址栏不发生变化,属于同一次请求。
request.getRequestDispatcher(“/目标URL-pattern”).forward(request, response);// 存数据request.setAttribute(key,value);// 取数据request.getAttribute(key);
重定向。重定向作用在客户端,客户端将请求发送给服务器后,服务器响应给客户端一个新的请求地址,客户端重新发送新请求。
重定向可以指向任何的资源,包括当前应用程序中的其他资源、同一个站点上的其他应用程序中的资源、其他站点的资源。
response.sendRedirect(“目标URI”);// 带数据response.sendRedirect(“目标URI?username=tom&ps=123”);// 接收数据request.getParameter(“username”);
servlet 用户管理系统。
目录结构。
public class AddUserServlet extends HttpServlet { private IUserService userService = new UserServiceImpl(); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("utf-8"); resp.setContentType("text/html;charset=utf8"); String username = req.getParameter("username"); String password = req.getParameter("password"); String age = req.getParameter("age"); String sex = req.getParameter("sex"); User user = new User(); user.setUsername(username); user.setPassword(password); user.setAge(Integer.valueOf(age)); user.setSex(Integer.valueOf(sex)); int i = userService.AddUser(user); if (i == 0) { resp.getWriter().write("添加失败"); } else { resp.getWriter().write("添加成功"); resp.getWriter().write("查询所有用户"); } }}public class DeleteUserServlet extends HttpServlet { private IUserService userService = new UserServiceImpl(); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("utf-8"); resp.setContentType("text/html;charset=utf8"); String username = req.getParameter("username"); int i = userService.DeleteUser(username); if (i == 0) { resp.getWriter().write("删除失败"); } else { resp.getWriter().write("删除成功"); resp.getWriter().write("查询所有用户"); } }}public class GetUserListServlet extends HttpServlet { private IUserService userService = new UserServiceImpl(); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("utf-8"); resp.setContentType("text/html;charset=utf8"); System.out.println("查询所有的用户:" + req); List userList = userService.getUserList(); // 转发数据 req.setAttribute("userList",userList); // 转发对象 req.getRequestDispatcher("ViewUserServlet").forward(req,resp); // 重定向 最好不带参数 resp.sendRedirect("ViewUserServlet?username=zs&password=123"); resp.sendRedirect("http://www.baidu.com"); }}public class LoginUserServlet extends HttpServlet { private IUserService userService = new UserServiceImpl(); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("utf-8"); resp.setContentType("text/html;charset=utf8"); String username = req.getParameter("username"); String password = req.getParameter("password"); User user = userService.login(username, password); if (user == null) { resp.getWriter().write("用户名或密码错误.."); } else { resp.getWriter().write("欢迎【" + req.getRemoteAddr() + username + "】登陆"); resp.getWriter().write("查询所有用户"); } }}public class SelectUserServlet extends HttpServlet { private IUserService userService = new UserServiceImpl(); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("utf-8"); resp.setContentType("text/html;charset=utf8"); System.out.println("查询所有的用户:" + req); String username = req.getParameter("username"); User user = userService.SelectUser(username); StringBuffer buffer = new StringBuffer(); buffer.append(""); buffer.append(""); buffer.append("
");
buffer.append(""); buffer.append("ID");
buffer.append("用户名");
buffer.append("密码");
buffer.append("年龄");
buffer.append("性别");
buffer.append("
");
if (user != null) {
buffer.append(""); buffer.append("" + user.getId() + "");
buffer.append("" + user.getUsername() + "");
buffer.append("" + user.getPassword() + "");
buffer.append("" + user.getAge() + "");
buffer.append("" + user.getSex() + "");
buffer.append("
");
}
buffer.append("
"); buffer.append(""); buffer.append(""); buffer.append("查询所有用户"); resp.getWriter().write(buffer.toString()); }}public class UpdateUserServlet extends HttpServlet { private IUserService userService = new UserServiceImpl(); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("utf-8"); resp.setContentType("text/html;charset=utf8"); String username = req.getParameter("username"); String password = req.getParameter("password"); String age = req.getParameter("age"); String sex = req.getParameter("sex"); User user = new User(); user.setUsername(username); user.setPassword(password); user.setAge(Integer.valueOf(age)); user.setSex(Integer.valueOf(sex)); int i = userService.UpdateUser(user); if (i == 0) { resp.getWriter().write("更新失败"); } else { resp.getWriter().write("更新成功"); resp.getWriter().write("查询所有用户"); } }}public class ViewUserServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("展示所有的用户:" + req); resp.setContentType("text/html;charset=utf8"); System.out.println("username:" + req.getParameter("username")); List userList = (List) req.getAttribute("userList"); StringBuffer buffer = new StringBuffer(); buffer.append(""); buffer.append(""); buffer.append("
");
buffer.append(""); buffer.append("ID");
buffer.append("用户名");
buffer.append("密码");
buffer.append("年龄");
buffer.append("性别");
buffer.append("
");
if (userList != null) {
for (User user: userList) {
buffer.append(""); buffer.append("" + user.getId() + "");
buffer.append("" + user.getUsername() + "");
buffer.append("" + user.getPassword() + "");
buffer.append("" + user.getAge() + "");
buffer.append("" + user.getSex() + "");
buffer.append("
");
}
}
buffer.append("
"); buffer.append(""); buffer.append(""); resp.getWriter().write(buffer.toString()); }}
public interface IUserDao { public User login(String username); public ListgetUserList(); public int AddUser(User user); public int DeleteUser(String name); public int UpdateUser(User user); public User SelectUser(String name);}public class UserDaoImpl implements IUserDao { @Override public User login(String username) { String sql = "select * from t_user where username = ?"; List users = DaoUtils.commonQuery(sql, User.class, username); if (users.isEmpty()) { return null; } return users.get(0); } @Override public ListgetUserList() { return DaoUtils.commonQuery("select * from t_user", User.class); } @Override public int AddUser(User user) { List userList = getUserList(); // 存在同名 for (User subUser: userList) { if (subUser.getUsername().equals(user.getUsername())) { return 0; } } String sql = "insert into t_user(username, password, age, sex) value(?, ?, ?, ?)"; int i = DaoUtils.commonUpdate(sql, user.getUsername(),user.getPassword(), user.getAge(),user.getSex()); return i; } @Override public int DeleteUser(String username) { String sql = "delete from t_user where username = ?"; int i = DaoUtils.commonUpdate(sql, username); return i; } @Override public int UpdateUser(User user) { String sql = "update t_user set password=?,age=?,sex=? where username = ?"; int i = DaoUtils.commonUpdate(sql,user.getPassword(),user.getAge(),user.getSex(),user.getUsername()); return i; } public User SelectUser(String name) { List users = DaoUtils.commonQuery("select * from t_user where username = ?", User.class, name); if (users.isEmpty()) { return null; } return users.get(0); }}
@Datapublic class User { private Integer id; private String username; private String password; private Integer age; private Integer sex;}
public interface IUserService { public User login(String username, String password); public ListgetUserList(); public int AddUser(User user); public int DeleteUser(String name); public int UpdateUser(User user); public User SelectUser(String name);}public class UserServiceImpl implements IUserService { private IUserDao userDao = new UserDaoImpl(); @Override public User login(String username, String password) { User user = userDao.login(username); if (user == null) { System.out.println("用户名或密码错误"); return null; } if (!user.getPassword().equals(password)) { System.out.println("用户名或密码错误"); return null; } return user; } @Override public ListgetUserList() { return userDao.getUserList(); } public int AddUser(User user) { return userDao.AddUser(user); } public int DeleteUser(String name) { return userDao.DeleteUser(name); } public int UpdateUser(User user) { return userDao.UpdateUser(user); } public User SelectUser(String name) { return userDao.SelectUser(name); }}
public class DaoUtils { // 更改 public static int commonUpdate(String sql, Object ...args) { Connection connection = DBUtils.getConnection(); PreparedStatement prst = null; try { prst = connection.prepareStatement(sql); if (args != null && args.length > 0) { for (int i = 0; i < args.length; i ++) { prst.setObject(i + 1,args[i]); } } return prst.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally { DBUtils.close(prst); } return 0; } // 查询 public static ListcommonQuery(String sql, Class cls, Object ...args) { Connection connection = DBUtils.getConnection(); PreparedStatement prst = null; ResultSet resultSet = null; List list = new ArrayList<>(); try { prst = connection.prepareStatement(sql); if (args != null && args.length > 0) { for (int i = 0; i < args.length; i ++) { prst.setObject(i + 1,args[i]); } } resultSet = prst.executeQuery(); while (resultSet.next()) { T t = cls.newInstance(); Field[] fields = cls.getDeclaredFields(); for (Field field: fields) { // 设置动态给属性赋值权限 field.setAccessible(true); Object value = null; try { value = resultSet.getObject(field.getName()); } catch (SQLException e) { // 出现实体字段和数据库字段不一致 String columnName = DBUtils.getProperties().getProperty(field.getName()); value = resultSet.getObject(columnName); } field.set(t, value); } list.add(t); } } catch (SQLException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } finally { DBUtils.close(resultSet, prst); } return list; }}
public class DBUtils { private static DataSource dataSource = null; private static Properties properties = new Properties(); private static ThreadLocal threadLocal = new ThreadLocal<>(); static { try { properties.load(DBUtils.class.getClassLoader().getResourceAsStream("jdbc.properties")); dataSource = DruidDataSourceFactory.createDataSource(properties); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } public static Properties getProperties() { return properties; } public static Connection getConnection() { Connection connection = threadLocal.get(); if (connection == null) { try { connection = dataSource.getConnection(); threadLocal.set(connection); } catch (SQLException e) { e.printStackTrace(); } } return connection; } public static void close(AutoCloseable ...args) { for (AutoCloseable obj: args) { if (obj != null) { try { obj.close(); } catch (Exception e) { e.printStackTrace(); } } } }}
# jdbc.properties#连接设置driverClassName=com.mysql.cj.jdbc.Driverurl=jdbc:mysql://localhost:3306/mydb1?characterEncoding=utf-8username=rootpassword=Liu01234#初始化可连接数量,实际项目时要设置更大值initialSize=100#最大连接数量maxActive=500#最小空闲连接,当空闲连接小于此值时会开辟新当空间,直到最大连接数量minIdle=50#超时等待时间以毫秒为单位 1000等于1秒maxWait=5000
<?xml version="1.0" encoding="UTF-8"?><web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5"> <servlet> <servlet-name>LoginUserServletservlet-name> <servlet-class>com.baidu.day.test1.controller.LoginUserServletservlet-class> servlet> <servlet-mapping> <servlet-name>LoginUserServletservlet-name> <url-pattern>/LoginUserServleturl-pattern> servlet-mapping> <servlet> <servlet-name>GetUserListServletservlet-name> <servlet-class>com.baidu.day.test1.controller.GetUserListServletservlet-class> servlet> <servlet-mapping> <servlet-name>GetUserListServletservlet-name> <url-pattern>/GetUserListServleturl-pattern> servlet-mapping> <servlet> <servlet-name>ViewUserServletservlet-name> <servlet-class>com.baidu.day.test1.controller.ViewUserServletservlet-class> servlet> <servlet-mapping> <servlet-name>ViewUserServletservlet-name> <url-pattern>/ViewUserServleturl-pattern> servlet-mapping> <servlet> <servlet-name>AddUserServletservlet-name> <servlet-class>com.baidu.day.test1.controller.AddUserServletservlet-class> servlet> <servlet-mapping> <servlet-name>AddUserServletservlet-name> <url-pattern>/AddUserServleturl-pattern> servlet-mapping> <servlet> <servlet-name>DeleteUserServletservlet-name> <servlet-class>com.baidu.day.test1.controller.DeleteUserServletservlet-class> servlet> <servlet-mapping> <servlet-name>DeleteUserServletservlet-name> <url-pattern>/DeleteUserServleturl-pattern> servlet-mapping> <servlet> <servlet-name>UpdateUserServletservlet-name> <servlet-class>com.baidu.day.test1.controller.UpdateUserServletservlet-class> servlet> <servlet-mapping> <servlet-name>UpdateUserServletservlet-name> <url-pattern>/UpdateUserServleturl-pattern> servlet-mapping> <servlet> <servlet-name>SelectUserServletservlet-name> <servlet-class>com.baidu.day.test1.controller.SelectUserServletservlet-class> servlet> <servlet-mapping> <servlet-name>SelectUserServletservlet-name> <url-pattern>/SelectUserServleturl-pattern> servlet-mapping>web-app>
<%-- index.jsp --%><%@ page contentType="text/html;charset=UTF-8" language="java" %><html> <head> <title>$Title$title> head> <body> <form method="post" action="LoginUserServlet"> username:<input type="text" name="username" value="zs"><br><br> password:<input type="text" name="password" value="123"><br><br> <input type="submit" value="登陆"> form> <br><br> <form method="post" action="AddUserServlet"> username:<input type="text" name="username" value="zs"><br><br> password:<input type="text" name="password" value="123"><br><br> age:<input type="text" name="age" value="12"><br><br> sex:<input type="text" name="sex" value="1"><br><br> <input type="submit" value="添加用户"> form> <br><br> <form method="post" action="DeleteUserServlet"> username:<input type="text" name="username" value="zs"><br><br> <input type="submit" value="删除用户"> form> <br><br> <form method="post" action="SelectUserServlet"> username:<input type="text" name="username" value="zs"><br><br> <input type="submit" value="查询用户"> form> <br><br> <form method="post" action="UpdateUserServlet"> username:<input type="text" name="username" value="zs"><br><br> password:<input type="text" name="password" value="123"><br><br> age:<input type="text" name="age" value="12"><br><br> sex:<input type="text" name="sex" value="1"><br><br> <input type="submit" value="修改用户"> form> <br><br> body>html>