FrontPage

目次

設計書作成

シーケンス図

Visual Studio Codeを開きます。 左側のメニューに拡張機能があるので PlantUMLと入力してください
検索すると一番上に出てくると思うのでクリックしてインストールします。 インストールが終えたら
左上のメニューにあるファイルから新規作成を選択してください。 Untitled-1が作成されるのでCTRL + SHIFT + S を押します。
任意のファイル名を入力し、ファイルの種類をPlantUMLに選択して保存します。 .wsdという形式のファイルができればOKです。 下記がUMLのサンプルになります。

   @startuml Update
   mainframe ユーザー編集
   actor User
   participant "ユーザー一覧画面" as View
   participant "編集モーダル" as Modal
   participant "エンコード" as encode
   participant "更新処理" as Update
   database "データベース" as DB
   alt 権限あり
   User -> View : 編集したい
   activate View
   else 権限なし
   User <-- View : エラー
   end
   View -> Modal : 一覧から選択する
   activate Modal
   Modal <-- DB : ユーザーID,変更前の名前,メールアドレス,パスワード
   activate DB
   Modal -> Update : 入力(名前,メールアドレス)
   activate Update
   Modal -> encode : 入力(パスワード)
   deactivate Modal
   activate encode
   encode -> Update : 暗号化したパスワード
   deactivate encode
   Update -> DB :更新
   deactivate Update
   View <-- DB : 更新したユーザー情報を反映
   deactivate DB
   deactivate View
   @enduml


ALT+Dを押すとプレビューに図が表示されます。
図を画像ファイルとして保存したい場合は ファイル内で右クリックすると ファイル内のダイアグラムをエクスポートとあるのでクリックします。
pngを選択するとのファイルを作成した場所にフォルダが作成されているのでフォルダ内に画像ファイルがあります。

環境構築

Eclipse

Eclipseのダウンロードサイトに移動します。
Eclipseの最新版をクリックします。JavaのFull Editionをクリックしてダウンロードを開始します。
WindowsではダウンロードしたZipファイルを7-Zipで展開してください。 ない場合はダウンロードしてください。
展開したファイルからpleiades/eclipse/eclipseのアプリケーションを起動して完了です。

MySQL

インストーラーをダウンロードします。
インストールしたファイルをダブルクリックしてインストールが開始されます。
Developer Defaultを選択してNext そのままNextを選択して確認画面が出るのでYesを選択します。 インストールをおこなうのでExecuteをクリックして、インストールが開始されます。
インストールが完了したら初期設定をするのでNextをクリック
デフォルトのままNext
Use Strong Password Encryption for Authentication を選択して、Nextをクリック
rootアカウントのパスワードを設定してNext
Configure MySQL Server as a Windows Service にチェックしてサービス名はデフォルトの MySQL80 でWindows の起動時に MySQL も起動するように Start the MySQL Server at System Startup にチェック
設定が終わりましたらNextをクリック Executeを選択してFinishで完了です。

フレームワーク

mybatis

   <?xml version="1.0" encoding="UTF-8"?>
       作成したxmlファイルにmybatisを使うための設定をします。
       <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
       Mapperを指定します。
       <mapper namespace="com.example.demo.mapper.UserMapper">
           検索結果をデータ型に変換するためクラスをresultTypeで指定する
           <select id="findUser" resultType="com.example.demo.entity.User">
               select user_id,user_name from m_user;
           </select>
       </mapper>

parameterTypeはinsert文でvalueの値やupdateでsetする値を指定するときに使う。

spring

Thymeleaf

HTML5などのテンプレートエンジン メリットとしては変数の部分を属性値で記述しているため、ブラウザで表示しても崩れないのが大きい
使い方はこちらを参考に

Spring Security

ログインページの作成

