java:(设置编码集,密码的加密,JSTL,EL表达式,权限设置)

时间:2024-05-05 21:05:08

1.设置编码集:

package cn.zzsxt.lee.web.sevlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; @WebServlet("/encoding.sxt")
public class EncodingServlet extends HttpServlet { @Override
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 客户端向服务器端请求的信息,设置编码集
request.setCharacterEncoding("UTF-8"); String username = request.getParameter("username");
String realname = request.getParameter("realname"); // System.out.println(username + "---------------" + new
// String(realname.getBytes("ISO8859-1"), "UTF-8"));
System.out.println(username + "---------------" + realname); // 服务器向客户端响应数据
response.setCharacterEncoding("utf-8");//已经进行了一次编码
response.setContentType("text/html;charset=utf-8");
response.getWriter().print("<h1>我是响应信息</h1>");// 把服务器响应的内容显示在页面上 } }
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head> <title>My JSP 'index.jsp' starting page</title>
</head> <body> <form action="encoding.sxt" method="get">
<input type="text" name="username" />
<input type="text" name="realname" />
<input type="submit" value="提交" /> </form> <pre>
客户端向服务器端发送请求
post:
request.setCharacterEncoding("UTF-8");
get:
request.setCharacterEncoding("UTF-8");
在tomcat中,conf文件夹的server.xml中配置
useBodyEncodingForURI="true"
<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000" redirectPort="8443"
!! useBodyEncodingForURI="true" />默认支持中文编码
http://localhost:8080/zzsxt/encoding.sxt?username=zhangsan&realname=%E5%95%8A%E5%95%8A%E5%95%8A 服务器端向客户端响应数据:
response.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8"); </pre> </body>
</html>

2.密码的加密:

  工具类中,MD5加密方法:

package cn.zzsxt.lee.web.utils;

import java.security.MessageDigest;

public class MD5 {

    public static String getMD5(String message) {
String md5str = "";
try {
// 1 创建一个提供信息摘要算法的对象,初始化为md5算法对象
MessageDigest md = MessageDigest.getInstance("MD5"); // 2 将消息变成byte数组
byte[] input = message.getBytes(); // 3 计算后获得字节数组,这就是那128位了
byte[] buff = md.digest(input); // 4 把数组每一字节(一个字节占八位)换成16进制连成md5字符串
md5str = bytesToHex(buff); } catch (Exception e) {
e.printStackTrace();
}
return md5str;
} /**
* 二进制转十六进制
*
* @param bytes
* @return
*/
public static String bytesToHex(byte[] bytes) {
StringBuffer md5str = new StringBuffer();
// 把数组每一字节换成16进制连成md5字符串
int digital;
for (int i = 0; i < bytes.length; i++) {
digital = bytes[i]; if (digital < 0) {
digital += 256;
}
if (digital < 16) {
md5str.append("0");
}
md5str.append(Integer.toHexString(digital));
}
return md5str.toString().toUpperCase();
} }

  处理加密的servlet:

package cn.zzsxt.lee.web.servlet;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.UUID; import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import cn.zzsxt.lee.web.utils.MD5; public class PasswordServlet extends HttpServlet { @Override
protected void service(HttpServletRequest request, HttpServletResponse response) { System.out.println("我是处理加密的servlet,我被访问过!");
String username = request.getParameter("username");
String password = request.getParameter("pwd");
password = MD5.getMD5(password);// 经过加密
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl", "scott", "scott");
String sql = "insert into e_user (id, username, password) values(?,?,?)";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, UUID.randomUUID().toString());
ps.setString(2, username);
ps.setString(3, password);
int result = ps.executeUpdate();
System.out.println(result); } catch (Exception e) {
e.printStackTrace();
} } }

  反编译登录的servlet:

package cn.zzsxt.lee.web.servlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet; 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.zzsxt.lee.web.utils.MD5; @WebServlet("/login.sxt")
public class LoginServlet extends HttpServlet { @Override
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { String username = request.getParameter("username");
String password = request.getParameter("pwd");
password = MD5.getMD5(password);//反编译
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl", "scott", "scott");
String sql = "select * from e_user where username=? and password=?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, username);
ps.setString(2, password);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
System.out.println(rs.getString("id"));
}
} catch (Exception e) {
e.printStackTrace();
} } }

3.EL表达式:

  EL(Expression Language) 是为了使JSP写起来更加简单。表达式语言的灵感来自于 ECMAScript 和 XPath 表达式语言,它提供了在 JSP 中简化表达式的方法,让Jsp的代码更加简化。

