<< 액션클래스에서 세션 얻어오기 >>
1) SessionAware인터페이스를 상속받는다.
2) setSession메소드를 오버라이딩한다.(파라미터에 세션객체가 저장되어 온다)
1) login.jsp
2) main.jsp
3) LoginAction.java
4) LogoutAction.java
5) MembersDao.java
6) MembersVo.java
7) Mybatis 관련 orm파일들
7-1) SqlSessionFactoryService.java
7-2) MembersMapper.xml
7-3) mybatis-config.xml
8) example.xml ( Action 매핑 xml )
-------------------------------------------------------------------------
1) login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>Insert title here</title>
<style type="text/css">
span{
color:red;
font-size: 10pt;
}
</style>
</head>
<body>
<h2>로그인하기</h2>
<form method="post"action="login.action">
아이디 <input type="text" name="id"/><span>${fieldErrors.errId }</span><br/>
비밀번호 <input type="password" name="pwd"/><span>${fieldErrors.errPwd }</span><br/>
<span>${errMsg }</span><br/>
<input type="submit" value="로그인"/>
</form>
</body>
</html>
2) main.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!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=UTF-8">
<title>Insert title here</title>
</head>
<body>
<c:choose>
<c:when test="${empty sessionScope.id }">
<a href="loginForm.action">로그인하기</a><br/>
</c:when>
<c:otherwise>
<div>
${sessionScope.id }님 환영합니다.<br/>
<a href="logout.action">로그아웃</a>
</div>
</c:otherwise>
</c:choose>
<p>
여기는 main.jsp입니다.....
</p>
</body>
</html>
3) LoginAction.java
package test.action;
import java.util.HashMap;
import java.util.Map;
import org.apache.struts2.dispatcher.SessionMap;
import org.apache.struts2.interceptor.SessionAware;
import test.dao.MembersDao;
import test.vo.MembersVo;
import com.opensymphony.xwork2.ActionSupport;
public class LoginAction extends ActionSupportimplements SessionAware{
private String id;
private String pwd;
private String errMsg;//오류메시지를 담을 변수
//스트럿츠에서는 SessionMap으로 세션처리를 한다.
private SessionMap<String,Object> session;
public void setId(String id) {
this.id = id;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public String getErrMsg() {
return errMsg;
}
//파라미터 session에 세션객체가 자동으로 담겨져 있다.
@Override
public void setSession(Map<String, Object> session) {
//멤버변수 session에 옮겨 담기
this.session=(SessionMap<String,Object>)session;
}
//execute메소드가 호출되기 전에 미리 호출되며 유효성체크를 하는 기능
//에러가 하나라도 추가되면 리절트의 input으로 설정된 페이지로 자동이동된다.
@Override
public void validate() {
//사용자가 아이디를 입력하지 않은경우
if(id==null || id.length()==0){
//에러를 추가한다.
addFieldError("errId","아이디를 입력하세요!");
}
if(pwd==null || pwd.length()==0){
addFieldError("errPwd","비밀번호를 입력하세요!");
}
}
@Override
public String execute() throws Exception {
//싱글톤객체인 dao얻어오기
MembersDao dao=MembersDao.getInstance();
//검색조건인 아이디와 비밀번호를 담긴위한 Map객체
HashMap<String,String> map=new HashMap<>();
map.put("id",id);
map.put("pwd",pwd);
MembersVo vo=dao.isMember(map);
if(vo!=null){
//세션에 로그인정보(id) 담기
session.put("id",id);
return SUCCESS;
}else{
errMsg="아이디 또는 비밀번호가 맞지 않아요!";
return LOGIN;//로그인페이지로 이동
}
}
}
4) LogoutAction.java
package test.action;
import java.util.Map;
import org.apache.struts2.dispatcher.SessionMap;
import org.apache.struts2.interceptor.SessionAware;
import com.opensymphony.xwork2.ActionSupport;
public class LogoutAction extends ActionSupport implements SessionAware{
private SessionMap<String, Object> session;
@Override
public void setSession(Map<String, Object> session) {
this.session = ( SessionMap<String,Object>)session;
}
public String logout(){
//로그인 할때 담은 id제거
session.remove("id");
return SUCCESS;
}
}
5) MembersDao.java
package test.dao;
import java.util.HashMap;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import test.orm.SqlSessionFactoryService;
import test.vo.MembersVo;
//MembersDao dao=MembersDao.getInstance();
//싱글톤패턴의 DAO
public class MembersDao {
private static MembersDao instance=new MembersDao();
public static MembersDao getInstance() {
return instance;
}
private SqlSessionFactory sqlSessionFactory;
private MembersDao() {
sqlSessionFactory=SqlSessionFactoryService.getSqlSessionFactory();
}
public MembersVo isMember(HashMap<String,String> map){
SqlSession sqlSession=null;
try{
sqlSession=sqlSessionFactory.openSession();
return sqlSession.selectOne("ismember",map);
}finally{
if(sqlSession!=null) sqlSession.close();
}
}
}
6) MembersVo.java
package test.vo;
import java.sql.Timestamp;
public class MembersVo {
private String id;
private String pwd;
private String email;
private String phone;
private Timestamp regdate;
public MembersVo() {}
public MembersVo(String id, String pwd, String email, String phone,
Timestamp regdate) {
super();
this.id = id;
this.pwd = pwd;
this.email = email;
this.phone = phone;
this.regdate = regdate;
}
public Timestamp getRegdate() {
return regdate;
}
public void setRegdate(Timestamp regdate) {
this.regdate = regdate;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
@Override
public String toString() {
return "MembersVo [id=" + id + ", pwd=" + pwd + ", email=" + email
+ ", phone=" + phone + ", regdate=" + regdate + "]";
}
}
7) Mybatis 관련 orm파일들
7-1) SqlSessionFactoryService.java
package test.orm;
import java.io.IOException;
import java.io.InputStream;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class SqlSessionFactoryService {
private static SqlSessionFactory sqlSessionFactory;
//static멤버변수를 초기화할때는 static블록을 사용한다.(생성자x)
static{
try{
InputStream is=
Resources.getResourceAsStream("test/orm/mybatis-config.xml");
sqlSessionFactory=new SqlSessionFactoryBuilder().build(is);
}catch(IOException ie){
System.out.println(ie.getMessage());
}
}
public static SqlSessionFactory getSqlSessionFactory() {
return sqlSessionFactory;
}
}
7-2) MembersMapper.xml
<?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="test.orm.MembersMapper">
<select id="ismember" parameterType="hashmap"
resultType="test.vo.MembersVo">
select * from members
where id=#{id} and pwd=#{pwd}
</select>
</mapper>
7-3) mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!--//////// 접속할 DB서버에 대한 정보 설정 /////////////-->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="oracle.jdbc.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:@localhost:1521:xe" />
<property name="username" value="scott" />
<property name="password" value="tiger" />
</dataSource>
</environment>
</environments>
<!--/////// sql구문이 들어있는 SQL Mapper파일 포함 ////////// -->
<mappers>
<mapper resource="test/orm/MembersMapper.xml" />
</mappers>
</configuration>
8) example.xml ( Action 매핑 xml )
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="example" namespace="/" extends="default">
<!-- 로그인페이지로 이동하는 액션 -->
<action name="loginForm">
<result>/login/login.jsp</result>
</action>
<action name="login" class="test.action.LoginAction">
<result name="input">/login/login.jsp</result>
<result name="login">/login/login.jsp</result>
<result name="success">/main.jsp</result>
</action>
<!--
method를 지정하지 않으면 기본으로 설정된 execute메소드가
호출되고 다른 이름의 메소드를 호출하려면 호출할 메소드 이름을 적는다.
-->
<action name="logout" class="test.action.LogoutAction" method="logout">
<!-- 리다이렉트방식으로 페이지 이동하기 -->
<result name="success" type="redirect">/main.jsp</result>
</action>
</package>
</struts>
; action클래스에서 validate를 사용하면 유효성검증 후 다시 페이지로 메시지를 보내 화면에 뿌린다.
; 자바스크립트로 검증할수 없을 경우 위와 같이 검증이 가능하다.
'WEB > Struts2' 카테고리의 다른 글
Struts2 #03(Action클래스 : 여러 파라미터값을 vo객체에 한번에 담기(setter)) (0) | 2013.05.04 |
---|---|
Struts2 #02(Action클래스만들기: ActionSupport클래스를 상속받아 만들기) (0) | 2013.05.04 |
Struts2 #01( action클래스 만들기: Action인터페이스 상속받아 만들기 ) (0) | 2013.05.04 |
Struts2 #00 ( 시작하기 ) (0) | 2013.05.04 |