小峰servlet/jsp(3)登陆功能实现
一、User模型:
User.java:
package com.java1234.model; public class User { private int id;
private String userName;
private String password; public User() {
super();
// TODO Auto-generated constructor stub
} public User(String userName, String password) {
super();
this.userName = userName;
this.password = password;
} 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;
} }
二、封装jdbc连接数据库:
package com.java1234.util; import java.sql.Connection;
import java.sql.DriverManager; public class DbUtil { private String dbUrl="jdbc:mysql://localhost:3306/db_jsp";
private String dbUserName="root";
private String dbPassword="123456";
private String jdbcName="com.mysql.jdbc.Driver"; public Connection getCon()throws Exception{
Class.forName(jdbcName);
Connection con=DriverManager.getConnection(dbUrl, dbUserName, dbPassword);
return con;
} public void closeCon(Connection con)throws Exception{
if(con!=null){
con.close();
}
} public static void main(String[] args) {
DbUtil dbUtil=new DbUtil();
try {
dbUtil.getCon();
System.out.println("连接成功");
} catch (Exception e) {
e.printStackTrace();
}
}
}
三、userDao:
package com.java1234.dao; import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet; import com.java1234.model.User; public class UserDao { public User login(Connection con,User user)throws Exception{
User resultUser=null;
String sql="select * from t_user where userName=? and password=?";
PreparedStatement pstmt=con.prepareStatement(sql);
pstmt.setString(1, user.getUserName());
pstmt.setString(2, user.getPassword());
ResultSet rs=pstmt.executeQuery();
if(rs.next()){
resultUser=new User();
resultUser.setUserName(rs.getString("userName"));
resultUser.setPassword(rs.getString("password"));
}
return resultUser;
} }
四、loginServlet.java:
package com.java1234.web; import java.io.IOException;
import java.sql.Connection; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession; import com.java1234.dao.UserDao;
import com.java1234.model.User;
import com.java1234.util.DbUtil; public class LoginServlet extends HttpServlet{ /**
*
*/
private static final long serialVersionUID = 1L; DbUtil dbUtil=new DbUtil();
UserDao userDao=new UserDao(); @Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
} @Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String userName=request.getParameter("userName");
String password=request.getParameter("password"); Connection con=null;
try {
User user=new User(userName,password);
con=dbUtil.getCon();
User currentUser=userDao.login(con, user);
if(currentUser==null){
request.setAttribute("error", "用户名或密码错误");
request.setAttribute("userName", userName);
request.setAttribute("password", password);
request.getRequestDispatcher("login.jsp").forward(request, response);
}else{
HttpSession session=request.getSession();
session.setAttribute("currentUser", currentUser);
response.sendRedirect("main.jsp");
}
} catch (Exception e) {
e.printStackTrace();
}
} }
前台登陆界面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=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="login" method="post">
<table>
<tr>
<th colspan="2">用户登录</th>
</tr>
<tr>
<td>用户名:</td>
<td><input type="text" id="userName" name="userName" value="${userName }"/></td>
</tr>
<tr>
<td>密码:</td>
<td><input type="password" id="password" name="password" value="${password }"/></td>
</tr>
<tr>
<td><input type="submit" value="登录"/></td>
<td><font color="red">${error }</font></td>
</tr>
</table>
</form>
</body>
</html>
登陆成功后跳转到main.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=UTF-8">
<title>Insert title here</title>
</head>
<body>
主页!当前登录用户:${currentUser.userName } <a href="logout">注销</a>
</body>
</html>
五、注销方法:
LogoutServlet.java:
package com.java1234.web; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; public class LogoutServlet extends HttpServlet{
/**
*
*/
private static final long serialVersionUID = 1L; @Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
} @Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.getSession().invalidate();
response.sendRedirect("login.jsp");
} }
六、loginServlet.java/LogoutServlet.java两个servlet在web.xml中的配置:
web.xml配置:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>HeadFirstJspServletChap05</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list> <servlet>
<servlet-name>loginServlet</servlet-name>
<servlet-class>com.java1234.web.LoginServlet</servlet-class>
</servlet> <servlet-mapping>
<servlet-name>loginServlet</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping> <servlet>
<servlet-name>logoutServlet</servlet-name>
<servlet-class>com.java1234.web.LogoutServlet</servlet-class>
</servlet> <servlet-mapping>
<servlet-name>logoutServlet</servlet-name>
<url-pattern>/logout</url-pattern>
</servlet-mapping> <filter>
<filter-name>loginFilter</filter-name>
<filter-class>com.java1234.filter.LoginFilter</filter-class>
</filter> <filter-mapping>
<filter-name>loginFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping> <listener>
<listener-class>
com.java1234.listener.SessionAttributeListener
</listener-class>
</listener>
</web-app>
七、Servlet过滤器:
过滤用户请求;
添加登陆过滤器,LoignFilter.java:
package com.java1234.filter; import java.io.IOException; import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession; public class LoginFilter implements Filter{ public void destroy() { } public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request=(HttpServletRequest)servletRequest;
HttpSession session=request.getSession();
Object o=session.getAttribute("currentUser");
String path=request.getServletPath(); //获取用户请求的路径 "/login"
if(o==null&&path.indexOf("login")<0){
request.getRequestDispatcher("login.jsp").forward(servletRequest, servletResponse);
}else{
filterChain.doFilter(servletRequest, servletResponse);
}
} public void init(FilterConfig arg0) throws ServletException { } }
八、Servlet监听器:
监听web事件,如application、session、request
package com.java1234.listener; import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent; public class SessionAttributeListener implements HttpSessionAttributeListener{ //session中添加attribute时候会监听到
public void attributeAdded(HttpSessionBindingEvent httpSessionBindingEvent) {
System.out.println("添加的属性名: "+httpSessionBindingEvent.getName()+",属性值:"+httpSessionBindingEvent.getValue());
} public void attributeRemoved(HttpSessionBindingEvent httpSessionBindingEvent) {
System.out.println("删除的属性名: "+httpSessionBindingEvent.getName()+",属性值:"+httpSessionBindingEvent.getValue());
} public void attributeReplaced(HttpSessionBindingEvent httpSessionBindingEvent) { } }
配置listener见上面的web.xml;
登陆成功后,就能看到console打印:
servlet中跳转的两种方式:
response.sendRedirect("target.jsp"); //客户端跳转/重定向
request.getRequestDispatcher("target.jsp").forward(request, response); //服务器端跳转/转发
小峰servlet/jsp(3)登陆功能实现的更多相关文章
- 小峰servlet/jsp(1)
一.scriptlet标签: 通过scriptlet标签我们可以可以在jsp理嵌入java代码: 第一种:<%! %> 可以在里面定义全局变量.方法.类: 第二种:<% %> ...
- 小峰servlet/jsp(5)jsp自定义标签
一.自定义标签helloworld: 二.自定义有属性的标签: HelloWorldTag.java:继承TagSupport: package com.java1234.tag; import ja ...
- 小峰servlet/jsp(7)jstl国际化标签库、sql标签库等
一.jstl国际化标签库: fmt:setLocale 设定用户所在的区域: fmt:formatDate 对日期进行格式化 fmt:requestEncoding 设置所有的请求编码; fmt: ...
- 小峰servlet/jsp(6)jstl核心标签库
一.引入jstl 需要jstl.jar;standard.jar; 二.jstl核心标签库: c:out 内容输出标签; c:set 用来设置4种属性范围值的标签: c:re ...
- 小峰servlet/jsp(4)EL表达式
一.EL表达式内置对象: 二.EL表达式访问4种范围属性: 寻找值的顺序: page-->request-->session-->application; 三.EL表达式接收请求参数 ...
- 小峰servlet/jsp(2)
一.jsp javaBean组件引入 <jsp:useBean id="实例化对象名称" scope="保存范围" class="类完整名称&q ...
- 草草搞了个SERVLET的注册登陆功能
按书来的,学习阶段,一切都好新奇..至少对比于DJANGO,好像复杂点点,但HTTP的东东,是相通的哈. package cc.openhome.controller; import java.io. ...
- jsp+servlet实现最基本的注册登陆功能
源码和数据库下载地址:http://download.csdn.net/detail/biexiansheng/9759722 1:首先需要设计好数据库和数据表,这里简单截图说明我创建的字段和类型. ...
- JavaWeb实现用户登录注册功能实例代码(基于Servlet+JSP+JavaBean模式)
一.Servlet+JSP+JavaBean开发模式(MVC)介绍 Servlet+JSP+JavaBean模式(MVC)适合开发复杂的web应用,在这种模式下,servlet负责处理用户请求,jsp ...
随机推荐
- 深入理解java异常【绝对经典,推荐最少看五遍】
http://blog.csdn.net/hguisu/article/details/6155636 补充:检查异常(checkedException)与运行异常,什么时候throw,什么时候thr ...
- react 学习日记
1.本地配置代理服务: create-react-app 创建的react项目 package.jsoin 中 加入: "proxy": "http://localh ...
- 第十六篇 make中的路径搜索
在实际的工程项目中,源文件和头文件都会组织成一定的目录结构,这样也便于项目的管理,前述我们分析的makefile,源文件和头文件大都在当前目录,没有路径搜索的问题,下面我们引入今天的演示程序的目录结 ...
- jquery deferred promise
<script type="text/javascript">/* Deferredstate (then,done, fail, always,pipe, progr ...
- Win10:已禁用IME
问题 windows10莫名其妙地禁用了IME,导致的结果便是浏览器不能输入中文. 百度搜索的答案都是tmd 控制中心-->管理-->任务XXX,但是我的 任务XXX打不开啊. 解决 go ...
- bug20170125
1s定时请求接口,接口不响应(接口挂掉),浏览器崩溃
- SharePoint 列表多表联合查询
在SharePoint平台二次开发中,我们有时需要涉及多表关联查询展示多列表中的不同字段信息:SharePoint和Sql数据表一样,也支持多表联合查询,但是不像Sql语句那样简单,有一定的局限性,需 ...
- 《DSP using MATLAB》Problem 4.12
代码: function [As, Ac, r, v0] = invCCPP(b0, b1, a1, a2) % Determine the signal parameters Ac, As, r, ...
- java内存的分配和管理
常用的三个内存空间 栈内存 ,堆内存 ,方法区 栈内存存储的内容: 局部变量. 函数(栈中的局部变量,需要手动赋值.当变量,或者函数执行完毕,就自动被释放) 堆内存,存储的内容 :全局变量.数据容器. ...
- width百分比
table中的td可以在页面中直接在元素上设置width:但是li不能只能在页面中写style: <!-- <li width="20%" class="p- ...