spring的入门项目

该项目的基本架构如下:

其中UserDAO.java中的代码是:

package com.chl.dao;

import java.sql.SQLException;
import java.util.List;

import com.chl.test.Emp;


public interface UserDAO {
public boolean insert(Emp u);
public boolean update(Emp u);
public boolean query(Emp u) throws SQLException;
public boolean delete(Emp u) throws SQLException;
}

UserDAOImp1.java:

package com.chl.dao.imp;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.sql.DataSource;
import org.springframework.stereotype.Component;

import com.chl.dao.UserDAO;
import com.chl.test.Emp;
import com.mysql.jdbc.ResultSet;
import com.mysql.jdbc.Statement;
import com.sun.org.apache.xpath.internal.operations.Bool;

@Component("userDAO1")
public class UserDAOImp1 implements UserDAO{
private static DataSource dataSource;

public DataSource getDataSource() {
return dataSource;
}

@Resource(name="dataSource")
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}

@Override
//重载用户添加
public boolean insert(Emp u) {
try{
Connection conn = dataSource.getConnection();
conn.createStatement().executeUpdate("insert into user2(name,password,phone)values('"+u.getName()+"','"+u.getPassword()+"','"+11+"')");
conn.close();
return true;
}catch (SQLException e){
e.printStackTrace();
return false;
}
}
//添加用户查询
public boolean query(Emp u) throws SQLException{
Connection conn = dataSource.getConnection();
String str1 = "select * from user2 where name = '"+u.getName()+"'";
java.sql.ResultSet result = conn.createStatement().executeQuery(str1);
while(result.next()){
if (result.getString("password").equals(u.getPassword()))
{
return true;
}
}
return false;
}
/*
public List<Emp> search(String str) throws SQLException{
Connection conn = dataSource.getConnection();
String str1 = "select * from user2 where name = '"+str+"'";
java.sql.ResultSet result = conn.createStatement().executeQuery(str1);
List<Emp > list=new ArrayList<Emp >();

while(result.next()){
Emp e = new Emp();
e.setName(result.getString("name"));
e.setPassword(result.getString("password"));
e.setPhone(result.getString("phone"));
list.add(e);
System.out.println(result.getString("name"));
}
return list;
}*/
@Override
//添加用户删除
public boolean delete(Emp e1) throws SQLException{

Connection conn = dataSource.getConnection();
try {
String sql = "delete from user2 where name = '"+e1.getName()+"'and password='"+e1.getPassword()+"'";// 删除数据的sql语句
int count = conn.createStatement().executeUpdate(sql);
if (count == 0)
return false;
System.out.println("user2表中删除 " + count + " 条数据\n"); //输出删除操作的处理结果

conn.close(); //关闭数据库连接
return true;
} catch (SQLException e) {
System.out.println("删除数据失败");
return false;
}

}
@Override
//添加用户更新
public boolean update(Emp u) {
try {
Connection conn = dataSource.getConnection();
String sql = "update user2 set password='"+u.getPassword()+"' where name = '"+u.getName()+"'";// 更新数据的sql语句

int count = conn.createStatement().executeUpdate(sql); //创建用于执行静态sql语句的Statement对象,st属局部变量

System.out.println("user2表中更新 " + count + " 条数据"); //输出更新操作的处理结果
if (count == 0)
return false;
conn.close(); //关闭数据库连接
return true;

} catch (SQLException e) {
System.out.println("更新数据失败");
return false;
}
}

}

UserService.java:

package com.chl.service;


import java.sql.SQLException;

import javax.annotation.Resource;
import com.chl.dao.UserDAO;
import com.chl.test.Emp;

public class UserService {
private UserDAO userDAO;

public void init(){
System.out.println("init");
}
public UserDAO getUserDAO() {
return userDAO;
}

@Resource(name="userDAO1")
public void setUserDAO(UserDAO userDAO) {
this.userDAO = userDAO;
}

public Boolean del(Emp u) throws SQLException{
return userDAO.delete(u);
}

public Boolean insert(Emp u) throws SQLException{
return userDAO.insert(u);
}

public Boolean update(Emp u) throws SQLException{
return userDAO.update(u);
}

public Boolean query(Emp u) throws SQLException, ClassNotFoundException{
Boolean e= userDAO.query(u);
return e;
}

public void destroy(){
System.out.println("destroy");
}
}

