jsp嵌入java代码

JSP中嵌入java代码的三种方式:

 

    1)声明变量或方法  <%! 声明%> :慎重使用,因为此方法定义的是全局变量

 

    2java片段(scriptlet):  <% java代码%>

 

    3)表达式:用于输出表达式的值到浏览器,<%=表达式  %>  在表达式中不能加分号(;)


JSP页面的指令

    <%@ page %> //这个一般是写在最顶上的比如导入等

    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8" contentType="text/html; charset=UTF-8"%>

 

    指令的作用:设置JSP页面的属性和特征

 

    常用指令:

 

    (1)<%@ page %> <jsp:directive.page  :常用属性:language=""contentType="text/html;charset=UTF-8"

 

    pageEncoding="" import="com.inspur.Dpet"

 

    isErrorPage="true|false" 指定当前页面是否可以作为错误页

 

    errorPage="error.jsp" (error.jsp页面中的isErrorPage="true")

 

    (2)<%@ include file="url"%> <jsp:directive.include >

 

    【注意】静态包含,在编译阶段把其他文件包含进来一起编译生成字节码文件

 

     问题:(1).被包含的文件中不能包含<html></html><body></body>;  

 

        (2).file属性赋值不能用表达式,不能带参数


 

 

HTMLformresetsubmit标签的法:

    <form name=loginForm method=post/get action=”…” οnsubmit=return function()>

    //action的内容是Servlet Mapping当中的URL

    <input type=reset id=reset name=reset value=重置/>

    <input type=submit id=submit name=submit value=登陆/>

    </form>


 

form表单的methodpostget的区别:

Post提交的数据更具隐蔽性,适合提交大批量的数据

http://localhost:8080/booklib/user

 

get提交的数据隐蔽性不好,会在地址栏内显示出来而且地址栏最多允许255个字符

http://localhost:8080/booklib/user?username=admin&password=123&submit=登陆

 

上述这种通过get传输数据的方法也可以通过超链接实现:

<a href="user?username=admin&password=123&submit=登陆"></a>

效果与get方法一样,而且用超链接提交的数据也可以用String  userrname  request.getParameter("username"); 得到数据,其中方法的参数是数据名称即等号前的,值是等号后的。

也可以是:location.href="user?action=del&uid="+uid;  

或:location.replace(""user?action=del&uid="+uid");

Location.href 等同于location.assign。(怎么用?????????)

当使用replace的时候请求的地址不会放到list当中去?????什么意思??

 

Form中的action的值应是web.xml中的url-pattern的值:

Web容器在收到这个值后会解析这个值,然后拿这个值到web.xml中的url-pattern去匹配,直到找到对应的Servlet类,之后通过反射机制生成Servlet实例,然后到Servlet中的service()方法中去,然后根据method请求的是post还是get调用相应的doPost()doGet()方法。



 

如何调用jsp中的request和response对象:

requestresponse对象来源:来自doGet(HttpServletRequest request, HttpServletResponse response)

 

jsp可以直接用,用法如下:

request常用的方法两个即:

request.setAttibute(key,value)/requeset.getAttribute(key)

//一般在Servlet中用setAttribute()

//一般在jsp中用getAttribute()

 

    getAttribuet()得到的是一个对象即Object类型,用时需要进行强制类型转换

request.setCharacterEncoding("UTF-8");

    String username request.getParameter("username");

String password request.getParameter("password");

 

    session对象来源:在doGet()中申明的HttpSession session request.getSession(true);

session:sessioin.setAttribute("key",value); 

//一般在Servlet中用setAttribute()

  (Object)session.getAttribute("key");

//一般在jsp中用getAttribute()

 

Servlet中的RequestDispatcher对象:

RequestDispatcher rd request.getRequestDispatcher(target);

        rd.forward(request,response);


原文链接http://blog.sina.com.cn/s/blog_779cf34101017ixi.html