java web 里的JSP 对象的简单了解
1.基本的组成元素
page指令
<%@ page ..........%>
1-1. language---当前页面使用的语言:java
1-2. import---当前页面引入的类库, 默认是啥也不引入 使用Alt/ 快捷键引入
1-3. contentType---text/html; charset='字符集'
1-4. iso-8859-1是字符集的默认值, 纯英文的字符集
1-5. isErrorPage---定义当前页面是否是一个错误提醒页面 默认的是false,但要改为true
1-6. errorPage---定义当当前页面出错时跳转的页面 alt/的快捷键(在%前面),errorPage = "网页"
1-7. include指令 <%@ include file = "网页" %>(静态) ,把其他的页面也包含在这个页面里 先包含再编译
<jsp:include page="..." />--动态包含 此方法使用的居多 先编译再包含
实际应用:
<body>
<!-- 这是一个jsp页面 -->
<%-- <%
String str = "aa";
%> --%>
<%!
String str = "";
%>
<%
//在网页上打印一个九九乘法表
for( int i = 1; i < 10; i++) {
for( int j = 1; j <= i;j++){
str += i+ "*" + j +"=" + i*j; /* 换成字符串的一个拼接 */
str += " "; /* 每一个式子的后面都来一个空格 */
}
str += "<br>"; /* 最外面的for循环是为了 换行 */
}
%>
<%= str%> <!-- 输出内容 -->
</body>
2.内置对象的含义简单理解,用一些实例来看一下
<body>
<form action="test2.jsp" method = "post" >
<input type = "text" name = "test" />
<input type = "submit" value = "提交" />
one <input type = "checkbox" name = "ch" value = "1" /> <br> 复选框
two <input type = "checkbox" name = "ch" value = "2" /> <br>
three<input type = "checkbox" name = "ch" value = "3" /> <br>
four <input type = "checkbox" name = "ch" value = "4" /> <br>
<input type = "submit" value = "提交" />
</form>
<%
application.setAttribute("all", 123); //全局对象
session.setAttribute("save", "存储"); //存储对象
%>
</body>
<body>
<%
String s= request.getParameter("test"); //传递,接收参数
if("host".equals(s)){ //当request里面获取的参数为"host"时
response.sendRedirect("index.jsp"); //重定向
}
String [] s1 = request.getParameterValues("ch"); //接收的是那个复选框的名字
for( String ss : s1) { //遍历
out.print(ss + "<br>"); //out输出流对象
}
Integer i = (Integer)application.getAttribute("all"); //因其返回的为object,所以需要强转一下
out.print(i);
out.print("<br>");
String s2 = (String)session.getAttribute("save"); //因其返回的为object,所以需要强转一下
out.print(s);
%>
</body>
3.提交登录信息,以及解决request中出现中文乱码的问题(post,get的不同处理方式)
<body> <form action="index.jsp" method = "post"> <table> <tr> <td>用户名:</td> <td> <input type = "text" name = "user" /></td> </tr> <tr> <td>密码:</td> <td> <input type = "password" name = "password" /></td> </tr> <tr> <td colspan = 1 > <input type = "submit" value = "提交"/></td> </tr> </table> </form> </body>
当提交方式为post时,解决的方式如下:
<body>
<%
request.setCharacterEncoding("utf-8"); //如果提交方式为post,如果出现中文乱码,用这三条语句解决
response.setCharacterEncoding("utf-8");
response.setContentType("text/html; charset=UTF-8");
String u = request.getParameter("user");
String p = request.getParameter("password");
if( "王大海".equals(u)&& "1234".equals(p)){
/* session.setAttribute("information", u); */
out.print("欢迎!");
} else {
out.print("密码错误!");
}
%>
</body>
当提交的方式为post时,的解决方式,先定义一个方法,之后再调用一下
import java.io.UnsupportedEncodingException;
public class Main { //处理如果是get方式的话,中文乱码的处理方式
public static String convert(String text) {
String msg = null;
try {
msg = new String(text.getBytes("iso-8859-1"), "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return msg;
}
}
浙公网安备 33010602011771号