Bem-Vindo, Visitante
Username: Password: Lembrar-me
Publique dúvidas e ajude seus colegas com soluções e experiências vivenciadas
  • Página:
  • 1

TÓPICO: Trabalho Java

Trabalho Java 8 anos 6 mêses atrás #1

  • Mailson
  • Mailson's Avatar
  • OFFLINE
  • Novato
  • Postagens: 1
  • Karma: 0
// Código Controller

package br.ueg.posse.cadastro.controller;

import java.sql.SQLException;
import java.util.List;

import javax.validation.Valid;

import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.portlet.ModelAndView;

import br.ueg.posse.cadastro.dao.ClienteDAO;
import br.ueg.posse.cadastro.modelo.Cliente;

public class ClienteController {

@RequestMapping("/adicionar1")
public String execute(){
return"formulario-cadastro-cliente";
}


@RequestMapping("/adicionaCliente")
public String adiciona(@Valid Cliente cliente, BindingResult result)
throws SQLException {

if(result.hasErrors()){
return "formulario-cadastro-cliente";

}else{
ClienteDAO dao = new ClienteDAO();
dao.adiciona(cliente);
return "cliente-adicionado";
}

}

@RequestMapping("/listaCliente")
public ModelAndView lista () throws SQLException{
ClienteDAO dao = new ClienteDAO();
List<Cliente> clientes = dao.lista();
ModelAndView mv = new ModelAndView("lista-clientes");
mv.addObject("clientes", clientes);
return mv;
}


@RequestMapping("/excluirCliente")
public String remove(Cliente cliente) throws SQLException {
ClienteDAO dao = new ClienteDAO();
dao.remove(cliente);
return"redirect:listaCliente";
}
}


// Código View

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib uri="www.springframework.org/tags/form" prefix="form" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "www.w3.org/TR/html4/loose.dtd">
<script src="js/bootstrap.min.js"> </script>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Cadastro de Cliente</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<h2> Cadastro de Clientes </h2>

<div class="container">
<fieldset>
<form action="adicionaCliente" method="post">
Nome:<input type="text" size="60" maxlength="60" name="nome"/>
<form:errors path="cliente.nome"/>
<br/>
CPF:<input type="text" size="50" maxlength="50" name="cnpj"/>
<form:errors path="cliente.cpf"/>
<br/>
Endereço:<input type="text" size="20" maxlength="20" name="endereco"/>
<form:errors path="cliente.endereco"/>
<br/>
Telefone:<input type="text" size="20" maxlength="20" name="telefone"/>
<form:errors path="cliente.telefone" />
<br/>
</select>
<br>
<input type="submit" value="Gravar" name="gravar"/>
<input type="reset" value="Limpar" name="limpar"/>
</form>
</fieldset>
</div>
</body>
</html>
O administrador desabilitou o acesso público de escrita.

Trabalho Java 8 anos 6 mêses atrás #2

  • ronaldo
  • ronaldo's Avatar
  • OFFLINE
  • Administrador
  • Postagens: 22
  • Thank you received: 7
  • Karma: 1
Existe a view cliente-adicionado.jsp?
O administrador desabilitou o acesso público de escrita.

Criando o Login com Interceptors 8 anos 6 mêses atrás #3

  • ronaldo
  • ronaldo's Avatar
  • OFFLINE
  • Administrador
  • Postagens: 22
  • Thank you received: 7
  • Karma: 1
// Formulário de login

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Login no Sistema</title>
</head>
<body>
<form action="efetuaLogin" method="post">
Usuário: <input type="text" name="login"/><br>
Senha:<input type="password" name="senha"/><br>
<input type="submit" value="Login no sistema">
</form>
</body>
</html>



// Controller

@Controller
public class UsuarioController{

@RequestMapping("/loginForm")
public String login(){
return "usuario/login";
}

@RequestMapping("/efetuaLogin")
public String efetuaLogin(Usuario usuario, HttpSession session)
throws SQLException{
UsuarioDAO dao = new UsuarioDAO();
if (dao.existeUsuario(usuario)){
session.setAttribute("usuarioLogado",
StringToMD5.convert(usuario.getLogin()));
return "menu";
}
return "redirect:loginForm";
}

}


// DAO
//OBS.: Necessário criar a classe de conexão e StringToMD5
public class UsuarioDAO {

private Connection conexao = null;

public UsuarioDAO()throws SQLException{
conexao = Database.getConnection();
}

public boolean existeUsuario(Usuario usuario) {

try {
String senhaMD5 = StringToMD5.convert(usuario.getSenha());
PreparedStatement stmt = this.conexao
.prepareStatement("select * from " +
"usuario where login = ? " +
"and senha = ?");
stmt.setString(1, usuario.getLogin());
stmt.setString(2, senhaMD5);
ResultSet rs = stmt.executeQuery();
boolean encontrado = rs.next();
rs.close();
stmt.close();
conexao.close();
return encontrado;
}catch (SQLException e) {
throw new RuntimeException(e);
}
}

}

// criando o interceptador

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

public class AutorizadorInterceptor extends
HandlerInterceptorAdapter{

@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler)
throws Exception{
String uri = request.getRequestURI();
if (uri.endsWith("loginForm") || uri.endsWith("efetuaLogin")
|| uri.contains("resources")){
return true;
}

if (request.getSession().
getAttribute("usuarioLogado") != null){
return true;
}else{
response.sendRedirect("loginForm");
return false;
}
}

}
O administrador desabilitou o acesso público de escrita.
  • Página:
  • 1
Tempo de criação da página: 0.206 segundo(s)

Destaques

Links Importantes