Ir para conteúdo

Arquivado

Este tópico foi arquivado e está fechado para novas respostas.

gtamele

Spring + JSP (a URL não está sendo carregada no Browser)

Recommended Posts

Estou a enfrentar um comportamento um tanto quanto estranho no meu projecto que usa Maven+Spring+Hibernate+JSP. Quando acciono um botão no formulário,tudo flui normalmente (a URL correspondente é accionada e a lógica corresponde ao método ligada a mesma URL é executada), porém, o possível retorno do método não se reflecte no formulário porque a URL não é carregada no browser. O mais intrigante é que não arrebenta nenhum erro, o que faz tornar-se mais complicado superar esta anomalia. Alguém sabe dizer qual pode ser a razão desta anomalia? Estou a dias batendo cabeça com esta situação sem sucesso! Preciso de adicionar alguma biblioteca, ou qualquer coisa do género? Vide o códgo:

Form:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core"  prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<%@    taglib tagdir="/WEB-INF/tags" prefix="sb" %>


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    
        <link href="<c:url value="/resources/css/sigraStyle.css" />" rel="stylesheet"> 
        <link type="text/css" href="resources/css/jquery-ui-1.10.1.custom.css" rel="stylesheet"> 
         
        <script type="text/javascript" src="resources/js/jquery-1.9.1.js"></script>
        <script type="text/javascript" src="resources/js/jquery-ui-1.10.1.custom.js"></script>
    
    <title>Insert title here</title>
    
        
    
    
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
     <!--<script src="http://code.jquery.com/jquery-latest.min.js"></script> -->
    
    <script type="text/javascript" >

    
    function remove(selfId){
        
        $.get("remove",{'selfId':selfId});
    }

    function cancelar(){

        $.get("cancelar");
    }
    

       $(document).ready(function() {
           $("#deptForm").submit(function(e) {
               if(!validar()) {
                   e.preventDefault();
               }
           });             
       });


    function validar(){

        if (document.getElementById('designacao').value == ''){
            alert("O campo 'Designacao' deve ser preenchido");
            return false;
        }
        if (document.getElementById('descricao').value == ''){
            alert("O campo 'Descricao' deve ser preenchido");
            return false;
        }                             
        
        return true;
    }
        
    </script>
    
    </head>
    <body>
        
    <c:import url="/cabecalho.jsp" />     
    
        <form id="deptForm" action="/sigra/dept/save" method="post" modelAttribute="dept" >
        
            <fieldset>
                
                <h4 align="center"> CADASTRO DE DEPARTAMENTO</h4>
                <table width="100%">
                    <tr>
                        <td align="center" colspan="3"> 
                            <font color="blue"> 
                                ${statusMsg} 
                            </font>
                        </td>
                    </tr>    
                    <tr>
                    <td>&nbsp;</td>
                    </tr>
                    <tr>
                        <td>
                            <fieldset>
                                <table>
                                    <tr>
                                        <td>
                                            <c:if test="${dept.selfId!=null && dept.selfId>0}">
                                                <input  name="selfId" id="selfId" value="${dept.selfId}" hidden="true">
                                            </c:if>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td width="15%">
                                            <label> Designa&ccedil;&atilde;o:</label>
                                        </td>
                                        <td width="85%">
                                            <span id="refresh_01">                
                                                <input type="text" id="designacao" name="designacao" style=" width: 100%" value="${dept.designacao}" >
                                            </span>
                                        </td>
                                        
                                    </tr>
                                    <tr>
                                        <td width="15%">    
                                            <label>Descri&ccedil;&atilde;o:</label>
                                        </td>
                                        <td width="85%">
                                            <span id="refresh_02">
                                                <textarea name="descricao" id="descricao" rows="5" cols="40" style="width: 100%" >${dept.descricao}</textarea>
                                            </span>
                                        </td>
                                    </tr>
                                    
                                </table>
                            </fieldset>
                        </td>
                    </tr>
                    <tr>
                        
                        <td>
                            <fieldset>
                                <table>
                                    <tr>
                                        <td>
                                    <!--  <a id="save"  href="/sigra/dept/save.html" onclick="testFunction()">teste</a> -->    
                                        </td>
                                        <td>
                                            <c:choose>
                                                <c:when test="${(dept.selfId == null )|| (dept.selfId==0) }">
                                                    <input type="submit" name="action" value="Salvar" >
                                                    <input type="reset" value="Limpar" >
                                                </c:when>
                                                <c:otherwise>
                                                <!-- <input type="button" id="Actualizar" value="Actualizar" onclick="actualizar(${dept});" >     -->    
                                                    <input type="submit" name="action" value="Actualizar" >
                                                    <input type="button" value="Remover" onclick="remove(${dept.selfId});">
                                                    <input type="button" value="Cancelar" onclick="cancelar();">    
                                                </c:otherwise>
                                            </c:choose>
                                                    <input type="button" name="voltar" id="voltar" value="Voltar"> 
                                        </td>
                                        <td >
                                         <!-- <button type="button" id="post-btn">$.Post Submit</button> -->    
                                        </td>
                                        <td>
                                                
                                        </td>
                                    </tr>
                                </table>
                            </fieldset>
                        </td>
                    </tr>
                    <tr>
                        <td>&nbsp;
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <fieldset>
                                <legend>Lista de Departamentos</legend>
                                <table width="100%">
                                    <tr>
                                    <!--     <td width="15%"></td> -->
                                        <td width="85%">
                                            <table >
                                                <tr align="left">
                                                    <th width="5%" >EDITAR</th>    
                                                    <th width="45%">DESIGNA&Ccedil;&Atilde;O</th>
                                                    <th width="50%">DESCRI&Ccedil;&Atilde;O</th>
                                                </tr>
                                                <c:forEach items="${allDept}" var="departamento">
                                                    <tr>
                                                        <td height="20" valign="middle">
                                                            <a href="/sigra/dept/selecteddept?selfId=${departamento.selfId}" >
                                                                
                                                                
                                                               <img src="<c:url value="/imagens/edit_big.gif" />" width="22px" height="22px" title="Clica aqui para Detalhar!"/>
                                                         <!--  <img src="comuns/images/edit_big.gif" width="22px" height="22px" title="Clica aqui para Detalhar!" /> -->  
                                                            </a>
                                                        </td>
                                                        <td>${departamento.designacao}</td>
                                                        <td>${departamento.descricao}</td>    
                                                    </tr>
                                                </c:forEach>
                                            </table>
                                        </td>
                                    </tr>
                                    
                                </table>
                            </fieldset>
                        </td>
                    </tr>
                    <tr>
                        
                    </tr>
                </table>
            </fieldset>
            
        </form>
        <c:import url="/rodape.jsp" /> 
    </body>
