jsp语法从入门到精通

———–Jsp语法:

1.注释:


2.———实例:

JSP

// 可以使用java注释

/*

可以写入java代码

*/

%>

———–打印9*9表格:scriptlet:脚本小应用程序;

JSP

for (int x = 0; x {

%>

for (int y = 0; y {

%>

}

%>

“)–%>

}

%>

———-html通过表单与服务器交互:

// Demo.html

表单交互

行数:

列数:

// Demo.jsp

JSP

int row = 0; // 行数

int col = 0; // 列数

String rowNum = request.getParameter(“row”); // 获取行数

String colNum = request.getParameter(“col”); // 获取列数

try

{

row = Integer.parseInt(rowNum); // String–>Integer–>int

col = Integer.parseInt(colNum); // 同上

}

catch (Exception e)

{

out.println(“转换,请输入正整数!”);

}

%>

for (int x = 0; x {

%>

for (int y = 0; y {

%>

}

%>

“)–%>

}

%>

———-jsp中的java代码:

JSP

int sum = 0; // 定义变量

for (int x = 0; x {

sum += x;

}

out.println(sum); // 打印sum

%>

// jsp源文件中的html元素将以流的方式输出到客户端浏览器上!

———page指令:
page表示一个jsp页面,是一个对象的本身,每个jsp页面是个对象;
—编码乱码:encoding.jsp

你好,中国!

——-tomcat/conf/web.xml的mime映射配置:

/*

htm

text/html

html

text/html

doc

application/msword

*/

// 通过恰当的设置MIME映射,可以将页面以各种格式显示
// 比如可以让一个jsp以doc扩展名显示!只需:

—-在jsp页对象中导入其他包:

中国,你好!

——–jsp连接mysql数据库,平台:ubuntu 9.10;
//准备:首先确保当前帐号拥有完全正常使用的tomcat实例!:

public static final String DBDRIVER = “com.mysql.jdbc.Driver”;

public static final String DBURL = “jdbc:mysql://localhost:3306/school”;

public static final String DBUSER = “root”;

public static final String DBPASS = “123456”;

%>

try

{

Class.forName(DBDRIVER); // 加载驱动,

}

catch (ClassNotFoundException e)

{

e.printStackTrace();

}

Connection conn = null; // 准备数据库连接

PreparedStatement pstmt = null; // 预处理语句

ResultSet rs = null; // 接收结果集

try

{

conn = DriverManager.getConnection(DBURL, DBUSER, DBPASS); // 获取连接

String = “select id, name, age, sex, birthday from student order by id asc”;

pstmt = conn.prepareStatement(); // 获取预操作对象

rs = pstmt.executeQuery();

}

catch (SQLException e)

{

e.printStackTrace();

}

%>

while (rs.next())

{

int id = rs.getInt(1); // 获取id

String name = rs.getString(2);

int age = rs.getInt(3);

String sex = rs.getString(4);

java.util.Date date = rs.getDate(5);

%>

}

%>

rs.close();

pstmt.close();

conn.close();

%>

ID 姓名 年龄 性别 生日

———–include语句:

—include.jsp: 静态包含:包含静态文件:

JSPinclude

—include.html:

include.html

—include.txt

include.txt

—include.inc:

include.inc

/* 请求:include.jsp:

JSPinclude

include.html

include.txt

include.inc

*/

—jsp:include指令,动态包含
若包含的是jsp,则处理好后再包含,如果是非jsp的静态文件,则直接包含进来;
两种类型:
1.
2.
               
                ………..
       

—–使用语法一:

JSPinclude

效果和        等同;
—–使用语法二:
// jspinclude.jsp

hello

// in.jsp:

变量传递

public static final String str = “www.k187.com”;

%>

// content.jsp:

跳转之后的页面

——–jsp:forward,动态跳转,变量传递;

public static final String str = “www.k187.com”;

%>

跳转之后的页面

// 以上跳转方式地址栏都不发生变化;

——–内置对象:
1.pageContext,javax.servlet.jsp.PageContext;
2.request,     javax.servlet.http.HttpServletRequest;
3.response:           javax.servlet.http.HttpServletResponse;
4.session:     javax.servlet.http.HttpSession;
5.application: javax.servlet.ServletContext;
6.config:      javax.servlet.ServletConfig;
7.out:         javax.servlet.jsp.JspWriter;
8.page:        java.lang.Object;
9.exception:   java.lang.Throwable;
——-四种属性范围:
1.pageContext:当前页作用域,只能在一个页面中取得本页面设置的属性;
2.request:一次服务器请求范围,页面属性在经过服务器的跳转后,仍然可以访问;
3.application:上下文中,整个服务器上设置的;
4.session:一次会话,一个用户设置的内容,只有与此用户相关的页面都可以访问;
四种属性范围,共享以下属性操作:
1.设置:

public void setAttribute(String name, Object value);

2.删除:

public void removeAttribute(String name);

3.取得:

public Object getAttribute(String name);

—-pageContext页面属性范围:
一个页面内设置的属性,跳到其他页面则无法访问,使用pageContext对象完成,表示一个页面中的上下文,不同与page;
—访问本页面属性:

pageContext.setAttribute(“name”, “k187”);

pageContext.setAttribute(“date”, new Date());

%>

String getName = (String)pageContext.getAttribute(“name”);

Date getDate = (Date)pageContext.getAttribute(“date”);

%>

用户名:

——-request属性范围:
当前页面在服务器端跳转到其他页面,属性可以访问();
当前页面包含其他页面,属性仍然可以访问();
将跳到新页面,只是客户端url不变;
将以页面的一部分包含进来被包含的页面,同时url也不变;
此种跳转与次数无关!
但跳转只能是在同一运行时进行时才会具有request范围,即跳转必须发生在服务器端;
当在客户端以超链接形式跳转时,将不是同一个request范围!
但同一页面定义的局部变量(不是属性),在不同的页面将不能访问!
局部变量应该有page作用域!
// request.jsp

request.setAttribute(“name”, “k187”);

request.setAttribute(“date”, new Date());

%>

String rname = (String)request.getAttribute(“name”);

Date rdate = (Date)request.getAttribute(“date”);

%>

用户:

—-rq.jsp

String rname1 = (String)request.getAttribute(“name”);

Date rdate1 = (Date)request.getAttribute(“date”);

%>

用户:

—服务器端的跳转与客户端的跳转不算同一个request范围:
// 属性的作用域是由属性存在的运行时决定的!
// 当运行时对服务器只进行一次动态请求,则是一个request;
// 但若客户端通过链接请求另一个jsp页面,则是另一个request,这是另一次调用服务器;

request.setAttribute(“name”, “k187”);

request.setAttribute(“date”, new Date());

%>

String rname = (String)request.getAttribute(“name”);

Date rdate = (Date)request.getAttribute(“date”);

%>

用户:

跳转页面

// a.jsp

String rname = (String)request.getAttribute(“name”);

Date rdate = (Date)request.getAttribute(“date”);

%>

用户:

———session属性范围:
当前用户访问服务器后,规定的持续链接时间内,无论页面如何跳转,都可以访问:
// session.jsp:

session.setAttribute(“name”, “k187”);

session.setAttribute(“date”, new Date());

%>

String rname = (String)session.getAttribute(“name”);

Date rdate = (Date)session.getAttribute(“date”);

%>

用户:

时间:

–%>

跳转页面

// 客户端第二次跳转:a.jsp

String rname = (String)session.getAttribute(“name”);

Date rdate = (Date)session.getAttribute(“date”);

%>

用户:

时间:

第二次跳转

//session用来判断是否是同一个用户,如果在其他电脑上,或另一个浏览器访问a.jsp或b.jsp则无法获取属性设置!
——application属性范围:
这是在服务器每次开启时创建的对象,此对象范围内的所有属性可以被所有用户显式获取!
与跳转无关!
此范围属性的设置,会影响到服务器的性能!
——–实际应用当中属性范围的设置:
在设置属性时,同时指定该属性的作用域:这必须在pageContext对象中设置:
器中内置PageContext的实例pageContext对象,定义了四种全局常量:
// 分别表示四种属性范围:

1.static int APPLICATION_SCOPE

Application scope: named reference remains available in the ServletContext until it is reclaimed.

2.static int PAGE_SCOPE

Page scope: (this is the default) the named reference remains available in this PageContext until the return from the current Servlet.service() invocation.

3.static int REQUEST_SCOPE

Request scope: the named reference remains available from the ServletRequest associated with the Servlet until the current request is completed.

4.static int SESSION_SCOPE

Session scope (only valid if this page participates in a session): the named reference remains available from the HttpSession (if any) associated with the Servlet until the HttpSession is invalidated.

// 以下方法用于设置当前页面上下文中不同访问范围的属性:

public abstract void setAttribute(String name,

Object value,

int scope) // 其他页面中只有在可以访问到的属性范围内才可访问本页设置的属性;

Register the name and value specified with appropriate scope semantics. If the value passed in is null, this has the same effect as calling removeAttribute( name, scope ).

—在页面中设置不同访问范围的属性:

application.setAttribute(“name”, “k187”, PageContext.APPLICATION_SCOPE);

application.setAttribute(“date”, new Date(), PageContext.APPLICATION_SCOPE);

%>

session.setAttribute(“name1”, “k187”, PageContext.SESSION_SCOPE);

session.setAttribute(“date1”, new Date(), PageContext.SESSION_SCOPE);

%>

request.setAttribute(“name2”, “k187”, PageContext.REQUEST_SCOPE);

request.setAttribute(“date2”, new Date(), PageContext.REQUEST_SCOPE);

%>

pageContext.setAttribute(“name3”, “k187”, PageContext.PAGECONTEXT_SCOPE);

pageContext.setAttribute(“date3”, new Date(), PageContext.PAGECONTEXT_SCOPE);

%>

String rname = (String)application.getAttribute(“name”);

Date rdate = (Date)application.getAttribute(“date”);

%>

用户:

时间:

–%>

跳转页面

—————ServletRequest:

public interface ServletRequest;// javax.servlet;

Defines an object to provide client request information to a servlet. The servlet container creates a ServletRequest object and passes it as an argument to the servlet's service method.
A ServletRequest object provides data including parameter name and values, attributes, and an input stream. Interfaces that extend ServletRequest can provide additional protocol-specific data (for example, HTTP data is provided by HttpServletRequest.

public interface HttpServletRequest

extends ServletRequest;// ServletRequest的子接口!支持http协议

Extends the ServletRequest interface to provide request information for HTTP servlets.
The servlet container creates an HttpServletRequest object and passes it as an argument to the servlet's service methods (doGet, doPost, etc).
——–request乱码:
当客户端浏览器的编码与服务器发送页面使用的编码不同时会产生乱码,此时可以手动调整浏览器的默认编码,一般这种情况很少发生,因为服务器发送的页面中会有当前页面的编码信息,浏览器会根据该信息以正确的编码显示当前页面,所以我们可以浏览编码完全不同的服务器上的网页,但不必手动设置浏览器的字符编码;
但还有另种情况:
当客户端的系统默认编码与所请求的页面所在的服务器端的默认编码不同时:比如,客户端:GBK,服务器端:utf8;
而且,此时需要客户端通过所请求的页面,提交非英文的信息(如在表单中提交中文)到动态网页(需要服务器的web容器处理),,
此时,提交的中文信息在客户端采用GBK编码,到服务器端则会采用服务器默认的编码:utf8进行对编码格式为GBK的信息的解码和编码操作,则肯定提交的信息是乱码,服务器处理完毕后会以本地编码utf8发送请求结果页面给客户端,客户端浏览器收到的编码信息是utf8,则其他页面信息正常,唯独提交的信息显示为乱码;
这种乱码是客户端向服务器发送了服务器端不识别的编码造成的,服务器端的错误编码是根本原因;
——-模拟request乱码产生的环境:
// 准备提交表单信息的html:

function validate(form)

{

var unLen = form.info.value.replace(/[^\x00-\xff]/g, "**").length;

if(unLen 15)

{

alert("用户名必须5-15位!");

form.info.focus();

return false;

}

return true;

}

用户名:

// 准备请求的jsp页面:

// 这是必须的,否则客户端浏览器不知道采用何种编码显示该页面!

String str = request.getParameter(“info”); // 服务器端接收该参数同时以服务器端默认的字符集编码方式进行解码并保存,如果info采用了与本地不同的编码,显然解码错误!这是乱码产生的源头!

%>

你好,

// 表达式内容是服务器端处理的,输出到客户端时采用服务器端的默认编码
// 注意:在本地测试时,由于服务器和客户端是同一台机器,浏览器接收和提交的信息必定都是采用本地(与服务器相同)的编码,
// 所以不会出现提交信息的请求乱码,但是可以手动设置当前浏览器编码为GBK(与服务器不同),会出现乱码,然后输入信息请求,
// 请求的页面input.jsp自然是乱码,但此时将浏览器的编码调整为和服务器相同(如utf8),则提交的信息是乱码,而其他信息正常;
//
—-解决方法:

request.setCharacterEncoding(“utf8”); // 以中文接收 ,

String str = request.getParameter(“info”); // info可能采用非utf8编码

//str = new String(str.getBytes(“GBK”)); // 有时候不管用

%>

你好,

——-response内置对象:
// ServletResponse:

public interface ServletResponse; // servlet对客户端的响应

Defines an object to assist a servlet in sending a response to the client. The servlet container creates a ServletResponse object and passes it as an argument to the servlet's service method.
// HttpServletResponse:

public interface HttpServletResponse // 遵循http协议的

extends ServletResponse;// ServletResponse的接

口,表示服务器的响应
Extends the ServletResponse interface to provide HTTP-specific functionality in sending a response. For example, it has methods to access HTTP headers and cookies.
The servlet container creates an HttpServletResponse object and passes it as an argument to the servlet's service methods (doGet, doPost, etc). // response对象是由servlet容器创建的HttpServletResponse的对象;
/方法:

void setHeader(String name,

String value) ;// 设置头信息

Sets a response header with the given name and value. If the header had already been set, the new value overwrites the previous one. The containsHeader method can be used to test for the presence of a header before setting its value.
    Parameters:
        name – the name of the header
        value – the header value If it contains octet string, it should be encoded according to RFC 2047 (https://www.ietf.org/rfc/rfc2047.txt)
/

void addCookie(Cookie cookie); // 添加cookie

Adds the specified cookie to the response. This method can be called multiple times to set more than one cookie.
    Parameters:
        cookie – the Cookie to return to the client
/

void sendRedirect(String location)

throws IOException;// 跳转到指定的url

Sends a temporary redirect response to the client using the specified redirect location URL. This method can accept relative URLs; the servlet container must convert the relative URL to an absolute URL before sending the response to the client. If the location is relative without a leading ‘/' the container interprets it as relative to the current request URI. If the location is relative with a leading ‘/' the container interprets it as relative to the servlet container root.
    If the response has already been committed, this method throws an IllegalStateException. After using this method, the response should be considered to be committed and should not be written to.
    Parameters:
        location – the redirect location URL
/方法:

String getContentType();// 返回响应定义的内容类型

Returns the content type used for the MIME body sent in this response. The content type proper must have been specified using setContentType(java.lang.String) before the response is committed. If no content type has been specified, this method returns null. If a content type has been specified, and a character encoding has been explicitly or implicitly specified as described in getCharacterEncoding() or getWriter() has been called, the charset parameter is included in the string returned. If no character encoding has been specified, the charset parameter is omitted.
    Returns:
        a String specifying the content type, for example, text/html; charset=UTF-8, or null  
// HttpServletRequest:
方法:

Enumeration getHeaderNames();// 获取请求方的全部头信息名字

Returns an enumeration of all the header names this request contains. If the request has no headers, this method returns an empty enumeration.
    Some servlet containers do not allow servlets to access headers using this method, in which case this method returns null
    Returns:
        an enumeration of all the header names sent with this request; if the request has no headers, an empty enumeration; if the servlet container does not allow servlets to use this method, null
/

String getHeader(String name);// 返回指定头信息的内容

Returns the value of the specified request header as a String. If the request did not include a header of the specified name, this method returns null. If there are multiple headers with the same name, this method returns the first head in the request. The header name is case insensitive. You can use this method with any request header.
    Parameters:
        name – a String specifying the header name
    Returns:
        a String containing the value of the requested header, or null if the request does not have a header of that name
——-获取头信息:
—-实例:

Enumeration e = request.getHeaderNames(); // 接收传递的所有头信息的名字

%>

while (e.hasMoreElements())

{

String paraName = (String)e.nextElement(); // 获取当前参数名

%>

:

}

%>

————————————————————
// 第一次客户端请求:返回的头信息:
host: localhost
user-agent: Mozilla/5.0 (X11; U; Linux i686; zh-CN; rv:1.9.1.9) Gecko/20100401 Ubuntu/9.10 (karmic) Firefox/3.5.9
accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
accept-language: zh-cn,zh;q=0.5
accept-encoding: gzip,deflate
accept-charset: GB2312,utf-8;q=0.7,*;q=0.7
keep-alive: 300
connection: keep-alive
referer: https://localhost/pro/checkbox.html
content-type: application/x-www-form-urlencoded
content-length: 5
// 第二次客户端请求:返回的头信息:
host: localhost
user-agent: Mozilla/5.0 (X11; U; Linux i686; zh-CN; rv:1.9.1.9) Gecko/20100401 Ubuntu/9.10 (karmic) Firefox/3.5.9
accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
accept-language: zh-cn,zh;q=0.5
accept-encoding: gzip,deflate
accept-charset: GB2312,utf-8;q=0.7,*;q=0.7
keep-alive: 300
connection: keep-alive
referer: https://localhost/pro/checkbox.html
cookie: JSESSIONID=A0C40E8E4D4DD6C3118E3B4EB2E89995 # 增加的信息
cache-control: max-age=0 # 增加的信息
content-type: application/x-www-form-urlencoded
content-length: 5
// 无表单请求时,第一次客户端请求返回的头信息:
host: localhost
user-agent: Mozilla/5.0 (X11; U; Linux i686; zh-CN; rv:1.9.1.9) Gecko/20100401 Ubuntu/9.10 (karmic) Firefox/3.5.9
accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
accept-language: zh-cn,zh;q=0.5
accept-encoding: gzip,deflate
accept-charset: GB2312,utf-8;q=0.7,*;q=0.7
keep-alive: 300
connection: keep-alive
// 无表单请求时,第二次客户端请求返回的头信息:
host: localhost
user-agent: Mozilla/5.0 (X11; U; Linux i686; zh-CN; rv:1.9.1.9) Gecko/20100401 Ubuntu/9.10 (karmic) Firefox/3.5.9
accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
accept-language: zh-cn,zh;q=0.5
accept-encoding: gzip,deflate
accept-charset: GB2312,utf-8;q=0.7,*;q=0.7
keep-alive: 300
connection: keep-alive
cookie: JSESSIONID=95F05A0F95E7FAFA36118294771A19A9 # 增加了cookie
cache-control: max-age=0 # 增加了
// 上面这些信息是http协议自动生成的,用户也可以自定义,回应给客户端!
// 其中定时刷新是比较有用的类型:refresh:
// 使用以下方法可以设置:

void setHeader(String name,

String value);

Sets a response header with the given name and value. If the header had already been set, the new value overwrites the previous one. The containsHeader method can be used to test for the presence of a header before setting its value.
    Parameters:
        name – the name of the header 比如:refresh头信息表示定时刷新
        value – the header value If it contains octet string, it should be encoded according to RFC 2047 (https://www.ietf.org/rfc/rfc2047.txt);比如:定时刷新的时间间隔;
—-实例:

int temp = 0;

%>

response.setHeader(“refresh”, “2”); // 设置refresh头信息,每2秒刷新一次

%>

—实例二,实现定时跳转:

int temp = 0;

%>

response.setHeader(“refresh”, “2;URL=input.jsp”); // 设置refresh头信息,2秒后自动跳转到input.jsp

%>

如果没有跳转,请按

这里

// 此时的跳转,浏览器的url改变了,属于客户端跳转!
// 也可以直接用http内置的头信息设置方法,定义定时跳转:
—实现定时跳转的html:

如果没有跳转,请按

这里

——-respons对跳转的支持:
—客户端端跳转:

response.sendRedirect(“input.jsp”);

%>

—实现跳转时传递参数:

response.sendRedirect(“input1.jsp?ref=hello!”);

%>

// 接收参数jsp:

—–服务器跳转与客户端跳转的区别:
使用:服务器跳转:
1.地址栏不变,
2.执行到跳转后无条件跳转—之后的代码不再执行;
3.若使用此种跳转,一定要保证跳转后释放掉全部的资源(比如数据库链接);
4.跳转后,设置的request属性仍然保留,(setAttribute());
使用:response.sendRedirect(“url”)重定向:
1.地址栏改变,客户端跳转
2.所有代码执行完毕后再跳转;
3.不再保存request属性—地址改变了, 客户端跳转,属于请求的改变!
使用重定向客户端跳转时,可以借助重写url的操作,传递必要的参数到跳转后的页面!

声明: 除非转自他站(如有侵权,请联系处理)外,本文采用 BY-NC-SA 协议进行授权 | 智乐兔
转载请注明:转自《jsp语法从入门到精通
本文地址:https://www.zhiletu.com/archives-190.html
关注公众号:智乐兔

赞赏

wechat pay微信赞赏alipay pay支付宝赞赏

上一篇
下一篇

相关文章

在线留言

你必须 登录后 才能留言!

在线客服
在线客服 X

售前: 点击这里给我发消息
售后: 点击这里给我发消息

智乐兔官微