1. 程式人生 > >Struts2+Mybatis整合實現註冊登入功能

Struts2+Mybatis整合實現註冊登入功能

1.要實現框架之間的整合,第一

2.接下來先配置Struts2的核心控制器web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <display-name></display-name>	
  <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
  
  
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

核心控制器中的程式碼去官方文件中直接摘抄即可。

3.接下來,我們需要一個Po類,簡單的在其中定義id,使用者名稱和密碼即可

package com.guanglan.po;

public class User {
	private int id;
	private String uname;
	private String pwd;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getUname() {
		return uname;
	}
	public void setUname(String uname) {
		this.uname = uname;
	}
	public String getPwd() {
		return pwd;
	}
	public void setPwd(String pwd) {
		this.pwd = pwd;
	}
	
	
}


4.匯入Struts.xml配置檔案

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
	"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
	"http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>

    <constant name="struts.enable.DynamicMethodInvocation" value="true" />
    <constant name="struts.devMode" value="true" />
    <constant name="struts.i18n.encoding" value="UTF-8" />

</struts>

開啟動態方法,開發者模式,其餘使用註解

5.建立一個Action類,並引入User,實現其get,set方法

public class regAction {
	
	private User user;
	
	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

6.建立JSP檔案,並寫表單,從jsp檔案中傳入資料至action中。
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>Welcome Reg My WebSite</title>

  </head>
  
  <body>
  	<form action="guanglan!reg.action">
    	使用者名稱:<input type="text" name=user.uname><br/>
    	密碼:<input type="password" name=user.pwd><br/>
    	提交:<input type="submit" value="提交"/>
    </form>
  </body>
</html>


在action中定義一個reg方法來接收表單資料,同理定義login方法接收表單資料。

public String reg() throws IOException{
		
		
		return "ok";
	
	}
	
	public String login() throws Exception{
		
	}


7.下面我們來實現一下mybatis

先在src下匯入mybatis.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>
	<typeAliases>
		<typeAlias type="com.guanglan.po.User" alias="User"/>
	
	</typeAliases>

	<environments default="development">
		<environment id="development">
			<transactionManager type="JDBC" />
			<dataSource type="POOLED">
				<property name="driver" value="com.mysql.jdbc.Driver" />
				<property name="url" value="jdbc:mysql:///my_zh" />
				<property name="username" value="root" />
				<property name="password" value="123456" />
			</dataSource>
		</environment>
	</environments>
	<mappers>
		<mapper resource="com/guanglan/Mapper/TestMapper.xml"/>
	</mappers>
</configuration>

8.新建立一個查詢關係對映sql語句的包

然後建立一個mapper.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">
<!-- sql 對映檔案  -->
<mapper namespace="com.mybatis.Hello">
	<select id="selectAll" parameterType="map" resultType="User">
		select * from t_user where uname=#{un} and pwd=#{pwd}
	</select>
	
	<insert id="insertUser" parameterType="User">
		insert into t_user(uname,pwd) values(#{uname},#{pwd})
		
	</insert>
	
	
</mapper>

9.建立一個Service類
package com.guanglan.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import com.guanglan.po.User;
public class UserService {
	
	
	
		public static void add(String name,String password) throws IOException{
			SqlSessionFactory ssf= new SqlSessionFactoryBuilder().build(Resources.getResourceAsReader("mybatis.xml"));
			SqlSession sqlsession=ssf.openSession();
					User u = new User();
					u.setUname(name);
					u.setPwd(password);
					
					sqlsession.insert("com.mybatis.Hello.insertUser",u);
					
					sqlsession.commit();
		
		}
		
		public static User add1(String name,String password) throws Exception{
			SqlSessionFactory ssf= new SqlSessionFactoryBuilder().build(Resources.getResourceAsReader("mybatis.xml"));
			SqlSession session=ssf.openSession();
					
					Map<String,Object> map= new HashMap<String,Object>();
					
					map.put("un",name);
					map.put("pwd",password);
					
					User datas=session.selectOne("com.mybatis.Hello.selectAll",map);
					
							
					if(datas!=null){
							
								return datas;
							}
					else
							
								return null;
							
								
					
					
					
			
			
			
			
			
		}
		
		
}

10.在action中呼叫Service中的方法,傳入值到Service中,執行session.selectOne,以及session.insert方法來查詢和往資料庫中寫入資料。並且返回一個User物件在action的login方法中,如果物件不是空,證明在資料庫中查詢到了資料,登入成功。如果為空,那麼登入失敗。
package com.guanglan.reg.action;

import java.io.IOException;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;

import com.guanglan.Service.*;


import com.guanglan.po.User;
@Action("guanglan")	
@Results({
	@Result(name="ok",location="/reg-ok.jsp"),
	@Result(name="success",location="/login-ok.jsp"),
	@Result(name="error",location="/login-error.jsp")
	})
public class regAction {
	
	private User user;
	
	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public String reg() throws IOException{
		
		UserService.add(user.getUname(), user.getPwd());
		
		return "ok";
	
	}
	
	public String login() throws Exception{
		User uu =UserService.add1(user.getUname(), user.getPwd());
		if(uu==null){
			
			return "error";
		
		}else
			return "success";
	}
	
	
}

只是簡單的總結了一下,本人也是java小白。