<%@ page language="java" import="java.util.*, cn.zzsxt.lee.web.entity.*"
pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head> <title>My JSP 'param.jsp' starting page</title> </head> <body> <%
User user = new User("123", "zhangsan", "123456", new Address("河南省郑州市"));
request.setAttribute("user", user);
%> ${param.name }--->${paramValues.fav }--->${paramValues.fav[0] }
<br />
<hr />
<!-- el表达式获取实体类型值是时候,一定要和声明变量对应(一个字母都不能错) -->
${user.id }
<!-- EL表达式的原理,同样是通过get方法进行获取值,使用的是反射 -->
${user.username } ${user.address.addr } <!-- EL表达式可以操作运算符(+,-,*,/,==,>,<,>=,<=) -->
${user.id == "123" } ${3+"3" }
<!-- 如果一个数字加上字符串类型的数字,把字符串类型的数字先转换为数字,再进行运算 -->
${"3"+"3" }
${user.id eq 1 }
${user.id gt 12345 }
</body>
</html>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head> <title>My JSP 'index.jsp' starting page</title>
</head> <body> <%
// 作用域
// 如果有重名的key值,EL表达式会从小往大取,一旦在小的作用域(scope)中找到了,就不会继续向下寻找
request.setAttribute("zzsxt", "www.zzsxt.cn");
session.setAttribute("zzsxt", "www.bjsxt.com");
%> 0${student.name }0 获取到的值为:
${sessionScope.zzsxt } 页面跳转的时候参数的传递:(一定不能使用)
<a href="param.jsp?name=zhangsan&fav=1&fav=2">页面跳转</a> <pre>
EL表达式语言:
在html页面上不出现Java代码
作用于:Java程序向页面进行值传递和显示
$ { } <---一切向钱看,通过设置key来取value request,session,pageContext,Application
get,set,remove+Attribute(); </pre> </body>
</html>
package cn.zzsxt.lee.web.servlet;

import java.io.IOException;

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.zzsxt.lee.web.entity.Students; @WebServlet("/login")
public class LoginServlet extends HttpServlet { @Override
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { String username = request.getParameter("username");
String pwd = request.getParameter("pwd");
Students student = new Students();
student.setName(username);
request.setAttribute("student", student);
request.getRequestDispatcher("index.jsp").forward(request, response);
return;
} }

4.jstl:

  JSTL(JSP Standard Tag Library,JSP标准标签库)是一个不断完善的开放源代码的JSP标签库,是由apache的jakarta小组来维护的。JSTL只能运行在支持JSP1.2和Servlet2.3规范的容器上,如tomcat 4.x。在JSP 2.0中也是作为标准支持的。

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head> <title>My JSP 'index.jsp' starting page</title>
</head> <% request.setAttribute("zzsxt", "www.zzsxt.cn");
session.setAttribute("zzsxt", "www.bjsxt.com");
int[] x = {1,2,3,4,5,6,7,8,9,10,11,12,13};
request.setAttribute("number", x);
List<String> arr = new ArrayList<String>();
arr.add("str1");
arr.add("str2");
arr.add("str3");
arr.add("str4");
arr.add("str5");
arr.add("str6");
arr.add("str7");
arr.add("str8");
request.setAttribute("arr", arr);
String str = "1,2,3,4,5,6,7";
request.setAttribute("str", str);
%> <body> <pre>
jstl:
jsp standrad标准 tag标签 library库
c.tld:
tld:tag lib description
官方自带的标签库:
core:(核心)最常用
使用jstl(core):在jsp页面开始使用< % @ taglib % > 配置uri="http://java.sun.com/jsp/jstl/core" 然后配置prefix(前缀)=""
< c : xxx >
format:(格式化)
xml:(xml)
sql:(sql)
function:(函数) 自定义(是shiro(权限框架)+spring框架)标签库(理解):
简单权限
</pre> <c:remove var="zzsxt" scope="request" />
<c:out value="${zzsxt }" default="暂无数据"></c:out>
<hr /> <!-- ***************** -->
<c:forEach begin="0" end="7" step="1" items="${arr }" var="each" varStatus="vars" >
<!-- vars.index:每个元素的下标 vars.count:每一个元素第几个被打印 vars.first:是否第一个被打印 vars.last:是否最后一个被打印-->
${each }--->${vars.index }--->${vars.count }---->${vars.first }--->${vars.last }<br />
</c:forEach> <!-- 在jstl中,并没有else -->
<c:if test="${1 eq 2 }">
我是一个老师
</c:if> <c:choose>
<c:when test="${1 eq 2 }">
我是一个老师1
</c:when>
<c:when test="${1 eq 1 }">
我是一个老师2
</c:when>
<c:when test="${1 eq 3 }">
我是一个老师3
</c:when>
<c:when test="${1 eq 4 }">
我是一个老师4
</c:when>
<c:when test="${2 eq 2 }">
我是一个老师5
</c:when>
<c:otherwise>
我是一个胖老师
</c:otherwise>
</c:choose>
<!-- 在Java中重定向不能传递参数,但是在jstl中,重定向可以传递参数 -->
<%-- <c:redirect url="redirect.jsp">
<c:param name="name" value="zhangsan"></c:param>
</c:redirect> --%>
<%-- <jsp:forward page="redirect.jsp">
<jsp:param value="zhangsan" name="name"/>
</jsp:forward> --%> <%-- <c:import url="http://www.bjsxt.com"></c:import> --%> <hr />
<c:forTokens items="${str }" delims="," var="each"> // delims以","分割
${each }
</c:forTokens> <!-- 必须会:
foreach
if
choose
remove --> </body>
</html>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head> <title>My JSP 'jstl.jsp' starting page</title> </head> <body> <%
request.setAttribute("date", new Date());
%> <!-- format库通常情况下是用来进行类型转换的 -->
<%-- <fmt:formatDate value="${date }" pattern="yyyy年MM月dd日hh时mm分ss秒" /> --%> ${fn:length("zhangsan") }<!-- 如果使用functions类库的时候,一定要和el表达式连用,否则无法使用 --> </body>
</html>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head> <title>My JSP 'redirect.jsp' starting page</title> </head> <body>
<c:import url="http://www.baidu.com" charEncoding="utf-8"></c:import>
<c:import url="http://www.qq.com" charEncoding="utf-8"></c:import>
<c:import url="http://www.163.com" charEncoding="utf-8"></c:import>
</body>
</html>

