首页 > 代码库 > 用标准Struts2+mvc写的用户管理

用标准Struts2+mvc写的用户管理

这星期的实验,终于调好了。一句话,麻雀虽小,五脏俱全。相信刚学struts2的同学可以通过该实验可以更好地理解struts的结构和mvc

登录的之前写过,这里直接进入用户管理

用struts2都要在src文件夹下建个struts.xml文件,文件名不能写错。这里直接贴上整个project定义到的action,了解下语法就可以了,以后具体用到再根据项目去改

<?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为配置文件根元素 -->
<struts>
	<!-- Action必须放在指定的包名空间中 -->
	<package name="user" extends="struts-default">
		<action name="queryAll" class="UserAction" method="queryAll">
			<result name="success">/index.jsp</result>
		</action>
		<action name="delete" class="UserAction" method="delete">
		    <result name="success" type="chain">queryAll</result> 
		</action>
		<action name="insert" class="UserAction" method="insert">
		    <result name="success" type="chain">queryAll</result>
		</action>
		<action name="edit" class="UserAction" method="edit">
		    <result name="success" type="chain">queryAll</result>
		</action>
		<action name="queryUserById" class="UserAction" method="queryUserById">
		    <result name="success">edit.jsp</result>
		</action>
	</package>
</struts>
WebRoot/WEB-INF下有个web.xml,得定义struts过滤器,直接看代码清楚些。这部分固定不变的,以后用到可以直接copy过去

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" 
	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_3_0.xsd">
  <display-name></display-name>	
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  <filter>
    <filter-name>struts2</filter-name>
    <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>struts2</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>
用户模型User.java,模型都是一些属性和getter、setter方法,不想每次手动写所有的getter、setter方法可以右击选中Generate Getter and Setters...设置生成相应的方法

public class User {

	public int id;
	public String username;
	public String password;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	
}
接下来一个DataBaseConn.java,用于获取数据库连接

import java.sql.*;

public class DataBaseConn {

	static Connection conn;
	public static Connection getConnection(){
		try {
			Class.forName("com.mysql.jdbc.Driver");
			conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "686175");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return conn;
	}
	public void close(){
		if(conn!=null){
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
QueryUpdate.java,业务逻辑层

import java.util.ArrayList;
import java.sql.*;

public class QueryUpdate {

	Connection conn;
	Statement stmt;
	ResultSet rs;
	String sql=null;
	
	public QueryUpdate(){
		conn=DataBaseConn.getConnection();
		try {
			stmt=conn.createStatement();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public ArrayList<User> queryAll(){
		ArrayList<User> users=new ArrayList<User>();
		try {
			sql="select * from user";
			rs=stmt.executeQuery(sql);
			while(rs.next()){
				User user=new User();
				user.setId(rs.getInt(1));
				user.setUsername(rs.getString(2));
				user.setPassword(rs.getString(3));
				users.add(user);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return users;
	}
	
	public User queryUserById(int id){
		User user=new User();
		sql="select * from user where id='"+id+"'";
		try {
			rs=stmt.executeQuery(sql);
			if(rs.next()){
				user.setId(rs.getInt(1));
				user.setUsername(rs.getString(2));
				user.setPassword(rs.getString(3));
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return user;
	}
	public void delete(int id){
		sql="delete from user where id='"+id+"'";
		try {
			stmt.executeUpdate(sql);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public void insert(String username,String password){
		try {
			int count=1;
			sql="select * from user";
			rs=stmt.executeQuery(sql);
			if(rs.next()){
				rs.last();
				count=rs.getInt(1)+1;
			}
			sql="insert into user values('"+count+"','"+username+"','"+password+"')";
			stmt.executeUpdate(sql);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	} 
	public void edit(int id,String username,String password){
		try {
			sql="update user set username='"+username+"', password='"+password+"' where id='"+id+"'";
			stmt.executeUpdate(sql);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
下面是一个Action类UserAction.java,struts都是用action处理的

import java.util.ArrayList;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class UserAction extends ActionSupport{
	
	int id;
	String username;
	String password;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public String queryAll(){
		QueryUpdate qu=new QueryUpdate();
		ArrayList<User> users=new ArrayList<User>();
		users=qu.queryAll();
		HttpServletRequest request=ServletActionContext.getRequest();
		request.setAttribute("all", users);
		return "success";
	}
	public String queryUserById(){
		QueryUpdate qu=new QueryUpdate();
		User user=new User();
		user=qu.queryUserById(this.getId());
		HttpServletRequest request=ServletActionContext.getRequest();
		request.setAttribute("user", user);
		return "success";
	}
	public String delete(){
		QueryUpdate qu=new QueryUpdate();
		qu.delete(this.getId());
		return "success";
	}
	public String insert(){
		QueryUpdate qu=new QueryUpdate();
		qu.insert(this.getUsername(), this.getPassword());
		return "success";
	}
	public String edit(){
		QueryUpdate qu=new QueryUpdate();
		qu.edit(this.getId(),this.getUsername(),this.getPassword());
		return "success";
	}
}
表现层

index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
  <head>
    <title>My JSP 'index.jsp' starting page</title>
  </head>
  
  <body>
    <table border="1">
       <tr>
          <td>编号</td>
          <td>账号</td>
          <td>密码</td>
          <td>编辑</td>
          <td>删除</td>
       </tr>
       <s:iterator value=http://www.mamicode.com/"#request.all" id="user">>
编辑更新信息edit.jsp。神了,用struts标签写的不知道为什么编译不过去,后来听同学的改用普通的jsp就可以了

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ page isELIgnored="false"%>
<html>
  <head>  
    <title>My JSP 'edit.jsp' starting page</title>
  <body>
    <form action="edit.action" method="post">          
                    编号<input type="text" name="id" value=http://www.mamicode.com/"${user.id}" readonly="readonly"/>
>

编号设为只读也可以用disabled="true",差别就是用disabled界面是灰色的看不太清id值;用readonly虽然看起来和username、password差不多,如果想删除id,程序会跳回index.jsp,da

添加新用户insert.java

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
  <head>
    <title>My JSP 'insert.jsp' starting page</title>
  </head>
  
  <body>
    <s:form action="insert" method="post">
      <s:textfield key="username" label="用户名"/>
      <s:password key="password" label="密码"/>
      <td><s:submit value=http://www.mamicode.com/"登录"/>>

在浏览器输入地址http://localhost:8080/struts2_mvc/queryAll.action便进入主页面


用标准Struts2+mvc写的用户管理