刚刚学完struts2框架,趁热打铁,做了个struts2MVC小项目练练手。主要用到了struts2的机制实现了登陆注册,
1.字符串到POJO类型的转换,
2.利用i18n拦截器实现了中英文国际化,
3.利用validate拦截器框架效验实现服务器端输入验证,
4.struts2标签库以及利用自定义拦截器实现权限控制(第四条下篇博客再进行介绍)
建完项目后,要引入jar包,我们用myeclipse自带的struts2jar包就ok,右键工程->MyEclipse->Project Faset->strutr2.x 完成之后就成功导入jar包
5.国际化实现之后,有三种方式实现中英文切换,前两种太过死板,第三种最灵活(推荐使用)
1>.直接在浏览器中修改浏览器语言
2>.在代码中设置locale属性。在struts.xml中加一个静态值(此方法虽然最简便,但不是长久之计)
代码:
若设置美国英文,将value值改为:en_US
3>.实现动态国际化,在页面中加入超连接的形式来实现,具体实现参见:点击打开链接
工程截图如下:
运行界面:
用mysql实现
一个用户表,三个字段,
varchar类型的userName,password
int类型的role用来设置权限(此篇博客暂时没用到)
数据库表截图如下:
<%@ taglib uri="/struts-tags" prefix="s" %>
代码如下:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s" %>
<%@ page import="com.user.bean.User" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
register.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
com.user.bean包下实体类:
package com.user.bean;
public class User {
private int role;
private String userName;
private String password;
/**
* @return the role
*/
public int getRole() {
return role;
}
/**
* @param role the role to set
*/
public void setRole(int role) {
this.role = role;
}
/**
* @return the userName
*/
public String getUserName() {
return userName;
}
/**
* @param userName the userName to set
*/
public void setUserName(String userName) {
this.userName = userName;
}
/**
* @return the password
*/
public String getPassword() {
return password;
}
/**
* @param password the password to set
*/
public void setPassword(String password) {
this.password = password;
}
}
com.user.action包下UserAction.java
package com.user.action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.user.bean.User;
import com.user.dao.UserDao;
import com.user.dao.UserDaoImpl;
public class UserAction extends ActionSupport{
private static final long serialVersionUID = 1L;
private User user;
private UserDao userDao = new UserDaoImpl();
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
//注册
public String regist(){
UserDaoImpl dao = new UserDaoImpl();
int i = dao.Register(user);
if(i!=-1){
return SUCCESS;
}else{
return ERROR;
}
}
//登陆验证
public String login(){
User checkUser = userDao.userLogin(user.getUserName(),user.getPassword(),user.getRole());
if(null == checkUser){
return ERROR;
}else{
ActionContext.getContext().put("tip", getText("success"));
ActionContext.getContext().put("username", user.getUserName());
return SUCCESS;
}
}
//重写validate方法,完成输入效验
/* (non-Javadoc)
* @see com.opensymphony.xwork2.ActionSupport#validate()
*/
@Override
public void validate() {
//如果用户名为空或为空字符串,则添加错误信息
if(user.getUserName() == null||user.getUserName().trim().equals("")){
//添加表单效验错误信息
addFieldError("username", "输入的用户名不能为空");
}
//如果密码为空或为空字符串,则添加错误信息
if(user.getPassword()==null ||user.getPassword().trim().equals("")){
addFieldError("password", "输入的密码不能为空");
}
}
}
com.user.dao包下
package com.user.dao;
import com.user.bean.User;
public interface UserDao {
//用户登陆
public User userLogin(String userName,String password,int role);
//用户注册
public int Register(User user);
}
UserDaoImpl.java
package com.user.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.user.bean.User;
import com.user.util.DBConnection;
public class UserDaoImpl implements UserDao {
@Override
public User userLogin(String userName,String password,int role) {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
User user = null;
//获得链接
conn = DBConnection.getConn();
//准备
String sql_userCheck="select userName,password,role from user where userName=? and password=? and role=?";
try {
pstmt = conn.prepareStatement(sql_userCheck);
pstmt.setString(1, userName);
pstmt.setString(2, password);
pstmt.setInt(3, role);
rs = pstmt.executeQuery();
if(rs.next()){
user = new User();
user.setUserName(rs.getString("userName"));
user.setPassword(rs.getString("password"));
user.setRole(rs.getInt("role"));
System.out.println(user.getUserName());
System.out.println(user.getPassword());
System.out.println(user.getRole());
}
} catch (SQLException e) {
System.out.println("登陆错误!");
e.printStackTrace();
} finally{
DBConnection.closeConn(conn);
DBConnection.closeStatement(pstmt);
DBConnection.closeResult(rs);
}
return user;
}
@Override
public int Register(User user) {
int i=-1;
Connection conn = null;
PreparedStatement pstmt = null;
try{
//获得链接
conn = DBConnection.getConn();
//准备
String sql_userCheck="INSERT INTO user (user.userName,user.password,user.flag) VALUES(?,?,?)";
pstmt = conn.prepareStatement(sql_userCheck);
pstmt.setString(1, user.getUserName());
pstmt.setString(2, user.getPassword());
pstmt.setInt(3, user.getRole());
i = pstmt.executeUpdate();
}catch(SQLException e){
System.out.println("注册错误");
e.printStackTrace();
}finally{
DBConnection.closeConn(conn);
DBConnection.closeStatement(pstmt);
}
return i;
}
}
com.user.util包下
package com.user.util;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
/**
* 数据库连接和关闭
* @author yl
*
*/
public final class DBConnection {
private static String DRIVER;
private static String URL;
private static String USER;
private static String PWD;
private static Properties pr = new Properties();
static{
try {
pr.load(DBConnection.class.getClassLoader().getResourceAsStream("db.properties"));
DRIVER = pr.getProperty("driver");
URL = pr.getProperty("url");
USER = pr.getProperty("user");
PWD = pr.getProperty("pass");
} catch (IOException e) {
System.out.println("加载资源文件错误");
e.printStackTrace();
}
}
//1.注册驱动
static{
try {
Class.forName(DRIVER);
} catch (ClassNotFoundException e) {
System.out.println("注册驱动失败!");
e.printStackTrace();
}
}
//2.获得连接
public static Connection getConn(){
Connection conn = null;
try {
conn = DriverManager.getConnection(URL, USER, PWD);
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println("数据库连接失败");
e.printStackTrace();
}
return conn;
}
//3.关闭连接
public static void closeConn(Connection conn){
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
System.out.println("关闭连接失败");
e.printStackTrace();
}
}
}
//4.关闭执行对象
public static void closeStatement(Statement stmt){
if(stmt!=null){
try {
stmt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//5.关闭结果集
public static void closeResult(ResultSet rs){
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
db.properties
driver=com.mysql.jdbc.Driver
url=jdbc\:mysql\://localhost\:3306/user_manager
user=root
pass=root
userName=User Name\uFF1A
password=Password\uFF1A
title_login=Login Page
submit=Submit
reset=Reset
regist=Regist
success=Congratulations {0}\uFF0CLogin success\uFF01
username=\u7528\u6237\u540D\uFF1A
password=\u5BC6\u7801\uFF1A
title_login=\u767B\u9646\u9875\u9762
submit=\u767B\u9646
reset=\u91CD\u7F6E
regist=\u6CE8\u518C
success=\u606D\u559C{0}\uFF0C\u767B\u9646\u6210\u529F\uFF01
/WEB-INF/Page/loginSuccess.jsp
/WEB-INF/Page/loginFailed.jsp
/Page/login.jsp
/Page/login.jsp
/Page/register.jsp
/Page/register.jsp