</html>

 

Controller:

 


@Controller
@RequestMapping("/dept")
public class DepartamentoAction {
    
    ArrayList<DepartamentoVO> allDept = new ArrayList<DepartamentoVO>();
    
    
    @RequestMapping(method= RequestMethod.GET)
    public ModelAndView step0(){
        
        DepartamentoDAO deptDao = new DepartamentoDAO();
        allDept = deptDao.getAll();
        
        ModelAndView modelView = new ModelAndView("dept/dept-form","allDept", this.allDept);
        
        return modelView;
        
    }
    
    
    @RequestMapping(value="/save", method= {RequestMethod.POST})
    public String save(DepartamentoVO dept, UsuarioVO user, @RequestParam("action") String action, RedirectAttributes redirectAttributes) throws Exception{
        
        DepartamentoDAO dao = new DepartamentoDAO();
        
        if (action.equalsIgnoreCase("Salvar")) {
        
            dao.save(dept, user);
        }
    
        else{
            dao.update(dept, user);
            
        }
        
        redirectAttributes.addFlashAttribute("statusMsg", Mensagens.OPERATION_SUCCESS_MSG);
        return "redirect:";
    }
    

    @RequestMapping(value="/remove")
    public ModelAndView remove( DepartamentoVO dept , UsuarioVO user, RedirectAttributes redirectAttributes, HttpServletRequest request) throws Exception{
        
        DepartamentoVO deptAux = (DepartamentoVO) request.getSession().getAttribute("dept");
        
        DepartamentoDAO deptDao = new DepartamentoDAO();
        
        deptDao.deleteByID(dept.getSelfId(), user);
        
        redirectAttributes.addFlashAttribute("statusMsg", Mensagens.OPERATION_SUCCESS_MSG);    
            
        return new  ModelAndView("dept/dept-form","allDept", this.allDept);
    }
    
    
    @RequestMapping(value="/selecteddept",  method= {RequestMethod.POST, RequestMethod.GET})
    public ModelAndView loadpagamento(@RequestParam("selfId") long id, UsuarioVO user,Model model){
    
        DepartamentoVO dept = new DepartamentoVO();
        dept.setSelfId(id);
        
        
        for ( DepartamentoVO departamento : this.allDept) {
            if(departamento.getSelfId()== dept.getSelfId()){
                
                dept = departamento;
                model.addAttribute("dept", dept);
            }    
        }
        
        return new ModelAndView("dept/dept-form","allDept", this.allDept);
    }
    
    
    
