build.gradle

buildscript {
        ext {
                springBootVersion = '2.0.4.RELEASE'
                jjwtVersion = '0.9.0'
                findbugsVersion='3.0.1'
                bootstrapVersion = '3.3.7'
                jqueryVersion = '3.3.1'
                vueVersion ='2.5.13'
                fontawesomeVersion = '5.2.0'
                jspapiVersion = '2.3.3'
        }
        repositories {
                mavenCentral()
        }
        dependencies {
                classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
        }
}

/*
* 在這個段落中你可以聲明使用哪些外掛程式
* apply plugin: 'java' 代表這是一個Java專案,需要使用java外掛程式
* 如果想生成一個 `Intellij IDEA` 的工程,類似的如果要生成
* eclipse工程,就寫 apply plugin: 'eclipse'
* 同樣的我們要學的是Spring Boot,所以應用Spring Boot外掛程式
*/
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'

// 在這個段落中你可以聲明編譯後的Jar檔資訊
bootJar {
        baseName = 'myspring'
        group = 'com.polinwei'
        version = '0.0.1-SNAPSHOT'
}

// 在這個段落中你可以聲明原始檔案和目標編譯後的Java版本相容性
sourceCompatibility = 1.8
targetCompatibility = 1.8

// 在這個段落中你可以聲明在哪裡可以找到你的項目依賴
repositories {
        mavenCentral()
        maven { url "https://repo.spring.io/snapshot" }
        maven { url "https://repo.spring.io/milestone" }
        maven { url "https://code.lds.org/nexus/content/groups/main-repo"}
        maven { url "http://maven.aliyun.com/nexus/content/repositories/central"}
}


dependencies {  
        compile("org.springframework.boot:spring-boot-starter-data-jpa")
        compile("org.springframework.boot:spring-boot-starter-thymeleaf")
        compile("org.springframework.boot:spring-boot-starter-freemarker")
        compile("org.springframework.boot:spring-boot-starter-web")
        compile("org.springframework.boot:spring-boot-starter-security")
        compile("org.springframework.security:spring-security-taglibs")
        compile("org.springframework.boot:spring-boot-devtools") // Class 程式有更改時, 自動重啟
        compile("org.hibernate.validator:hibernate-validator") //驗證
        compile("javax.servlet.jsp:javax.servlet.jsp-api:${jspapiVersion}")
        compile("org.springframework.session:spring-session-data-redis")
        compile("org.springframework.boot:spring-boot-starter-data-redis")
        runtime("mysql:mysql-connector-java")
        compileOnly("org.projectlombok:lombok")
        compile("com.maxmind.geoip2:geoip2:2.12.0")
        compile("io.jsonwebtoken:jjwt:${jjwtVersion}")
        compile("com.google.code.findbugs:findbugs:${findbugsVersion}")
        compile("org.webjars:bootstrap:${bootstrapVersion}")
        compile("org.webjars:jquery:${jqueryVersion}")
        compile("org.webjars:vue:${vueVersion}")
        compile("org.webjars:font-awesome:${fontawesomeVersion}")
        compile("org.webjars.bowergithub.lipis:flag-icon-css:3.1.0")
        compileOnly("org.springframework.boot:spring-boot-configuration-processor")
        testCompile("org.springframework.boot:spring-boot-starter-test")
        testCompile("org.springframework.security:spring-security-test")
}

model: Authority.java

/**
 * Authority generated by hbm2java
 */
@Entity
@Table(name = "authority", uniqueConstraints = @UniqueConstraint(columnNames = "name"))
public class Authority implements java.io.Serializable {

        private Long id;
        private String name;
        @Size(min=2, max=30 , message = "{Size}")
        private String description;
        private Set users = new HashSet(0);

        public Authority() {
        }

        public Authority(String name, String description) {
                this.name = name;
                this.description = description;
        }

        public Authority(String name, String description, Set users) {
                this.name = name;
                this.description = description;
                this.users = users;
        }

        @Id
        @GeneratedValue(strategy = IDENTITY)

        @Column(name = "id", unique = true, nullable = false)
        public Long getId() {
                return this.id;
        }

        public void setId(Long id) {
                this.id = id;
        }

        @Column(name = "name", unique = true, nullable = false, length = 50)
        public String getName() {
                return this.name;
        }

        public void setName(String name) {
                this.name = name;
        }

        @Column(name = "description", nullable = false, length = 100)
        public String getDescription() {
                return this.description;
        }

        public void setDescription(String description) {
                this.description = description;
        }

        @ManyToMany(fetch = FetchType.LAZY)
        @JoinTable(name = "user_authority", joinColumns = {
                        @JoinColumn(name = "authority_id", nullable = false, updatable = false) }, inverseJoinColumns = {
                                        @JoinColumn(name = "user_id", nullable = false, updatable = false) })
        @JsonBackReference
        public Set getUsers() {
                return this.users;
        }

