Fork me on GitHub

java web基础-数据库

这次的java web代码涉及到后端以及数据库。
一.数据库:
1.我们用的是MySQL数据库代码如下:

点击查看代码
package dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;

public class DBUtil {
	
	private String className;
	private String url;
	private String username;
	private String password;
	private Connection conn;
	private Statement stm;
	private PreparedStatement pStatement;
	private ResultSet rs;
	
	public DBUtil()
	{
		className="com.mysql.cj.jdbc.Driver"; // com.mysql.jdbc.Driver
		url="jdbc:mysql://localhost:3306/users";
		username="root";
		password="123456";
		pStatement = null;
		getCon();
	}
	
	public void getCon()
	{
		try{
			Class.forName(className);
		}
		catch(ClassNotFoundException e)
		{
			System.out.println("加载数据库驱动程序失败!");
		}
		try
		{
			conn=DriverManager.getConnection(url,username,password);
		}
		catch(Exception e){
			System.out.println("数据库连接失败!");
		}		
	}
	
    public ResultSet getRs(String sql)
    {
    	try
    	{
    	   stm=conn.createStatement();
    	   rs = stm.executeQuery(sql);
    	}
    	catch(Exception e){
			System.out.println("查询数据库失败!");
		}
    	return rs;
    }
    
    public ResultSet getRs(String sql, String[] args)
    {

    	try
    	{
    	  //设置参数	
    	   pStatement = conn.prepareStatement(sql);
    	   for(int i=0; i < args.length; i++) {
    		   pStatement.setString(i+1, args[i]); // 参数从1开始
    	   }
    	   //执行Sql语句,生成ResultSet结果
    	   rs = pStatement.executeQuery();
    	}
    	catch(Exception e){
			System.out.println("查询数据库失败2!");
		}
    	return rs;
    }
    
    public void close()
    {
    	try{
    	if(rs != null) rs.close();
    	if (stm != null) stm.close();
    	if (pStatement != null) pStatement.close();
    	if (conn != null) conn.close();
    	}catch(SQLException se){
    		System.out.println("close失败!");
            // 处理 JDBC 错误
            se.printStackTrace();
    	}
    }
}
二.jsp代码: 1.登陆代码:
点击查看代码
<%@ page language="java" contentType="text/html; charset=utf-8" import="java.util.*"
    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>
<style>
body{
width:1100px;
text-align:center;
margin-left:auto;
margin-right:auto;
}
.div_01{
background-color:#cccccc;
border:2px solid #aaaaaa;
width:1100px;
height:100px;
font-size:20pt;
line-height:100%;
}
</style>
</head>
<body>
<div class="div_01">
<h1>员工登录入口</h1>
</div>
<div class="div_02">
<form action="${pageContext.request.contextPath}/LoginServlet3"  method="post">
<br/><br/><br/>
用户名:<input type="text" name="userName"><br/><br/>
密 &nbsp;码:<input type="password" name="userPwd"><br/><br/>
<input type="submit" value="登录">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<input type="reset" value="重置"><br/>
</form>
</div>
</body>
</html>
2.主页代码:
点击查看代码
<%@ page language="java"  contentType="text/html; charset=utf-8"
    pageEncoding="utf-8" import="java.util.*"%>
 <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<!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>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath }/css/user.css">
