1.Filter
Filter:过滤器,用来过滤网站的数据
- 处理中文乱码
- 登录验证。。。
Filter开发步骤:
1.实现接口并重写方法
package com.kuang.filter;
import javax.servlet.*;
import java.io.IOException;
/*
* filterChain的作用:
* 过滤执行中的代码,在过滤特定请求的时候都会执行
* 必须要让过滤器继续执行
*
* */
public class CharacterEncodingFilter implements Filter {
@Override
//web服务器启动,就已经初始化了,随时等待过滤对象出现
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("CharacterEncodingFilter初始化");
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
servletRequest.setCharacterEncoding("utf-8");
servletResponse.setCharacterEncoding("utf-8");
servletResponse.setContentType("text/html;charset=utf-8");
System.out.println("CharacterEncodingFilter执行前。。。。");
filterChain.doFilter(servletRequest,servletResponse);//让我们的请求继续走,如果不写,程序到这里就被拦截停止
System.out.println("CharacterEncodingFilter执行后。。。。");
}
@Override
//web服务器关闭的时候,过滤会销毁
public void destroy() {
System.out.println("CharacterEncodingFilter销毁");
}
}
2.在web.xml中配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<servlet>
<servlet-name>ShowServlet</servlet-name>
<servlet-class>com.kuang.servlet.ShowServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ShowServlet</servlet-name>
<url-pattern>/servlet/show</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>ShowServlet</servlet-name>
<url-pattern>/show</url-pattern>
</servlet-mapping>
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>com.kuang.filter.CharacterEncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/servlet/*</url-pattern>
</filter-mapping>
<listener>
<listener-class>com.kuang.listener.OnlineCountListener</listener-class>
</listener>
<session-config>
<session-timeout>1</session-timeout>
</session-config>
</web-app>
2.监听器
开发步骤
1.实现接口并重写方法
package com.kuang.listener;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
public class OnlineCountListener implements HttpSessionListener {
@Override
public void sessionCreated(HttpSessionEvent se) {
System.out.println(se.getSession().getId());
ServletContext ctx = se.getSession().getServletContext();
Integer onlineCount = (Integer)ctx.getAttribute("OnlineCount");
if (onlineCount == null){
onlineCount = new Integer(1);
}else {
int count = onlineCount.intValue();
onlineCount = new Integer(count+1);
}
ctx.setAttribute("OnlineCount",onlineCount);
}
@Override
public void sessionDestroyed(HttpSessionEvent se) {
ServletContext ctx = se.getSession().getServletContext();
Integer onlineCount = (Integer)ctx.getAttribute("OnlineCount");
if (onlineCount == null){
onlineCount = new Integer(1);
}else {
int count = onlineCount.intValue();
onlineCount = new Integer(count-1);
}
ctx.setAttribute("OnlineCount",onlineCount);
}
}
/*
* session销毁:
* 手动销毁
* 自动销毁
* */
2.web.xml中配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<servlet>
<servlet-name>ShowServlet</servlet-name>
<servlet-class>com.kuang.servlet.ShowServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ShowServlet</servlet-name>
<url-pattern>/servlet/show</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>ShowServlet</servlet-name>
<url-pattern>/show</url-pattern>
</servlet-mapping>
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>com.kuang.filter.CharacterEncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/servlet/*</url-pattern>
</filter-mapping>
<listener>
<listener-class>com.kuang.listener.OnlineCountListener</listener-class>
</listener>
<session-config>//自动配置销毁时间
<session-timeout>1</session-timeout>
</session-config>
</web-app>
3.Filter 和监听器的应用场景:
3.1Filter:
登录权限的应用:
用户登录之后才能进入主页!用户注销后不能进入主页:
1、用户登录之后,向session中放入用户的数据。
2、进入主页的时候要判断用户是否已经登录;要求:在过滤器中实现。
package com.kuang.filter;
import com.kuang.util.Constant;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class SysFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp;
Object user_session = request.getSession().getAttribute(Constant.USER_SESSION);
if (user_session == null){
response.sendRedirect("/error.jsp");
}
chain.doFilter(request,response);
}
@Override
public void destroy() {
}
}
3.2监听器:(javaweb-filter)
统计在线人数,GUI界面
4.JDBC
4.1 导包
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
</dependencies>
4.2 连接数据库
package com.kuang.test;
import java.sql.*;
public class TestJdbc {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//配置信息
String url = "jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8";
String username = "root";
String password = "123456";
//加载驱动
Class.forName("com.mysql.jdbc.Driver");
//连接数据库,代表数据库
Connection connection = DriverManager.getConnection(url, username, password);
//向数据库发送sql的对象statement:crud
Statement statement = connection.createStatement();
//编写SQL
String sql = "select * from users";
//执行查询SQL,返回一个resultset,结果集
ResultSet rs = statement.executeQuery(sql);
while (rs.next()){
System.out.println("id="+rs.getObject("id"));
System.out.println("name="+rs.getObject("name"));
System.out.println("password="+rs.getObject("password"));
System.out.println("email="+rs.getObject("email"));
System.out.println("birthday="+rs.getObject("birthday"));
}
//关闭连接,释放资源(一定要做)先开后关
rs.close();
statement.close();
connection.close();
}
}
JDBC固定步骤:
1、加载驱动
Class.forName("com.mysql.jdbc.Driver");
2、连接数据库,代表数据库
Connection connection = DriverManager.getConnection(url, username, password);
3、向数据库发送SQL的对象Statement:CRUD
Statement statement = connection.createStatement();
4、编写SQL(根据业务,不同的SQL)
String sql = "select * from users";
5、执行SQL
ResultSet rs = statement.executeQuery(sql);while (rs.next()){ System.out.println("id="+rs.getObject("id")); System.out.println("name="+rs.getObject("name")); System.out.println("password="+rs.getObject("password")); System.out.println("email="+rs.getObject("email")); System.out.println("birthday="+rs.getObject("birthday"));}
6、关闭连接
rs.close();statement.close();connection.close();
预编译SQL
package com.kuang.test;
import java.sql.*;
public class TestJdbc2 {
public static void main(String[] args) throws Exception {
//配置信息
String url = "jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8";
String username = "root";
String password = "123456";
//加载驱动
Class.forName("com.mysql.jdbc.Driver");
//连接数据库,代表数据库
Connection connection = DriverManager.getConnection(url, username, password);
//编写SQL
String sql = "insert into users(id, name, password, email, birthday) values (?,?,?,?,?);";
//执行查询SQL,返回一个resultset,结果集
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1,8);
preparedStatement.setString(2,"333");
preparedStatement.setString(3,"232131");
preparedStatement.setString(4,"2324234@qq.com");
preparedStatement.setDate(5,new Date(new java.util.Date().getTime()));
int i = preparedStatement.executeUpdate();
if (i>0){
System.out.println("插入成功!!");
}
//关闭连接,释放资源(一定要做)先开后关
preparedStatement.close();
connection.close();
}
}
4.3 Jdbc事务
package com.kuang.test;
import org.junit.Test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class TestJdbc3 {
@Test
public void test(){
//配置信息
String url = "jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8";
String username = "root";
String password = "123456";
Connection connection = null;
//加载驱动
try {
Class.forName("com.mysql.jdbc.Driver");
//连接数据库,代表数据库
connection = DriverManager.getConnection(url, username, password);
connection.setAutoCommit(false);
String sql ="update account set money = money -100 where name = 'a';" ;
connection.prepareStatement(sql).executeUpdate();
String sql2 = "update account set money = money +100 where name = 'b';";
connection.prepareStatement(sql2).executeUpdate();
connection.commit();
System.out.println("success!!");
} catch (Exception e) {
try {
connection.rollback();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
e.printStackTrace();
}finally {
try {
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
5.javaweb项目(SMBMS)准备工作
jdk 1.8
tomcat 8.0
5.1、 搭建一个maven.web项目
5.2、 配置Tomcat
5.3、 测试项目是否能够 跑起来
5.4、 导入jar包
5.5、创建项目包结构
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-6tbwOrA1-1678669872712)(C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\1640160834443.png)]
5.6、编写实体类
ORM映射:表-类映射
5.7、编写公共类
5.7.1编写基础公共类
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306?useUnicode=true&characterEncoding=utf-8
username=root
password=123456
5.7.2 编写数据库的公共类
package com.kuang.dao;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
//操作数据库的公共类
public class BaseDao {
private static String driver;
private static String url;
private static String username;
private static String password;
//静态代码块,类加载的时候就初始化了
static {
Properties properties = new Properties();
//通过类加载器读取对应的资源
InputStream is = BaseDao.class.getClassLoader().getResourceAsStream("db.properties");
try {
properties.load(is);
} catch (IOException e) {
e.printStackTrace();
}
driver = properties.getProperty("driver");
url = properties.getProperty("url");
username = properties.getProperty("username");
password = properties.getProperty("password");
}
//获取数据库的链接
public static Connection getConnect(){
Connection connection =null;
try {
Class.forName(driver);
DriverManager.getConnection(url, username, password);
} catch (Exception e) {
e.printStackTrace();
}
return connection;
}
//编写查询公共类
public static ResultSet execute(Connection connection,String sql,Object[] params,ResultSet resultSet,PreparedStatement preparedStatement) throws SQLException {
//预编译的sql,在后面直接执行就可以了
preparedStatement = connection.prepareStatement(sql);
for (int i = 0; i < params.length; i++) {
//setObject,占位符从1开始,但是我们的数组是从0开始
preparedStatement.setObject(i+1,params[i]);
}
resultSet = preparedStatement.executeQuery();
return resultSet;
}
//编写增删改公共方法
public static int execute(Connection connection,String sql,Object[] params,PreparedStatement preparedStatement) throws SQLException {
preparedStatement = connection.prepareStatement(sql);
for (int i = 0; i < params.length; i++) {
//setObject,占位符从1开始,但是我们的数组是从0开始
preparedStatement.setObject(i+1,params[i]);
}
int updateRows = preparedStatement.executeUpdate();
return updateRows;
}
//释放资源
public static boolean closeResource(Connection connection,PreparedStatement preparedStatement,ResultSet resultSet){
boolean flag = true;
if (resultSet != null){
try {
resultSet.close();
//GC回收
resultSet = null;
} catch (SQLException throwables) {
throwables.printStackTrace();
flag =false;
}
}
if (connection != null){
try {
connection.close();
//GC回收
connection = null;
} catch (SQLException throwables) {
throwables.printStackTrace();
flag =false;
}
}
if (preparedStatement != null){
try {
preparedStatement.close();
//GC回收
preparedStatement = null;
} catch (SQLException throwables) {
throwables.printStackTrace();
flag =false;
}
}
return flag;
}
}
5.7.3编写字符编码过滤器
package com.kuang.filter;
import javax.servlet.*;
import java.io.IOException;
public class CharacterEncodingFilter implements Filter {
public void init(FilterConfig filterConfig) throws ServletException {
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
chain.doFilter(request,response);
}
public void destroy() {
}
}
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>com.kuang.filter.CharacterEncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
5.8、导入静态资源
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ZyZ3Xjje-1678669872716)(C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\1640165714404.png)]
6.javaweb项目业务实现
6.1登陆功能实现
1、编写前端页面
2、设置首页
<welcome-file-list>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list>
3、编写dao层用户登录接口
package com.kuang.dao.user;
import com.kuang.pojo.User;
import java.sql.Connection;
import java.sql.SQLException;
public interface UserDao {
//得到要登录的用户
public User getLoginUser(Connection connection,String userCode) throws SQLException;
}
4、编写dao接口的实现
package com.kuang.dao.user;
import com.kuang.dao.BaseDao;
import com.kuang.pojo.User;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class UserDaoImpl implements UserDao{
//得到要登录的用户
public User getLoginUser(Connection connection, String userCode) throws SQLException {
PreparedStatement pstm =null;
ResultSet rs = null;
User user = null;
if (connection != null){
String sql ="select * from smbms_user where userCode=?";
Object[] params = {userCode};
rs = BaseDao.execute(connection, pstm, rs, sql, params);
if (rs.next()){
user =new User();
user.setId(rs.getInt("id"));
user.setUserCode(rs.getString("UserCode"));
user.setUserName(rs.getString("UserName"));
user.setUserPassword(rs.getString("UserPassword"));
user.setGender(rs.getInt("gender"));
user.setBirthday(rs.getDate("birthday"));
user.setPhone(rs.getString("phone"));
user.setAddress(rs.getString("adress"));
user.setUserRole(rs.getInt("userRole"));
user.setCreatedBy(rs.getInt("createdBy"));
user.setCreationDate(rs.getTimestamp("creationDate"));
user.setModifyBy(rs.getInt("modifyBy"));
user.setModifyDate(rs.getTimestamp("modifyDate"));
}
BaseDao.closeResource(null,pstm,rs);
}
return user;
}
}
5、编写UserService层和其接口层
public User login(String userCode,String password);
public User login(String userCode, String password) {
Connection connection = null;
User user =null;
try {
connection = BaseDao.getConnection();
user = userDao.getLoginUser(connection, userCode);
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
BaseDao.closeResource(connection,null,null);
}
//匹配密码
if (user != null){
if (!user.getUserPassword().equals(userPassword)){
user = null;
}
}
return user;
}
/* @Test
public void test(){
UserServiceImpl userService = new UserServiceImpl();
User user = userService.login("admin", "12345675574567");
System.out.println(user.getUserPassword());
}*/
6.编写LoginServlet层
package com.kuang.servlet.user;
import com.kuang.pojo.User;
import com.kuang.service.user.UserService;
import com.kuang.service.user.UserServiceImpl;
import com.kuang.util.Constants;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("进入LoginServlet...");
String userCode = req.getParameter("userCode");
String userPassword = req.getParameter("userPassword");
UserService userService = new UserServiceImpl();
User user = userService.login(userCode, userPassword);
if (user != null){
req.getSession().setAttribute(Constants.USER_SESSION,user);
resp.sendRedirect("jsp/frame.jsp");
}else {
req.setAttribute("error","用户名或者密码不正确!!");
req.getRequestDispatcher("login.jsp").forward(req,resp);
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
6.2注销功能实现
1、LoginoutServlet的实现
package com.kuang.servlet.user;
import com.kuang.util.Constants;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class LoginoutServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.getSession().removeAttribute(Constants.USER_SESSION);
resp.sendRedirect(req.getContextPath()+"/login.jsp");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
6.3修改密码功能实现
1.编写Dao层和Dao层实现类
package com.kuang.dao.user;
import com.kuang.pojo.User;
import java.sql.Connection;
import java.sql.SQLException;
public interface UserDao {
//得到要登录的用户
public User getLoginUser(Connection connection,String userCode) throws SQLException;
//修改用户代码
public int updatePwd(Connection connection,int id, String password) throws SQLException;
}
package com.kuang.dao.user;
import com.kuang.dao.BaseDao;
import com.kuang.pojo.User;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class UserDaoImpl implements UserDao{
//得到要登录的用户
public User getLoginUser(Connection connection, String userCode) throws SQLException {
PreparedStatement pstm =null;
ResultSet rs = null;
User user = null;
if (connection != null){
String sql ="select * from smbms_user where userCode=?";
Object[] params = {userCode};
rs = BaseDao.execute(connection,sql,params,rs,pstm);
if (rs.next()){
user =new User();
user.setId(rs.getInt("id"));
user.setUserCode(rs.getString("userCode"));
user.setUserName(rs.getString("userName"));
user.setUserPassword(rs.getString("userPassword"));
user.setGender(rs.getInt("gender"));
user.setBirthday(rs.getDate("birthday"));
user.setPhone(rs.getString("phone"));
user.setAddress(rs.getString("address"));
user.setUserRole(rs.getInt("userRole"));
user.setCreatedBy(rs.getInt("createdBy"));
user.setCreationDate(rs.getTimestamp("creationDate"));
user.setModifyBy(rs.getInt("modifyBy"));
user.setModifyDate(rs.getTimestamp("modifyDate"));
}
BaseDao.closeResource(null,pstm,rs);
}
return user;
}
//修改用户代码
public int updatePwd(Connection connection, int id, String password) throws SQLException {
System.out.println("Userservlet" + password);
PreparedStatement pstm = null;
int execute = 0;
if (connection!= null){
String sql ="update smbms_user set userPassword = ? where id = ?";
Object params[] ={password,id};
execute = BaseDao.execute(connection, sql, params, pstm);
BaseDao.closeResource(null,pstm,null);
}
return execute;
}
}
2.编写service层及其实现类
package com.kuang.service.user;
import com.kuang.pojo.User;
import java.sql.Connection;
import java.sql.SQLException;
public interface UserService {
//用户登录
public User login(String userCode,String password);
//根据用户id修改密码
public boolean updatePwd(int id, String pwd);
}
package com.kuang.service.user;
import com.kuang.dao.BaseDao;
import com.kuang.dao.user.UserDao;
import com.kuang.dao.user.UserDaoImpl;
import com.kuang.pojo.User;
import org.junit.Test;
import java.sql.Connection;
import java.sql.SQLException;
public class UserServiceImpl implements UserService {
private UserDao userDao;
public UserServiceImpl(){
userDao = new UserDaoImpl();
}
public User login(String userCode, String password) {
Connection connection = null;
User user =null;
try {
connection = BaseDao.getConnection();
user = userDao.getLoginUser(connection, userCode);
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
BaseDao.closeResource(connection,null,null);
}
return user;
}
/* @Test
public void test(){
UserServiceImpl userService = new UserServiceImpl();
User user = userService.login("admin", "12345675574567");
System.out.println(user.getUserPassword());
}*/
//修改用户密码
public boolean updatePwd(int id, String pwd) {
System.out.println("Userservlet" + pwd);
Connection connection = null;
boolean flag = false;
//修改密码
try {
connection = BaseDao.getConnection();
if (userDao.updatePwd(connection,id,pwd)>0){
flag=true;
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
BaseDao.closeResource(connection,null,null);
}
return flag;
}
}
3.编写servlet层(UserServlet)
package com.kuang.servlet.user;
import com.kuang.pojo.User;
import com.kuang.service.user.UserService;
import com.kuang.service.user.UserServiceImpl;
import com.kuang.util.Constants;
import com.mysql.jdbc.StringUtils;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
//实现servlet复用
public class UserServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Object o = req.getSession().getAttribute(Constants.USER_SESSION);
String newpassword = req.getParameter("newpassword");
boolean flag = false;
System.out.println("Userservlet:" + newpassword);
System.out.println(o!= null);
System.out.println(!StringUtils.isNullOrEmpty(newpassword));
if (o!= null&& !StringUtils.isNullOrEmpty(newpassword)){
UserService userService = new UserServiceImpl();
flag = userService.updatePwd(((User) o).getId(), newpassword);
if (flag){
req.setAttribute("message","修改密码成功,请退出,使用新密码登陆");
//密码修改成功,移除当前session
req.getSession().removeAttribute(Constants.USER_SESSION);
}else {
req.setAttribute("message","密码修改失败!");
}
}else {
req.setAttribute("message","新密码有问题");
}
req.getRequestDispatcher("pwdmodify.jsp").forward(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
4.记得想要实现复用,就要提取出方法
package com.kuang.servlet.user;
import com.kuang.pojo.User;
import com.kuang.service.user.UserService;
import com.kuang.service.user.UserServiceImpl;
import com.kuang.util.Constants;
import com.mysql.jdbc.StringUtils;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
//实现servlet复用
public class UserServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String method = req.getParameter("method");
if (method.equals("savepwd")&& method!=null){
this.updatePwd(req,resp);
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
public void updatePwd(HttpServletRequest req, HttpServletResponse resp){
Object o = req.getSession().getAttribute(Constants.USER_SESSION);
String newpassword = req.getParameter("newpassword");
boolean flag = false;
System.out.println("Userservlet:" + newpassword);
System.out.println(o!= null);
System.out.println(!StringUtils.isNullOrEmpty(newpassword));
if (o!= null&& !StringUtils.isNullOrEmpty(newpassword)){
UserService userService = new UserServiceImpl();
flag = userService.updatePwd(((User) o).getId(), newpassword);
if (flag){
req.setAttribute("message","修改密码成功,请退出,使用新密码登陆");
//密码修改成功,移除当前session
req.getSession().removeAttribute(Constants.USER_SESSION);
}else {
req.setAttribute("message","密码修改失败!");
}
}else {
req.setAttribute("message","新密码有问题");
}
try {
req.getRequestDispatcher("pwdmodify.jsp").forward(req,resp);
} catch (ServletException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
6.4Ajax验证旧密码的实现
1、fastjson的引入
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.78</version>
</dependency>
<!-- 默认session过期时间-->
<session-config>
<session-timeout>30</session-timeout>
</session-config>
6.5用户页面管理
1、导入分页的工具类
package com.kuang.util;
public class PageSupport {
//当前页码-来自于用户输入
private int currentPageNo = 1;
//总数量(表)
private int totalCount = 0;
//页面容量
private int pageSize = 0;
//总页数-totalCount/pageSize(+1)
private int totalPageCount = 1;
public int getCurrentPageNo() {
return currentPageNo;
}
public void setCurrentPageNo(int currentPageNo) {
if(currentPageNo > 0){
this.currentPageNo = currentPageNo;
}
}
public int getTotalCount() {
return totalCount;
}
public void setTotalCount(int totalCount) {
if(totalCount > 0){
this.totalCount = totalCount;
//设置总页数
this.setTotalPageCountByRs();
}
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
if(pageSize > 0){
this.pageSize = pageSize;
}
}
public int getTotalPageCount() {
return totalPageCount;
}
public void setTotalPageCount(int totalPageCount) {
this.totalPageCount = totalPageCount;
}
public void setTotalPageCountByRs(){
if(this.totalCount % this.pageSize == 0){
this.totalPageCount = this.totalCount / this.pageSize;
}else if(this.totalCount % this.pageSize > 0){
this.totalPageCount = this.totalCount / this.pageSize + 1;
}else{
this.totalPageCount = 0;
}
}
}
2.用户列表页面导入
roolpage.jsp
userlist.jsp
if(currentPageNo > 0){
this.currentPageNo = currentPageNo;
}
}
public int getTotalCount() {
return totalCount;
}
public void setTotalCount(int totalCount) {
if(totalCount > 0){
this.totalCount = totalCount;
//设置总页数
this.setTotalPageCountByRs();
}
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
if(pageSize > 0){
this.pageSize = pageSize;
}
}
public int getTotalPageCount() {
return totalPageCount;
}
public void setTotalPageCount(int totalPageCount) {
this.totalPageCount = totalPageCount;
}
public void setTotalPageCountByRs(){
if(this.totalCount % this.pageSize == 0){
this.totalPageCount = this.totalCount / this.pageSize;
}else if(this.totalCount % this.pageSize > 0){
this.totalPageCount = this.totalCount / this.pageSize + 1;
}else{
this.totalPageCount = 0;
}
}
}
### 2.用户列表页面导入
roolpage.jsp
userlist.jsp