        public void setUsers(Set users) {
                this.users = users;
        }

}

Control: AuthorityController.java

@Controller
@RequestMapping(path = "/security")
public class AuthorityController {

        private final Logger logger = LoggerFactory.getLogger(this.getClass());
        
        @Autowired
        private AuthorityRepository authorityRepository;
        
        public void init(Model model) {
                model.addAttribute("programName", "Authority");
        }
        
        @RequestMapping("authority")
        public String crudAuthority(Model model) {
                init(model);
                model.addAttribute("authority", new Authority());
                model.addAttribute("authorityList",authorityRepository.findAll());              
                return "/security/authority";
        }
        
        /**
         * Get Authority Role from id
         * @param model
         * @param id
         * @return
         */
        @RequestMapping(value= {"authorityEdit","authorityEdit/{id}"} , method = RequestMethod.GET)
        public String crudAuthority(Model model, @PathVariable( required = false , name="id") Long id) {
                init(model);
                if (Objects.isNull(id)) {
                        model.addAttribute("authority", new Authority());
                } else {
                        model.addAttribute("authority", authorityRepository.findById(id).get());
                }               
                return "/security/authority";
        }
        
        /**
         * Save Authority Role
         * @param model
         * @param authority
         * @return
         */
        @RequestMapping(value="authorityEdit" , method = RequestMethod.POST)
        public String crudAuthority(Model model, @Valid Authority authority, BindingResult bindingResult) {
                init(model);
                if (bindingResult.hasErrors()) {
                        return "/security/authority";
                }
                        
                authorityRepository.save(authority);
                model.addAttribute("authority", new Authority());
                return "/security/authority";
        }
        
        /**
         * Delete Authority Role
         * @param model
         * @param id
         * @return
         */
        @RequestMapping(value="authorityDelete/{id}" , method = RequestMethod.GET)
        public String authorityDelete(Model model, @PathVariable( required = true, name = "id") Long id) {
                init(model);
                authorityRepository.deleteById(id);
                model.addAttribute("authority", new Authority());
                return "/security/authority";
        }
        
}

加入了@Valid注解 是為了實現JSR-303的驗證。

ftl: authority.ftl

文章標籤

MIS 發表在 痞客邦 留言(0) 人氣()

實現pdfmake使用中文本體主要就是編譯新的vfs_fonts.js代替原來vfs_fonts.js文檔引入到前端頁面中,為了編譯出新的字體文檔,下列是中文顯示的解決方法,供大家參考:

操作系統:Windows

操作步驟:

1. 安裝node.js

2. 下載pdfmake的源代碼、下載地址https://github.com/bpampuch/pdfmake

文章標籤

MIS 發表在 痞客邦 留言(0) 人氣()

使用 Hibernate Tool 去產生 Domain Code ( Model ) 時, 當 User.java & Authority.java 有相互參考時, 在 spring boot 使用 @RestController 會發生 Direct self-reference leading to cycle 的錯誤訊息, 解決的方法可以在 Domain Code ( Model ) 上加上 @JsonManagedReference & @JsonBackReference 來防止錯誤.

 

User.java

/**
 * User generated by hbm2java
 */
@Entity
@Table(name = "user")
public class User implements java.io.Serializable {

        private Long id;
        private User userByCreateUser;
        private User userByUpdateUser;
        private String username;
        private String password;
        private String firstname;
        private String lastname;
        private String email;
        private Boolean enabled;
        private Date lastpasswordresetdate;
        private Date activeDate;
        private Date inactiveDate;
        private Date createDate;
        private Date updateDate;
        private Set authorities = new HashSet(0);
        private Set usersForCreateUser = new HashSet(0);
        private Set usersForUpdateUser = new HashSet(0);

        public User() {
        }

        public User(String username, String password, String firstname, String lastname, String email,
                        Date lastpasswordresetdate) {
                this.username = username;
                this.password = password;
                this.firstname = firstname;
                this.lastname = lastname;
                this.email = email;
                this.lastpasswordresetdate = lastpasswordresetdate;
        }

        public User(User userByCreateUser, User userByUpdateUser, String username, String password, String firstname,
                        String lastname, String email, Boolean enabled, Date lastpasswordresetdate, Date activeDate,
                        Date inactiveDate, Date createDate, Date updateDate, Set authorities,
                        Set usersForCreateUser, Set usersForUpdateUser) {
                this.userByCreateUser = userByCreateUser;
                this.userByUpdateUser = userByUpdateUser;
                this.username = username;
                this.password = password;
                this.firstname = firstname;
                this.lastname = lastname;
                this.email = email;
                this.enabled = enabled;
                this.lastpasswordresetdate = lastpasswordresetdate;
                this.activeDate = activeDate;
                this.inactiveDate = inactiveDate;
                this.createDate = createDate;
                this.updateDate = updateDate;
                this.authorities = authorities;
                this.usersForCreateUser = usersForCreateUser;
                this.usersForUpdateUser = usersForUpdateUser;
        }