<link rel="stylesheet" type="text/css" href="<%=request.getContextPath() %>" + "/css/user.css">
</head>
<body>
<div class="div_01">
<h1>员工之窗</h1>
</div>
<div class="div_02">
 <span class="span_01"><%=session.getAttribute("userName") %></span>,欢迎你来到员工之窗。<br/>
 当前时间:<div id="span_02" onclick="time()"></div>
 </div>
 <div class="div_03">
 <table border="1" cellspacing="0" align="center">
 <tr>
 <th id="th_01">文章编号</th>
 <th id="th_01">文章类型</th>
 <th id="th_01">标题</th>
 <th id="th_01">作者</th>
 <th id="th_01">发表日期</th>
 </tr>
 <c:forEach items="${articlesList}" var="article">
 <tr>
 <td class="td_01">${article.articID}</td>
 <td class="td_01">${article.articType}</td>
 <td class="td_01"><a href="${pageContext.request.contextPath}/GetArticleServlet?articID=${article.articID}" target="_blank">${article.articTitle }</a></td>
 <td class="td_01">${article.articAuthor}</td>
 <td class="td_01"><fmt:formatDate value="${article.articTime}" pattern="yyyy/MM/dd"/></td>
   </tr>
   </c:forEach>
   </table><br/>
    <div class="div_1">
   <a href="${pageContext.request.contextPath}/./publish.jsp">[发表文章]</a>&nbsp;&nbsp;&nbsp;
   <a href="${pageContext.request.contextPath}/./out.jsp">[退出登录]</a>&nbsp;&nbsp;&nbsp;
   <a href="${pageContext.request.contextPath}/index.jsp">[返回首页]</a>
   </div>
 </div>
 <script type="text/javascript">
 function time2(){
	 var date=new Date();
	 var time=(date.getFullYear()+"-"+(date.getMonth()+1)+"-"+date.getDate()+" "+date.getHours()+":"+
			 date.getMinutes()+":"+date.getSeconds());
	        document.getElementById("span_02").innerHTML=time;
 }
 window.setInterval(time2,1000);
 </script>
</body>
</html>
3.文本编辑代码:
点击查看代码
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path=request.getContextPath();
String basePath=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html>
<html>
<head>
<base href="<%=basePath %>">
<title>含有在线编辑器的表单页面</title>
<script type="text/javascript" src="ckeditor/ckeditor.js"></script>
<script type="text/javascript">
window.onload=function(){
	CKEDITOR.replace('articContent');
};
</script>
<style type="text/css">
table{
	border-color:#aaaaaa;
}
 
.td_01{
	width:500px;
	height:50px;
	text-align:center;
	font-weight:bold;
	font-size:20pt;
	background-color:#cccccc;
	color:#222222;
}
 
.td_02{
	width:180px;
	text-align:center;
}
 
.td_03{
	width:100px;
	text-align:center;
	
	
}
</style>
</head>
<body>
	<form action="./PublishServlet2" method="post">
		<table border="1" cellspacing="0" align="center">
			<tr>
				<td colspan="2" class="td_01">发表文章</td>
			</tr>
			<tr>
				<td class="td_02">文章类型:</td>
				<td>
					<select name="articType">
						<option value="程序设计">程序设计</option>
						<option value="军事">军事</option>
						<option value="艺术设计">艺术设计</option>
						<option value="传统文化">传统文化</option>
						<option value="篮球体育">篮球体育</option>
						<option value="世界地图">世界地图</option>
					</select>
				</td>
			</tr>
			<tr>
				<td class="td_02">文章标题:</td>
				<td>
					<input type="text" name="articTitle"/>
				</td>
			</tr>
			<tr>
				<td class="td_03">文章内容:</td>
				<td>
					<textarea rows="10" cols="41" name="articContent" id="articContent"></textarea><br>
				</td>
			</tr>
			<tr>
				<td class="td_02">您已发表的文章数:</td>
				<td>${sessionScope.count}篇</td>
			</tr>
			<tr>
				<td colspan="2" align="center">
				<input type="submit" value="确定发表">&nbsp;&nbsp;
				<input type="button" onclick="out()" value="返回首页">
				<input type="button" onclick="back()" value="返回用户界面">
				</td>
			</tr>
			</table>
		</form>
</body>
</html>

4.退出代码:
点击查看代码
<%@ page language="java" contentType="text/html; charset=utf-8" import="java.util.*"
    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>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keywordl1,keywordl2,keyword3">
</head>
<body>
<%
if("User[userName]"!=null){
	
	response.sendRedirect("login.jsp");
}
%>