com.chl.test包中Emp.java:

package com.chl.test;

public class Emp {
private String name;
private String password;
private String phone;

public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}

public String toString(){
return "login name:"+name+" password:"+password;
}
}

startController.java:

package com.chl.test;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.chl.service.UserService;

@Controller
public class startController{
private static UserService service ;
@RequestMapping("/add")
public ModelAndView start(Emp emp,HttpServletRequest req, HttpServletResponse resp)
throws Exception {
BeanFactory applicationContext = new ClassPathXmlApplicationContext("test-servlet.xml");
service = (UserService)applicationContext.getBean("userService");
Boolean e = true;

e = service.query(emp);
Map<String, Boolean> model = new HashMap<String, Boolean>();
System.out.println(e);
model.put("list", e);
if (!e){
return new ModelAndView("login",model);
}
return new ModelAndView("add");
}

@RequestMapping("/login")
public ModelAndView end(){
Boolean e = true;
Map<String, Boolean> model = new HashMap<String, Boolean>();
model.put("list", e);
return new ModelAndView("login",model);
}

@RequestMapping("/Result")
public ModelAndView result(Emp emp,HttpServletRequest req, HttpServletResponse resp) throws SQLException, ClassNotFoundException{
ModelAndView model = new ModelAndView("add");
String str = req.getParameter("operation");
Boolean ee = false;
if (str.equals("delete")){
ee = service.del(emp);
model.addObject("ee",ee);
}
else if (str.equals("update")){
ee = service.update(emp);
model.addObject("ee", ee);
}
else if (str.equals("insert")){
ee = service.insert(emp);
model.addObject("ee", ee);
}
else{
ee = service.query(emp);
model.addObject("ee", ee);
}
model.addObject("str1",str);
System.out.println(str);
return model;
}
}

test-servlet.xml:

 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd ">

 

<context:annotation-config/>
<mvc:annotation-driven />
<context:component-scan base-package="com.chl" />

 

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/login"/>
<property name="username" value="root"/>
<property name="password" value="chl"/>
</bean>

 

<bean id="userService" class="com.chl.service.UserService" init-method="init" destroy-method="destroy">
</bean>
<!--
<bean id="useQuery1" class="com.chl.useQuery.useQuery">
<property name="url" value="jdbc:mysql://localhost:3306/login"/>
<property name="username" value="root"/>
<property name="password" value="chl"/>
<property name="drive" value="com.mysql.jdbc.Driver"/>
</bean>
-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>

add.jsp中的主要代码是:

 

<script language="JavaScript">
window.onload=checkname();
function checkname(){
var a=${ee};
var num1="${str1}";

 

if(a){
window.alert(num1+" 操作成功!");
}
else{
window.alert("无此记录");
}
}
</script>
<center>
<h2><font color=red>用户管理界面</font></h2>
<form name="tf" action="Result.test" method="post" >
用户名: <input name="name" type="text" class="box01"><br>
密 码: <input name="password" type=password class="box01"><br>
请选择您的操作:<select name="operation" id="operation" >
<option value="update">update</option>
<option value="insert">insert</option>
<option value="delete">delete</option>
<option value="query">query</option>
</select><br>
<input type="submit" value="Action"/>
</form>

login,jsp主要代码是:

 

<script language="JavaScript">
window.onload=checkname;
function checkNum(){
var num1=document.getElementById("name").value;
var num2=document.getElementById("password").value;
if(!num1||!num2){
window.alert("输入不能为空");
return false;
}

 

}
function checkname(){
if (!a){
window.alert("用户名或密码不匹配");
}
}
</script>

其中在html中取得后台中的数据可用:<script>var a=${list}</script>

上面这个例子主要是为了熟悉spring的基础流程,了解MVC的架构,以便后来能很快上手

posted @ 2012-11-30 09:59  SA高处不胜寒  阅读(731)  评论(0编辑  收藏  举报