        @Id
        @GeneratedValue(strategy = IDENTITY)

        @Column(name = "id", unique = true, nullable = false)
        public Long getId() {
                return this.id;
        }

        public void setId(Long id) {
                this.id = id;
        }

        @ManyToOne(fetch = FetchType.LAZY)
        @JoinColumn(name = "create_user")
        public User getUserByCreateUser() {
                return this.userByCreateUser;
        }

        public void setUserByCreateUser(User userByCreateUser) {
                this.userByCreateUser = userByCreateUser;
        }

        @ManyToOne(fetch = FetchType.LAZY)
        @JoinColumn(name = "update_user")
        public User getUserByUpdateUser() {
                return this.userByUpdateUser;
        }

        public void setUserByUpdateUser(User userByUpdateUser) {
                this.userByUpdateUser = userByUpdateUser;
        }

        @Column(name = "username", nullable = false, length = 50)
        public String getUsername() {
                return this.username;
        }

        public void setUsername(String username) {
                this.username = username;
        }

        @Column(name = "password", nullable = false, length = 100)
        public String getPassword() {
                return this.password;
        }

        public void setPassword(String password) {
                this.password = password;
        }

        @Column(name = "firstname", nullable = false, length = 50)
        public String getFirstname() {
                return this.firstname;
        }

        public void setFirstname(String firstname) {
                this.firstname = firstname;
        }

        @Column(name = "lastname", nullable = false, length = 50)
        public String getLastname() {
                return this.lastname;
        }

        public void setLastname(String lastname) {
                this.lastname = lastname;
        }

        @Column(name = "email", nullable = false, length = 50)
        public String getEmail() {
                return this.email;
        }

        public void setEmail(String email) {
                this.email = email;
        }

        @Column(name = "enabled")
        public Boolean getEnabled() {
                return this.enabled;
        }

        public void setEnabled(Boolean enabled) {
                this.enabled = enabled;
        }

        @Temporal(TemporalType.TIMESTAMP)
        @Column(name = "lastpasswordresetdate", nullable = false, length = 19)
        public Date getLastpasswordresetdate() {
                return this.lastpasswordresetdate;
        }

        public void setLastpasswordresetdate(Date lastpasswordresetdate) {
                this.lastpasswordresetdate = lastpasswordresetdate;
        }

        @Temporal(TemporalType.TIMESTAMP)
        @Column(name = "active_date", length = 19)
        public Date getActiveDate() {
                return this.activeDate;
        }

        public void setActiveDate(Date activeDate) {
                this.activeDate = activeDate;
        }

        @Temporal(TemporalType.TIMESTAMP)
        @Column(name = "inactive_date", length = 19)
        public Date getInactiveDate() {
                return this.inactiveDate;
        }

        public void setInactiveDate(Date inactiveDate) {
                this.inactiveDate = inactiveDate;
        }

        @Temporal(TemporalType.TIMESTAMP)
        @Column(name = "create_date", length = 19)
        public Date getCreateDate() {
                return this.createDate;
        }

        public void setCreateDate(Date createDate) {
                this.createDate = createDate;
        }

        @Temporal(TemporalType.TIMESTAMP)
        @Column(name = "update_date", length = 19)
        public Date getUpdateDate() {
                return this.updateDate;
        }

        public void setUpdateDate(Date updateDate) {
                this.updateDate = updateDate;
        }

        @ManyToMany(fetch = FetchType.LAZY)
        @JoinTable(name = "user_authority", catalog = "my_spring", joinColumns = {
                        @JoinColumn(name = "user_id", nullable = false, updatable = false) }, inverseJoinColumns = {
                                        @JoinColumn(name = "authority_id", nullable = false, updatable = false) })
        @JsonManagedReference
        public Set getAuthorities() {
                return this.authorities;
        }

        public void setAuthorities(Set authorities) {
                this.authorities = authorities;
        }

        @OneToMany(fetch = FetchType.LAZY, mappedBy = "userByCreateUser")
        public Set getUsersForCreateUser() {
                return this.usersForCreateUser;
        }

        public void setUsersForCreateUser(Set usersForCreateUser) {
                this.usersForCreateUser = usersForCreateUser;
        }

        @OneToMany(fetch = FetchType.LAZY, mappedBy = "userByUpdateUser")
        public Set getUsersForUpdateUser() {
                return this.usersForUpdateUser;
        }