</body>
</html>
5.主页的css样式:
点击查看代码
@CHARSET "UTF-8";
body{
	width:1100px;
	text-align:auto;
	margin-left:auto;
	margin-right:autp;
}
.div_01{
	background-color:SkyBlue;
	border:2px soild #aaaaaa;
	width:1100px;
	height:100px;
	font-size:20pt;
	text-align:center;
}
.div_1{
	margin-left:400px;
	
}
.div_02{
	text-align:left;
	line-height:20pt;
	padding-top:10px;
	padding-bottom:10px;
	font-weight:bold;
	border:bottom:solid #777777 2px;;
}
.div_03{
	padding-top:10px;
}
#th_01{
	background-color:#22ccff;
	width:140px;
	height:60px;
}
a{
	font-family:宋体;
	text-align:left;
	text-frcoration:underline;
	TEXT-DECORATION:none;
}
.td_01{
	text-align:center;
}
.span_01{
	color:red;
}
.td_02{
	text-align:center;
}
#span_02{
	width:200px;
	height:20px;
	background-color:red;
}

6.文章发表css样式:
点击查看代码
@CHARSET "UTF-8";
body{
	width:1100px;
	text-align:center;
	margin-left:auto;
	margin-right:auto;
	
}
.div_bj{
	background-color:Cyan;/*背景颜色*/
	
}
.div_01{
	background-color:SkyBlue;
	border:2px solid #aaaaaa;
	width:1100px;
	height:100px;
	font-size:20pt;
	line-hight:100%;
}
.div_02{
	text-align:center;
	line-height:20pt;
	padding-top:10px;
	padding-bottom:10px;
	font-weight:bold;
	border-bottom:solid #777777 2px;
	
}
.div_03{
	text-align:left;
	line-height:20pt;
	padding-top:10px;
	padding-bottom:10px;
	font-weight:bold;
	border-bottom:solid #777777 2px;
	text-indent:2em ;
}
.div_04{
	padding-top:10px;
	
}
a{
	font-family:宋体;
	text-align:left;
	text-decoration:underline;
	TEXT-DECORATION:none;
}
#span_02{
	width:250px;
	height:20px;
	background-color:red;
}
三.Servlet的编写: 1.登陆密码账号的判断:
点击查看代码
package cn.text.bean;

import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.text.dao.DBUtil;


@WebServlet("/LoginServlet3")
public class LoginServlet3 extends HttpServlet {
	private static final long serialVersionUID = 1L;
       

    public LoginServlet3() {
        super();
    }

	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html);charset=utf-8");
		String userName=request.getParameter("userName");
		String userPwd=request.getParameter("userPwd");
		DBUtil db =new DBUtil();
		db.getConn();
		ResultSet rs=db.getResult("select * from admin where name=? and pwd=?",new String[]{userName,userPwd});
		try{
			if(rs!=null && rs.next()){
				HttpSession session =request.getSession();
				session.setAttribute("userName",userName);
				request.getRequestDispatcher("GetAllArticleServlet").forward(request, response);
			}else{
				response.sendRedirect("login.jsp");
				response.sendRedirect(request.getContextPath()+"/./login.jsp");
			}
	}catch(SQLException e){
		e.printStackTrace();
	}finally{
		if(db!=null)
			db.release();
	}
	}

}

2.查询数据库中的信息:
点击查看代码
package cn.text.bean;

import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.text.dao.DBUtil;


@WebServlet("/GetArticleServlet")
public class GetArticleServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    public GetArticleServlet() {
        super();
    }
    public void destroy(){
    	super.destroy();
    }
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
	    String articID=request.getParameter("articID");
	    Articles article;
	    DBUtil db=new DBUtil();
	    db.getConn();
	    ResultSet rs=db.getResult("select * from essays where id="+articID);
	    try{
	    	if(rs.next()){
	    		article=new Articles();
	    		article.setArticID(rs.getString("id"));
	    		article.setArticType(rs.getString("type"));
	    		article.setArticTitle(rs.getString("title"));
	    		article.setArticContent(rs.getString("essay"));
	    		article.setArticAuthor(rs.getString("author"));
	    		article.setArticTime(rs.getDate("date"));
	    		request.setAttribute("article", article);
	    		request.getRequestDispatcher("./content.jsp").forward(request, response);
	    	}
	    }catch(SQLException e){
	    	e.printStackTrace();
	    }finally{
	    	if(db!=null)
	    		db.release();
	    }
	}