Spring Securityの依存性を注入するとアプリケーションを起動した際にSpring Securityのデフォルトのログイン画面が表示されるようになります。
まずは、自前で作成したログイン画面を表示させたいので 適当に作成したHTMLをcontrollerクラスのgetmappingで呼びます。
次に、javaconfigで設定を行います。 設定を行うためのwebsecurityconfigクラスを作成します。このクラスは、websecurityconfigureradapterを継承します。

   import org.springframework.context.annotation.Bean;
   import org.springframework.context.annotation.Configuration;
   import org.springframework.security.config.annotation.web.builders.HttpSecurity;
   import org.springframework.security.config.annotation.web.builders.WebSecurity;
   import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
   import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
   import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
   import org.springframework.security.crypto.password.PasswordEncoder;
   import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
   @Configuration
   @EnableWebSecurity
   public class WebSecurityConfig extends WebSecurityConfigurerAdapter{
   
   	@Override
   	public void configure(WebSecurity web) throws Exception {
   		// spring securityで無視するリクエストパスを設定 / **より下の階層は自由にアクセス可能
   		web.ignoring().antMatchers("/css/**", "/images/**", "/js/**");
   	}
   
   	@Override
       protected void configure(HttpSecurity http) throws Exception {
       
   		/*ログインページ
   		  ログインのアクション
   		  認証するときのパラメーター
   		  認証成功時の遷移先
   		  ログアウトのアクション
   		  ログアウト成功時のURL
   		  cookieの削除
   		  セッションを無効にする*/
   		 
           http.formLogin()
               .loginPage("/login/form")
               .loginProcessingUrl("/signin")
               .usernameParameter("mailaddress")
               .passwordParameter("password")
               .defaultSuccessUrl("/mypage")
               .and()
               .logout()
               .logoutRequestMatcher(new AntPathRequestMatcher("/signout"))
               .logoutSuccessUrl("/login/form")
               .deleteCookies("JSESSIONID")
               .invalidateHttpSession(true)
               .permitAll();
   
           //ログイン前に許可する処理
           http.authorizeRequests()
           	.antMatchers("/user/add").permitAll()
           	.antMatchers("/login/change/password").permitAll()
               .anyRequest().authenticated();
   
       }
   
   	@Bean
   	PasswordEncoder passwordEncoder() {
   		return new BCryptPasswordEncoder();
   	}
   }

ハッシュ化の方式はbcryptpasswordencoderを用いたいのでbcryptpasswordencoderをjavaconfigでbeanに追加します。 ここまで完了すると自作したログインページが表示されるようになります。

ハッシュ化

新規ユーザー作成画面からパスワードの入力フォームに入力された文字をcontrollerクラスで取得します。 serviceクラスにパスワードをハッシュ化するメソッドを作成します。

   import org.springframework.beans.factory.annotation.Autowired;
   import org.springframework.security.crypto.password.PasswordEncoder;
   
   @Autowired
   PasswordEncoder passwordEncoder;
   
   public void hashPassword(String password) {
       passwordEncoder.encode(password);
   }

controllerにserviceで作成したメソッド呼び出し取得した文字を引数に渡してハッシュ化させて登録します。
データベースに登録したユーザーのパスワードがハッシュ化されているか確認してください。

ユーザー認証

userテーブルからユーザーを取得するmapperを書きます。

   <?xml version="1.0" encoding="UTF-8"?>
   <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
   <mapper namespace="com.example.demo.mapper.UserMapper">
       <select id="findUser" resultType="com.example.demo.entity.User">
           select user_id,user_name,mailaddress,password,admin_flg,isdeleted from m_user where mailaddress = #{mailaddress};
       </select>
   </mapper>
   @Mapper
   public interface UserMapper {
       public Optional<User>findUser(String mailaddress);
   }

ユーザーを照合するクラスを書きます。

   import java.util.ArrayList;
   import java.util.Collection;
   import org.springframework.security.core.GrantedAuthority;
   import org.springframework.security.core.authority.SimpleGrantedAuthority;
   import org.springframework.security.core.userdetails.UserDetails;
   import lombok.Data;
   
   @Data
   public class LoginUserDetailsImpl implements UserDetails{
   
   	private User loginUser;
   
   	private Collection<GrantedAuthority>authorities;
   
   	public LoginUserDetailsImpl(User loginUser) {
   		this.loginUser = loginUser;
   
   		String role = null;
   
   		if(loginUser.getAdmin_flg() == 1) {
   			role = "ADMIN";
   		}else if(loginUser.getAdmin_flg() == 0) {
   			role = "USER";
   		}
   		this.authorities = new ArrayList<>();
   		this.authorities.add(new SimpleGrantedAuthority("ROLE_" + role));
   	}
   
   	@Override
   	public Collection<? extends GrantedAuthority> getAuthorities() {
   		return authorities;
   	}
   
   	@Override
   	public String getPassword() {
   		return loginUser.getPass();
   	}
   
   	@Override
   	public String getUsername() {
   		return loginUser.getUser_name();
   	}
   
   	@Override
   	public boolean isAccountNonExpired() {
   		return true;
   	}
   
   	@Override
   	public boolean isAccountNonLocked() {
   		return true;
   	}
   
   	@Override
   	public boolean isCredentialsNonExpired() {
   		return true;
   	}
   
   	@Override
   	public boolean isEnabled() {
   		if(loginUser.getIsdeleted() == 1) {
   			return false;
   		}
   		return true;
   	}
   }

ログイン画面から直接URL書き換えて遷移しないようにloginconfigクラスを作成します。

   import org.springframework.context.annotation.Configuration;
   import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
   import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
   
   @Configuration
   public class LoginConfig implements WebMvcConfigurer{
   	public void addViewContorllers(ViewControllerRegistry registry) {
   		registry.addViewController("/login/form").setViewName("/pages/login_form");
   	}
   }

トップ   新規 一覧 単語検索 最終更新   ヘルプ   最終更新のRSS