        public void setUsersForUpdateUser(Set usersForUpdateUser) {
                this.usersForUpdateUser = usersForUpdateUser;
        }

}

 

Authority.java

文章標籤

MIS 發表在 痞客邦 留言(0) 人氣()

SpringBoot+SpringSecurity+Freemarker專案中在頁面上使用security標籤控制按鈕顯示隱藏達到對按鈕級許可權控制還是比較方便的,如下配置即可。


1. gradle 引入依賴


dependencies {
        compile("org.springframework.security:spring-security-taglibs")
        compile("javax.servlet.jsp:javax.servlet.jsp-api:2.3.3")
}


2. 依賴引入後到spring-security-taglibs包中META-INF下security.tld複製出來,放到/resources/static下,最後建一個目錄tags,如下:

文章標籤

MIS 發表在 痞客邦 留言(0) 人氣()

除了 痞客邦 PIXNET 使用 Syntax Highlighter 顯示程式碼 以外, 也可以使用 highlight.js 來讓 pixnet 顯示程式碼

在後台管理的 側欄管理, 選擇 頁尾描述加入

<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/styles/default.min.css"/>
<script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/highlight.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/languages/go.min.js"></script>
<script>hljs.initHighlightingOnLoad();</script>


日後要展示程式碼的部分,先在撰寫貼上程式碼,轉到原始碼模式,用

<pre><code class="html">...</code></pre>

把程式碼包起來。

文章標籤

MIS 發表在 痞客邦 留言(0) 人氣()

Spring Boot + Freemarker 多語言國際化的作法

1. 在 application.properties 增加

# ===============================
# Multi Language
# ===============================
spring.messages.basename=i18n/messages

# 為了取得當前頁面的URL (get current page url)
spring.freemarker.expose-spring-macro-helpers=true

2. 在 resource 目錄下建立一個目錄 i18n , 並新增三個檔

messages.properties , messages_zh_TW.properties , 內容為

label.login =  登入

messages_en_US.properties 內容為

文章標籤

MIS 發表在 痞客邦 留言(0) 人氣()

使用 Hibernate Tool 產生 Model 時, FetchType 預設是 FetchType.LAZY , 但在執行時, 卻常會產生類似下列 no Session 的錯誤訊息

org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.spring.jwt.db.maria.model.authentication.User.userAuthorities, could not initialize proxy - no Session

 

這時候需要在 Method 前加入 @Transactional 就可以解決

@Test
@Transactional
public void testUserAuthority() {
        User user = userRepository.findById(1L).get();
        JwtUser jwtUser = JwtUserFactory.create(user);
        logger.info(jwtUser.getUsername());
        
}

Ref: http://javasampleapproach.com/hibernate/use-hibernate-lazy-fetch-eager-fetch-type-spring-boot-mysql

MIS 發表在 痞客邦 留言(0) 人氣()

使用 Spring Boot 2 建置系統就是希望快速. 若專案範圍小的話, 資料庫倒是可以考慮使用 H2 database 來建罝

在 build.gradle 上加入

compile('com.h2database:h2')

然後編輯 application.properties

server.port=8088
# ===============================
# H2
# ===============================
spring.h2.console.enabled=true
spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
這樣就可以登入 http://localhost:8088/h2-console 操作了
文章標籤

MIS 發表在 痞客邦 留言(0) 人氣()

 環境: ApacheFriends XAMPP Version 7.1.7

  + Apache 2.4.26
  + MariaDB 10.1.25
  + PHP 7.1.7 (VC14 X86 32bit thread safe) + PEAR
  + phpMyAdmin 4.7.0
文章標籤

MIS 發表在 痞客邦 留言(0) 人氣()

在 Tomcat 的 server.xml 裡設定

<Context docBase="weixin" path="/weixin" reloadable="true" source="org.eclipse.jst.jee.server:weixin">
        <Resource name="jdbc/mysqlLocalDS01" username="root" password="password" url="jdbc:mysql://localhost:3306?characterEncoding=utf-8" auth="Container" driverClassName="com.mysql.cj.jdbc.Driver" factory="org.apache.tomcat.dbcp.dbcp2.BasicDataSourceFactory" maxIdle="10" maxTotal="20" maxWaitMillis="-1" type="javax.sql.DataSource" />      
        <Resource name="jdbc/JappsDS01" username="ap" password="password" url="jdbc:oracle:thin:@127.0.0.1:1521:xe" driverClassName="oracle.jdbc.driver.OracleDriver" maxIdle="2" maxTotal="4" maxWaitMillis="5000"  type="javax.sql.DataSource" validationQuery="select 1 from dual"/>
    <Resources>
文章標籤

MIS 發表在 痞客邦 留言(0) 人氣()