
<%! String nome = “José”; %> <%! int numero, idade, altura; %> <%! boolean fim = false; int peso = 10; %>
- <%= %> - Declaração de expressão, o resultado é retornado como um String
<%= 2 + 2 %> // Será retornado o String “4”
- <% %> - Declaração de sintaxe, declaração livre.
<% for( int i= 0; i< 10; i++){ out.println(“ numero: “+ i); }%>
| Declarações | Declara variáveis e métodos válidos no script daquela página. | <%! declaração; [declaração;]+ ... %> |
| Expressões | Contém uma expressão válida no script daquela página. | <%= expressão %> |
| Scriptlet | Contém um fragmento de código válido no script daquela página. | <% fragmento de um código com uma ou mais linhas %> |
| Comentário HTML | Cria um comentário que é enviado para o cliente viabilizar no código da página. | <!-- comentário [<%= expressão %>] --> |
| Comentário JSP | É visto apenas no fonte do JSP mas não é enviado para o cliente. | <%-- comentário --%> ou <% /* comentário */ %> |
| Diretiva "Include" | Inclue um arquivo estático, analisando os elementos JSP daquela página. | <%@ include file="URL relativa" %> |
| Diretiva "Page" | Define atributos que serão aplicados a uma página JSP. | <%@ page [ atributo = valor(es) ] %> atributos e valores: - language="java" - extends = "package.class" - import = "{package.class" | package.* }, ..." ] - session = "true | false" - buffer = "none | 8kb | sizekb" - autoFlush = "true | false" - isThreadSafe = "true | false" - info = "text" - errorPage"relativeURL" - contentType = "{mimeType [; charset = characterSet ] text/html; charset = isso-8859-1}" - isErrorPage = "true | false" |
| <tagPrefix:name> | Acessa um padrão de funcionalidade de uma tag. | <tagPrefix:name attribute="value" + ...
/> <tagPrefix:name attribute="value" + ... > other tags and data </tagPrefix:name> |
| <jsp:foward> | Redireciona uma requisição para um arquivo HTML, JSP ou servlet para processar. | <jsp:forward page="{relativeURL | <%= expressão %>}" |
<jsp: useBean> <jsp: useBean id=“ user” scope=“ session” class=“ exemplos. Usuario”/>
<jsp: setProperty name=“ user” property=“ nome” value=“ José da Silva” />
<jsp: setProperty name=“ user” property=“ nome” param=“nomeUsuario” />
<jsp: setProperty name=“ user” property=“*” />
<jsp: getProperty name=“ user” property=“ nome” /> <jsp: getProperty name=“ user” property=“ idade” />
<jsp: setProperty name=“ nomeBean” property=“*” />
public class Usuario {
private String login;
private String senha;
private String nome;
private String email;
private String telefone;
private String endereco;
public Usuario() {
this("","");
this.nome = "";
this.email = "";
this.telefone = "";
this.endereco = "";
}
public Usuario(String login, String senha){
this.login = login;
this.senha = senha;
}
public void setLogin(String login){
this.login = login;
}
public String getLogin(){
return this.login;
}
public void setSenha(String senha){
this.senha = senha;
}
public String getSenha(){
return this.senha;
}
public void setNome(String nome){
this.nome = nome;
}
public String getNome(){
return this.nome;
}
public void setEmail(String email){
this.email = email;
}
public String getEmail(){
return this.email;
}
public void setTelefone(String telefone){
this.telefone = telefone;
}
public String getTelefone(){
return this.telefone;
}
public void setEndereco(String endereco){
this.endereco = endereco;
}
public String getEndereco(){
return this.endereco;
}
public String toString(){
return "login : "+login+
"\nsenha : "+senha+
"\nnome : "+nome+
"\nemail : "+email+
"\nendereco : "+endereco+
"\ntelefone : "+telefone;
}
}
<%@page import="exemplos.Usuario" %> <jsp:useBean id="user" scope="request" class="Usuario" /> <html> <head> <title>Exemplo com Bean</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> </head> <body bgcolor="#FFFFFF"> <%@ include file="cabecalho.txt" %> <h3><font face="Arial, Helvetica, sans-serif">Cadastro de Usuários</font> </h3> <form name="form1" method="post" action="cadastrar.jsp"> <p>Login: <input type="text" name="login"> <br> Senha: <input type="text" name="senha"> <br> Nome: <input type="text" name="nome"> <br> e-mail: <input type="text" name="email"> <br> Endereço: <input type="text" name="endereco"> <br> Telefone: <input type="text" name="telefone"> </p> <p> <input type="submit" name="Submit" value="Submit"> </p> </form> <p> </p> <%@ include file="rodape.txt" %> </body> </html>
<%@ page isErrorPage=" true" %>
<%@ page errorPage=“ error. jsp" %>
<%@page isErrorPage="true" %> <html> <head> <title>Página de Erros</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> </head> <body bgcolor="#FFFFFF"> <%@ include file="cabecalho.txt" %> <h3><font face="Arial, Helvetica, sans-serif">Página de erros</font></h3> <h4><font face="Arial, Helvetica, sans-serif">Ocorreu uma exceção: <%=exception.toString()%> </font></h4> <pre> <%exception.printStackTrace();%> </pre> <p><%@ include file="rodape.txt" %> </p> <p> </p></body> </html><%@page errorPage="erros.jsp"%> <html> <head> <title>Exemplo de tratamento de Exceções</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <% String numero = request.getParameter("numero"); if(numero != null){ int teste = Integer.parseInt(numero); } %> </head> <body bgcolor="#FFFFFF"> <%@ include file="cabecalho.txt" %> <h3><font face="Arial, Helvetica, sans-serif">Exemplo de tratamento de Exceções</font></h3> <p>Para causar uma exceção, digite: exemploExcecao.jsp?numero=x</p> <p><%@ include file="rodape.txt" %> </p> <p> </p></body> </html>
<%@page import="Usuario" %> <% String msg = (String)request.getAttribute("mensagem"); if(msg == null) msg = ""; %> <jsp:useBean id="user" scope="request" class="Usuario" /> <html> <head> <title>Exemplo Login</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> </head> <body bgcolor="#FFFFFF"> <%@ include file="cabecalho.txt" %> <h1><font face="Arial, Helvetica, sans-serif">Cadastro de Usuários</font> </h1> <h3><font color="#FF0000"><%=msg%></font></h3> <h4>Forneça seu login e senha:</h4> <form name="form1" method="post" action="/curso/servlet/exemplos.LoginServlet"> <p>Login: <input type="text" name="login" value="login"> <br> Senha: <input type="text" name="senha" value="senha"> <br> </p> <p> <input type="submit" name="Submit" value="Submit"> </p> </form> <p> </p> <%@ include file="rodape.txt" %> </body> </html>import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class LoginServlet extends HttpServlet { public void init(ServletConfig config) throws ServletException { super.init(config); } public void destroy(){ super.destroy(); } public void service (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { RequestDispatcher dispatcher = null; String login = request.getParameter("login"); String senha = request.getParameter("senha"); if(!check(login) || !check(senha)){ request.setAttribute("mensagem","Todos os campos devem ser preenchidos"); dispatcher = getServletContext().getRequestDispatcher("/exemplos/login.jsp"); }else if(!checkUsuario(login,senha)){ request.setAttribute("mensagem","Login e senha Inválidos"); dispatcher = getServletContext().getRequestDispatcher("/exemplos/login.jsp"); }else{ HttpSession session = request.getSession(); session.setMaxInactiveInterval(60*60); // 1 hora session.setAttribute("usuario",getUsuario()); dispatcher = getServletContext().getRequestDispatcher("/exemplos/comprar.jsp"); } if(dispatcher == null){ response.sendError(response.SC_NO_CONTENT); }else{ dispatcher.forward(request,response); } } }