public void init() throws ServletException{
	
}
}

3.查询信息:
点击查看代码
package cn.text.bean;

import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.text.dao.DBUtil;


@WebServlet("/GetAllArticleServlet")
public class GetAllArticleServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    public GetAllArticleServlet() {
        super();
       
    }
public void destroy(){
	super.destroy();
}
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		List<Articles>articlesList=new ArrayList<Articles>();
		Articles article;
		DBUtil db=new DBUtil();
		db.getConn();
		ResultSet rs=db.getResult("select * from essays");
		try{
			while(rs.next()){
				article=new Articles();
				article.setArticID(rs.getString("id"));
				System.out.println(rs.getString("id"));
				article.setArticType(rs.getString("type"));
				article.setArticTitle(rs.getString("title"));
				System.out.println(rs.getString("title"));
				article.setArticContent(rs.getString("essay"));
				article.setArticAuthor(rs.getString("author"));
				article.setArticTime(rs.getDate("date"));
				articlesList.add(article);
			}
			request.setAttribute("articlesList",articlesList);
			request.getRequestDispatcher("./user.jsp").forward(request, response);
		}catch(SQLException e){
			e.printStackTrace();
		}finally{
			if(db!=null)
				db.release();
		}
	}
public void init() throws ServletException{
	
}
}

4.增加信息的Servlet:
点击查看代码
package cn.text.bean;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;



import cn.text.dao.DBUtil;


@WebServlet("/PublishServlet2")
public class PublishServlet2 extends HttpServlet {
	private static final long serialVersionUID = 1L;
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}

	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		String articType=request.getParameter("articType");
		String articTitle=request.getParameter("articTitle");
		String articContent=request.getParameter("articContent");
		HttpSession session=request.getSession();
		String articAuthor=(String)session.getAttribute("userName");
		if(articTitle==null||articTitle==""||articContent==null||articContent==""){
				request.setAttribute("message", "文章的标题和文章的内容不能为空");
				request.getRequestDispatcher("admin/publish.jsp").forward(request, response);
		}else{
			PreparedStatement pstat=null;
			int result=0;
			DBUtil db=new DBUtil();
			Connection conn=db.getConn();
			try{
				pstat=(PreparedStatement) conn.prepareStatement("insert into essays(type,title,essay,author,date)value(?,?,?,?,?)");
				pstat.setString(1, articType);
				pstat.setString(2, articTitle);
				pstat.setString(3, articContent);
				pstat.setString(4, articAuthor);
				pstat.setDate(5, (java.sql.Date) new Date(System.currentTimeMillis()));
				
				result=pstat.executeUpdate();
				if(result>0){
					System.out.println("success发表成功");
					request.getRequestDispatcher("./user.jsp").forward(request, response);
				}else{
					System.out.println("error发表失败");
					request.getRequestDispatcher("./publish.jsp").forward(request, response);
				}
			}catch(SQLException e){
					e.printStackTrace();
				}catch(Exception e){
					e.printStackTrace();
			}finally{
				if(db!=null)
					db.release();
			}
		}
	}
}









四.用户的实例化 1.user的实例化:
点击查看代码
package cn.text.bean;


public class User {
	private String userName;
	private String userPwd;
	private Integer loginTimes;
	public User(){
		super();
	}
	public User(String userName,String userPwd,Integer loginTimes){
		super();
		this.userName=userName;
		this.userPwd=userPwd;
		this.loginTimes=loginTimes;	
	}
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public String getUserPwd() {
		return userPwd;
	}
	public void setUserPwd(String userPwd) {
		this.userPwd = userPwd;
	}
	public Integer getLoginTimes() {
		return loginTimes;
	}
	public void setLoginTimes(Integer loginTimes) {
		this.loginTimes = loginTimes;
	}
@Override
public String toString(){
	return "User[userName="+userName+",userPwd="+userPwd+","
					+ "loginTimes="+loginTimes+"]";
}

}