    @RequestMapping(value="/cancelar",  method= {RequestMethod.GET})
    public ModelAndView cancelar(){
        
        System.out.println("Cancelando....!");
        
        ModelAndView modeView = new ModelAndView("dept/dept-form","allDept", this.allDept);
        
        modeView.addObject("dept", new DepartamentoVO());
        
        return modeView;
        
    }

}
 

Compartilhar este post


Link para o post
Compartilhar em outros sites

  • Conteúdo Similar

    • Por Rengavitp
      Bom dia pessoal!

      Estou com o seguinte problema, tenho uma aplicação que funciona perfeitamente rodando na minha IDE (Spring Tool Suite) mas ao gerar o arquivo war e subir a aplicação no tom cat ele não funciona, mas apenas erro 404, abri o war e todos os arquivo estão lá, já tem seguir tudo quando e tutorial com problemas semelhantes mas nenhum resolveu. Abaixo mais informações,.

      Versão do java na aplicacao 11
      Versão do jva no servidor 11
      Versão do tomcat no servidor 8.5.55
       
      minha classe principal
      package br.com.masterplastfitas; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; @SpringBootApplication public class MasterApplication extends SpringBootServletInitializer { public static void main(String[] args) { SpringApplication.run(MasterApplication.class, args); } @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) { return builder.sources(MasterApplication.class); } } meu pom.xml
      <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.7.2</version> <relativePath /> <!-- lookup parent from repository --> </parent> <groupId>masterplast</groupId> <artifactId>Master</artifactId> <version>2.0</version> <packaging>war</packaging> <name>Master</name> <description>Aplicação web </description> <properties> <java.version>11</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </dependency> <dependency> <groupId>com.microsoft.sqlserver</groupId> <artifactId>mssql-jdbc</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.thymeleaf.extras</groupId> <artifactId>thymeleaf-extras-springsecurity5</artifactId> </dependency> <dependency> <groupId>org.mindrot</groupId> <artifactId>jbcrypt</artifactId> <version>0.4</version> </dependency> <dependency> <groupId>com.itextpdf</groupId> <artifactId>itextpdf</artifactId> <version>5.5.0</version> </dependency> </dependencies> <build> <plugins> <!-- <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> --> </plugins> </build> </project>  
    • Por Ninja2112
      Ola pessoal....estou c o seguinte problema: Tenho uma página .jsp com uns botões
         e querendo preenche-los durante o carregamento. De acordo com o value, querendo
         colorir de uma forma diferente. Alguma idéia ? Estou tentando assim:
      value="<%=consultarStatusSemana(dist1[i],vetorsematual[j])%>" e como posso chamar uma função q de os estilos de acordo ??
    • Por RSN
      Boa noite,
      Gostaria de após selecionar o produto carregasse outro select informando os preços(tabela produto), com javascript fazendo requisição para a servlet.
      div class="form-group col-md-4"> <label for="exampleInputEmail1">Produto</label> <select class="form-control select2" style="width: 100%;" id="id_produto" name="id_produto"> <option value="nao_informado">Selecione</option> <c:forEach items="${produto}" var="product"> <option value="${product.id}" id="${product.id}" <c:if test="${product.id == orcament.id_produto}"> <c:out value = "selected=selected" /> </c:if>> ${product.descricao}</option> </c:forEach> </select> </div> <div class="form-group col-md-1"> <label for="exampleInputEmail1">Tabela/Precos</label> <select class="form-control select2" style="width: 100%;" id="id_table" name="id_table" > <option value="nao_informado">Selecione</option> </select> </div>  
    • Por Claudinei Teodoro
      Sou super novato estou começando a entender programação agora e estou com dificuldade em implementar o método UPDATE no meu DAO Generico.
      Os métodos INSERT, SELECT, DELETE já esta funcionando preciso somente de uma ajuda para o método UPDATE.

      Segue abaixo método INSERT que estou utilizando, alguém pode me ajudar com o método UPDATA utilizando como base este método INSERT.


      public void salvar(T objeto) throws SQLException, IllegalArgumentException, IllegalAccessException, ClassNotFoundException {


      Class classe = objeto.getClass();

      String parteInicialSQL = "INSERT INTO " + classe.getSimpleName().toLowerCase() + "(";

      Field[] atributos = classe.getDeclaredFields();
      String parteFinalSQL = ") VALUES(";

      for (Field atributo : atributos) {
      if (!"id".equals(atributo.getName())) {
      parteInicialSQL += atributo.getName().toLowerCase() + ",";
      parteFinalSQL += "?,";
      }
      }

      parteInicialSQL = parteInicialSQL.substring(0, parteInicialSQL.length() - 1);
      parteFinalSQL = parteFinalSQL.substring(0, parteFinalSQL.length() - 1) + ")";

      Class.forName("org.postgresql.Driver");
      Connection conexao = DriverManager.getConnection("jdbc:postgresql://127.0.0.1:5432/postgres", "postgres", "123456");
      PreparedStatement sql = conexao.prepareStatement(parteInicialSQL + parteFinalSQL);

      int numeroInterrogacao = 1;
      for (Field atributo : atributos) {
      if (!"id".equals(atributo.getName())) {
      atributo.setAccessible(true);
      sql.setObject(numeroInterrogacao++, atributo.get(objeto));
      }
      }

      System.out.println(parteInicialSQL + parteFinalSQL);

      sql.execute();
      conexao.close();

      }
    • Por Renato Muniz
      Boa noite pessoal, minha Entity tem um campo 
      @NumberFormat(pattern = "#,##0.00")     transient BigDecimal total; Esse campo é calculando la no meu repository com um JOIN.... o problema é que quando ponho ele não transitório eu não consigo exibir o valor dele na View
      tento como acima, como abaixo:
      @Transient     @Column(updatable = false, insertable = false)     @NumberFormat(pattern = "#,##0.00")     private BigDecimal valortemporario;  
       
      Meu desejo é utilizar esse campo calculado na View, mas sem persistir ele, quqndo mando salvar os dados enviando o objeto esse campo vai junto, utilizando o
      transient BigDecimal total ele retira da persistência mas não me deixa visualizar na view, to a um tempão procurando solução e não encontro, obrigado desde já!!
       
      Abaixo seque a query so pra efeito de visualizar o caso num todo!!
      public interface AtendimentosRepository extends JpaRepository<Atendimentos, Long> {     String sqlPrincipal = "SELECT id_heados, usuario_heados, cadastro_heados, "             + " sinistronumero_heados, pecastotal.valortemporario as total, "             + "corretor_heados, custosadicionais_heados, veiculo_heados, empresa_heados, seguradora_heados, "             + " datalanc_heados, dataprevsaida_heados, dataentrada_heados, deducao_heados,extramaoobra_heados ,"             + " extrapeca_heados, franquia_heados, maoobra_heados, materialpintura_heados,obschecklist_heados, "             + " veiculo_km_heados, obsextras_heados,tipoatendimento_heados, totalpecas_heados,  "             + " datasaida_heados FROM heados  "             + "    LEFT JOIN (    (SELECT pedos.controle_pedos,adicional_pedos,"             + "    sum( ( COALESCE(valor_pedos,'0') * COALESCE(quantidade_pedos,'0') ) - (  "             + "    ( COALESCE(valor_pedos,'0') * COALESCE(quantidade_pedos,'0') )    * COALESCE(desconto_pedos,'0') /100"             + "    ) ) as valortemporario FROM pedos as pedos  WHERE adicional_pedos  = 'N'"             + "    group by pedos.controle_pedos) ) pecastotal ON controle_pedos "             + " WHERE id_heados = :controle ";     @Query(value = sqlPrincipal, nativeQuery = true)     public Atendimentos atendimentoByControle(@Param("controle") Long controle); }
       
       
      Obrigado!!!
      Renato Muniz.
×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.