5.权限设置:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://www.bjsxt.com/role/lee" prefix="rl"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head> <title>My JSP 'index.jsp' starting page</title>
</head> <body> <%
request.getSession().setAttribute("role", (int) (Math.random() * 10));
%>
<h1>您的权限为:${role }</h1>
<rl:role min="1">
<input type="button" value="增加" />
<br />
</rl:role>
<rl:role min="3">
<input type="button" value="修改" />
<br />
</rl:role>
<rl:role min="5">
<input type="button" value="删除" />
<br />
</rl:role>
<rl:role min="7">
<input type="button" value="查询" />
<br />
</rl:role> <pre>
1.首先要在WEB-INF创建一个tld文件(标签库描述文件)
2.借鉴官方自带的标准标签库(core.tld)来编写自己的标签
3.创建一个class,并且继承TagSupport,并且重写两个方法:int doStartTag(),int doEndTag();
4.在创建TagRole中定义一个属性,这个属性必须要和<name>min</name>完全一致
</description>
<name>min</name>
<required>true</required>
<!-- 必须填写的属性 -->
<rtexprvalue>true</rtexprvalue>
<!-- 默认为true -->
<type>int</type>
<!-- 返回值的类型 -->
</attribute>
</pre>
</body>
</html>

  role.tld文件

<?xml version="1.0" encoding="UTF-8" ?>

<taglib 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-jsptaglibrary_2_1.xsd"
version="2.1"> <description>权限判定标准标签库</description>
<display-name>tag role</display-name>
<tlib-version>1.0</tlib-version>
<short-name>rl</short-name>
<uri>http://www.bjsxt.com/role/lee</uri><!-- 首先你要以自己公司的域名为准,所有的标签库的URI不允许重名 --> <!-- 开始定义标签 -->
<tag>
<description>
通过标签可以实现菜单的权限管理,使权限控制在按钮层
</description>
<name>role</name><!-- 标签的名字 -->
<tag-class>cn.zzsxt.lee.web.role.TagRole</tag-class><!-- 定义的class -->
<body-content>JSP</body-content><!-- 作用的内容:jsp页面 --> <attribute><!-- 定义标签中属性 -->
<description>
最小权限判定
</description>
<name>min</name>
<required>true</required><!-- 必须填写的属性 -->
<rtexprvalue>true</rtexprvalue><!-- 默认为true -->
<type>int</type><!-- 返回值的类型 -->
</attribute> </tag> </taglib>
package cn.zzsxt.lee.web.role;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport; public class TagRole extends TagSupport { private int min; public int getMin() {
return min;
} public void setMin(int min) {
this.min = min;
} @Override
public int doStartTag() throws JspException {
// startTag在权限开始的时候调用的方法
System.out.println("我是startTag方法,我被调用了");
// 获取到session值
int role = (Integer) this.pageContext.getSession().getAttribute("role");
// role = 6
if (min < role) {
// min代表最小的权限,role代表当前权限,能看到button
System.out.println(SKIP_PAGE);
return EVAL_BODY_INCLUDE;// EVAL_BODY_INCLUDE:显示标签之内的内容<rl:role min="1">这里的内容</rl:role>
}
return SKIP_BODY;//SKIP_BODY:隐藏标签之内的内容
} @Override
public int doEndTag() throws JspException {
// EndTag在权限结束的时候调用的方法
System.out.println("我是end方法,我被调用了");
return EVAL_PAGE;// SKIP_PAGE权限标签的代码后就不再显示任何页面;EVAL_PAGE权限标签后全部显示
}
}