2.发表的信息的实例化:
点击查看代码
package cn.text.bean;

import java.util.Date;

public class Articles {
private String articID;
private String articType;
private String articTitle;
private String articContent;
private String articAuthor;
private Date articTime;

public Articles(){
	super();
}
public Articles(String articID,String articType,String articTitle,String articContent,String articAuthor,
		Date articTime){
	super();
	this.articID=articID;
	this.articType=articType;
	this.articTitle=articTitle;
	this.articContent=articContent;
	this.articAuthor=articAuthor;
	this.articTime=articTime;
}
public String getArticID() {
	return articID;
}
public void setArticID(String articID) {
	this.articID = articID;
}
public String getArticType() {
	return articType;
}
public void setArticType(String articType) {
	this.articType = articType;
}
public String getArticTitle() {
	return articTitle;
}
public void setArticTitle(String articTitle) {
	this.articTitle = articTitle;
}
public String getArticContent() {
	return articContent;
}
public void setArticContent(String articContent) {
	this.articContent = articContent;
}
public String getArticAuthor() {
	return articAuthor;
}
public void setArticAuthor(String articAuthor) {
	this.articAuthor = articAuthor;
}
public Date getArticTime() {
	return articTime;
}
public void setArticTime(Date articTime) {
	this.articTime = articTime;
}
@Override
public String toString() {
	return "Articles [articID=" + articID + ", articType=" + articType + ", articTitle=" + articTitle
			+ ", articContent=" + articContent + ", articAuthor=" + articAuthor + ", articTime=" + articTime + "]";
}

}

五.过滤器的运用: 1.登陆的过滤器:
点击查看代码
package beans;

import java.io.IOException;
import java.io.PrintWriter;

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.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * Servlet Filter implementation class AdminFilter
 */
@WebFilter(filterName="AdminFilter",urlPatterns="/admin/*")
public class AdminFilter implements Filter {

    /**
     * Default constructor. 
     */
    public AdminFilter() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		// place your code here
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		HttpServletRequest request1 = (HttpServletRequest) request;
		HttpSession session = request1.getSession();
		PrintWriter out = response.getWriter();
		if(session.getAttribute("userName")!=null){
			chain.doFilter(request, response);
			return;
		}else{
			out.print("<a href='../login.jsp'>你没有权限访问本页面,请先登录!</a>");
		}
		// pass the request along the filter chain
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}

2.过滤器2:
点击查看代码
package 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.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;



public class PublishFilter implements Filter {
    public PublishFilter() {
        // TODO Auto-generated constructor stub
    }
	public void destroy() {
	}
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request1 =(HttpServletRequest)request;
		HttpSession session=request1.getSession();
		if(session.getAttribute("user")!=null){
			chain.doFilter(request, response);
			return;
		}else{
			request1.setAttribute("message", "你没有权限访问本页面,请先登录!!");
			request1.getRequestDispatcher("/./login.jsp").forward(request1, response);
		}	
	}
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}

3.过滤器3:
点击查看代码
package 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.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;



public class PublishFilter implements Filter {
    public PublishFilter() {
        // TODO Auto-generated constructor stub
    }
	public void destroy() {
	}
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request1 =(HttpServletRequest)request;
		HttpSession session=request1.getSession();
		if(session.getAttribute("user")!=null){
			chain.doFilter(request, response);
			return;
		}else{
			request1.setAttribute("message", "你没有权限访问本页面,请先登录!!");
			request1.getRequestDispatcher("/./login.jsp").forward(request1, response);
		}	
	}
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}

六:效果展示:

posted @ 2022-07-17 15:12  sxflmy  阅读(168)  评论(0)    收藏  举报