Core
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Sesión 9 --------------------------------------------------------------------------------------------------- Internacionalizacion = i18n Localization = l10n Se usan las definiciones de i18n: es_ES en_UK en_US archivo: mensajes.properties = por defecto mensajes_es_ES.properties español de España mensajes_en_US.properties ingles estado unidos #comentario clave=valor rrhh.login.titulo=Página de login rrhh.login.username=Usuario: --------------------------------------messages.properties--------------------------------------------- #Claves de validacion user.name.invalid = El nombre no es valido. debete tener entre {2} y {1} caracteres. user.email.invalid = Direccion email invalida, escribe una direccion correcta. #Claves i18n para pagina de login login.title=Pagina de login login.username=Usuario: login.password=Password: Nombre: messages_es_ES.properties messages_en_US.properties ------------------------------------------------------------------------------------------------------- #Claves de validacion user.name.invalid = Name is not valid, must be between {2} and {1} characters. user.email.invalid = Email address is not valid, write a correct address. #Claves i18n para pagina de login login.title=Login Page login.username=Username: login.password=Password: ----------------------------------------------login.jsp--------------------------------------- Libreria de etiquetas de Spring = spring <%@taglib prefix="spring" uri="http://www.springframework.org/tags" %> <spring:message code="login.title" /> <spring:message code="login.username" /> <spring:message code="login.password" /> -Usando la libreria de etiquetas de Spring Si da un error es un fallo de configuracion o la clave mal escrita... -Usando la libreria de etiquetas de Java que se llama JSTL <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%> <fmt:message key="login.username" /> Si aparecen estos simbolos (???loggin.username???) es un fallo de configuracion o la clave mal escrita... ------------------------------------Version JSTL/Spring login.jsp------------------------------------- <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" isELIgnored="false" %> <%@taglib prefix="spring" uri="http://www.springframework.org/tags" %> <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%> <!DOCTYPE html> <html> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <body onload='document.loginForm.username.focus();'> <h1><spring:message code="login.title" /></h1> <!-- http://localhost:8080/AplicacionSpring5MVCHibernate/login --> <form name='login' action="login" method='POST'> <table> <tr> <td><fmt:message key="login.username" /></td> <td><input type='text' name='username' value=''></td> </tr> <tr> <td><spring:message code="login.password" /></td> <td><input type='password' name='password' /></td> </tr> <tr> <td colspan='2'><input name="submit" type="submit" value="Login" /></td> </tr> </table> <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" /> </form> <c:if test="${not empty errorMessge}"><div style="color:red; font-weight: bold; margin: 30px 0px;">${errorMessge}</div></c:if> </body> </html> ----------------------------------------Tablas corruptas en MySQL----------------------------------- Intentar repararlas con este comando: mysqlcheck -u root -p --repair --all-databases ---------------------------------------WebMvcConfig---------------------------------------- package com.pruebas.spring.config; import java.util.Locale; import org.springframework.context.MessageSource; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.support.ResourceBundleMessageSource; import org.springframework.validation.Validator; import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.view.InternalResourceViewResolver; import org.springframework.web.servlet.view.JstlView; //i18n recargable import org.springframework.context.support.ReloadableResourceBundleMessageSource; @Configuration @EnableWebMvc @ComponentScan(basePackages = {"com.pruebas.spring"}) public class WebMvcConfig implements WebMvcConfigurer { @Bean public InternalResourceViewResolver resolver() { InternalResourceViewResolver resolver = new InternalResourceViewResolver(); //Definimos JSTL como libreria de tags resolver.setViewClass(JstlView.class); //Podemos agregar mas prefijos y sufijos resolver.setPrefix("/WEB-INF/views/"); resolver.setSuffix(".jsp"); return resolver; } /* <!-- Esta delaracion XML equivale a la hecha en el metodo anterior(resolver) Configuracion del ViewResolver de Spring MVC --> <bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> <property name="prefix" value="/WEB-INF/jsp/" /> <property name="suffix" value=".jsp" /> </bean> */ /* @Bean //Definimos el bean de i18n = messages.properties public MessageSource messageSource() { ResourceBundleMessageSource source = new ResourceBundleMessageSource(); source.setBasename("messages"); return source; }*/ @Bean //El bean dedicado a la gestion de la i18n del modulo WebMVC //Por defecto trabaja con archivos *.properties en el classpath //Aqui se define el nombre de los archivos de i18n: messages_xx.properties //Las 'xx' del archivo representan el Local: es_ES: messages_es_ES.properties //Podemos usar packages para situar este archivo: "com/pruebas/i18n/messages" //Podemos usar packages para situar este archivo: "messages" public MessageSource messageSource() { //ResourceBundleMessageSource source = new ResourceBundleMessageSource(); //source.setBasename("com/pruebas/spring/i18n/messages"); //Usamos esta otra clase para recargar en ejecucion los mensajes i18n ReloadableResourceBundleMessageSource source = new ReloadableResourceBundleMessageSource(); //source.setBasename("classpath:com/pruebas/spring/i18n/messages"); source.setBasename("classpath:messages"); source.setDefaultEncoding("ISO-8859-1");//tabla de caracteres ISO Latin-1 return source; } @Override //Definine la posibilidad de usar Validadores public Validator getValidator() { LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean(); validator.setValidationMessageSource(messageSource()); return validator; } } ----------------------------------------Seguridad con Java--------------------------------------------------- Clase de autenticacion en Java: java.security.Principal Cuando esta obtiene una referencia = decimos que el usuario ha superado OK un proceso de autenticacion Esta clse obtiene los roles/grupos del usuario autenticado. ------------------------------------------LogFilter---------------------------------------------------------- URL pattern o Mapping: /* ------------------------------------------------------------------------------------------------------------- package com.pruebas.spring.utils; import java.io.IOException; import java.security.Principal; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.annotation.WebFilter; import javax.servlet.http.*; import org.springframework.http.HttpRequest; @WebFilter("/*") public class LogFilter extends HttpFilter implements Filter { private FilterConfig fConfig; public LogFilter() { System.out.println("-----Construyendo LogFilter"); } public void destroy() { System.out.println("Metodo destroy en LogFilter"); } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { //Obtenemos una header request de tipo HTTP HttpServletRequest peticion = (HttpServletRequest) request; String ip = peticion.getRemoteAddr(); String browser = peticion.getHeader("user-Agent"); Principal user = peticion.getUserPrincipal(); if(user != null) { System.out.println("====== Usuario: " + user.getName() + " autenticado"); if(peticion.isUserInRole("ADMIN")) { System.out.println("==== Usuario con role 'ADMIN'"); }else { System.out.println("==== Usuario sin role definido"); } } fConfig.getServletContext().log("=====Peticion con ip: " + ip + ", Navegador: " + browser); //Pasa la peticion al siguiente elemento de la cadena = Filtro o el recurso solicitado //Si el navegador se queda en blanco es posible que hayamos olvidado escribirla chain.doFilter(request, response); } public void init(FilterConfig fConfig) throws ServletException { this.fConfig = fConfig; } } -------------------------------------------AplicacionListener---------------------------------------------- package com.pruebas.spring.utils; import java.sql.Driver; import java.sql.DriverManager; import java.sql.SQLException; import java.util.Enumeration; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.annotation.WebListener; import com.mysql.cj.jdbc.AbandonedConnectionCleanupThread; @WebListener public class AplicacionListener implements ServletContextListener { public AplicacionListener() { } public void contextDestroyed(ServletContextEvent sce) { System.out.println("----Aplicacion parada"); //Para evitar la clausula INFO con la advertencia: //java.lang.IllegalStateException: Acceso ilegal: //esta instancia de aplicación web ya ha sido parada. Could not load []. //Elimino el registro del driver JDBC de MySQL //Obtenemos un listado de todos los drivers JDBC registrados Enumeration<Driver> drivers = DriverManager.getDrivers(); Driver d = null; while (drivers.hasMoreElements()) { try { //Nos situamos en el driver d = drivers.nextElement(); //Eliminamos el registro del driver DriverManager.deregisterDriver(d); System.out.println("Eliminando registro del driver: " + d); } catch (SQLException ex) { System.out.println("Error eliminando registro driver: " + d); } } try { //Para cada driver de RDBMS usamos la clase para limpiar las conexiones abandonadas //Esta clase corresponde al driver de MySQL AbandonedConnectionCleanupThread.checkedShutdown(); } catch (Exception e) { System.out.println("SEVERE Error listener: " + e.getMessage()); e.printStackTrace(); } } public void contextInitialized(ServletContextEvent sce) { System.out.println("----Aplicacion iniciada"); } } -----------------------------------------------------SpringBoot--------------------------------------- [ start.spring.io](https://start.spring.io/) ------------------------------------------------------Proyecto SpringBoot------------------------------ https://gofile.io/d/ZW72HB @Override public String toString() { return "Empleado [idempleado=" + idempleado + ", nombre=" + nombre + "]"; } ---------------------------------------------ProyectoSpringBoot con MVC y JPA-------------------------- https://gofile.io/d/JBDbAd ls -la rm -rf .dbeaver/ Eclipse MarketPlace DBeaver version (no instalar las otras apariciones) ----------------------------------------------Spring Batch---------------------------------------------- https://gofile.io/d/cVbWkf ----------------------------------------Documentacion adicional del curso---------------------------------- https://gofile.io/d/iYDzc1 El mismo contenidodesde Mega: https://mega.nz/file/kN80XRrb#1SXHtj4gbUrYfhmpM20n-pVFOlxwqkZCQAEbgMGvYfc cmota@corenetworks.es - Carlos Mota <version>8.0.33</version> ------------------------------------------------------------------------------------------------------------ #Puerto donde se iniciara Tomcat server.port=8080 spring.datasource.url=jdbc:mysql://localhost:3306/movielens?serverTimezone=UTC spring.datasource.username=root spring.datasource.password=password spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect spring.jpa.hibernate.ddl-auto = update #Disable Batch auto-start spring.batch.job.enabled=false #Database spring.batch.initialize-schema=always spring.jpa.show-sql = true

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully