20151210--MVC

package com.hanqi;

import java.io.IOException;
import java.sql.*;
import java.text.SimpleDateFormat;

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

import org.omg.PortableInterceptor.RequestInfoOperations;

import com.hanqi.*;
import com.hanqi.dao.User;
import com.hanqi.dao.UserDal;

import java.util.*;
import java.util.Date;
/**
 * Servlet implementation class SaveUser
 */
public class SaveUser extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private User user;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public SaveUser() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //转码,固定写法
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");    

        Date dt = new Date();//获取当前时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//格式化时间
        String sj = sdf.format(dt);//将时间转换为字符串格式

        //获取内容
        String userID = request.getParameter("userid");
        String userName = request.getParameter("username");
        String pw = request.getParameter("password");
        //判断输入的内容
        if(userID == null || userID.trim().length() == 0)
        {
            //输出内容
            response.getWriter().append("用户代码不能为空");
        }
        else if(userName == null || userName.trim().length() == 0)
        {
            response.getWriter().append("用户姓名不能为空");
        }
        else
        {

            User user = new User();

            user.setUserid(userID);
            user.setUsername(userName);
            user.setPassword(pw);
            user.setuserTime(sj);

            //调用模型层

            UserDal ud = new UserDal();

            try {

                ud.insert(user);

                response.sendRedirect("FindUserList");

            } catch (Exception e) {

                response.getWriter().append("保存数据失败");

                e.printStackTrace();
            }
            }
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}

增加

package com.hanqi;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.hanqi.common.DBHelper;

import java.sql.*;
import java.util.Date;
import com.hanqi.dao.*;

/**
 * Servlet implementation class DeleteUser
 */
public class DeleteUser extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public DeleteUser() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //转码
                request.setCharacterEncoding("UTF-8");
                response.setContentType("text/html;charset=UTF-8");
                response.setCharacterEncoding("UTF-8");    

                String userid = request.getParameter("userid");
                if(userid != null && userid.trim().length() > 0)
                {
                    UserDal ud = new UserDal();

                    try {

                        ud.delete(userid);

                        response.sendRedirect("FindUserList");

                    } catch (Exception e) {

                        response.getWriter().append("删除数据失败");

                        e.printStackTrace();
                    }
                }
}

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}

删除

package com.hanqi;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

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

import com.hanqi.common.DBHelper;
import com.hanqi.dao.User;
import com.hanqi.dao.UserDal;

/**
 * Servlet implementation class EditUser
 */
public class EditUser extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public EditUser() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");    

        //接受相关参数
        String userID = request.getParameter("userid");
        String userName = request.getParameter("username");
        String pw = request.getParameter("password");
        //判断输入的内容
                if(userID == null || userID.trim().length() == 0)
                {
                    //输出内容
                    response.getWriter().append("用户代码不能为空");
                }
                else if(userName == null || userName.trim().length() == 0)
                {
                    response.getWriter().append("用户姓名不能为空");
                }
                else
                {
                    User user = new User();

                    user.setUserid(userID);
                    user.setUsername(userName);
                    user.setPassword(pw);

                    UserDal ud = new UserDal();

                    try
                    {

                        ud.update(user);

                        response.sendRedirect("FindUserList");

                    }
                    catch(Exception e)
                    {

                        response.getWriter().append("修改数据失败");

                        e.printStackTrace();
                    }
                    }

    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}

修改

        package com.hanqi;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.*;

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

import com.hanqi.dao.User;
import com.hanqi.dao.UserDal;

/**
 * Servlet implementation class FindUserList
 */
public class FindUserList extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public FindUserList() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
                        UserDal ud = new UserDal();
                        try
                        {
                        ArrayList<User> al = ud.getListAll();
                        request.setAttribute("userlist", al);
                        }
                        catch(Exception e)
                        {
                            response.getWriter().append("查找数据失败");
                            e.printStackTrace();
                        }

        //页面跳转
        request.getRequestDispatcher("ShowUserList.jsp").forward(request,response);

    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}

查找

package com.hanqi.dao;

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

import com.hanqi.common.*;

//关于User表的数据库操作类
public class UserDal
{

    //增
    public int insert(User user) throws Exception
    {
        int rtn = -1;

        Connection conn = DBHelper.getConnection();

        PreparedStatement pst = null;

        if (conn != null)
        {
            try{
            String sql = "insert into T_User (user_id, user_name, password,user_time) values (?,?,?,?) ";

            pst = conn.prepareStatement(sql);

            pst.setString(1, user.getUserid());
            pst.setString(2, user.getUsername());
            pst.setString(3, user.getPassword());
            pst.setString(4, user.getuserTime());
            rtn = pst.executeUpdate();
        }
            catch(Exception ex)
            {
                throw ex;
            }
            finally
            {
            try
            {
                pst.close();
            }
            catch(Exception e)
            {
                conn.close();
            }
            }
        }

        return rtn;
    }

    //删

    public int delete(String user_id) throws Exception
    {
        int rtn = -1;

        Connection conn = DBHelper.getConnection();

        PreparedStatement pst = null;

        if (conn != null)
        {
            try{
            String sql = "delete T_User where user_id = ?";

            pst = conn.prepareStatement(sql);

            pst.setString(1, user_id);

            rtn = pst.executeUpdate();
            }
            catch(Exception ex)
            {
                throw ex;
            }
            finally
            {
            try
            {
                pst.close();
            }
            catch(Exception e)
            {
                conn.close();
            }
            }
        }

        return rtn;
    }

    //改
    public int update(User user) throws Exception
    {
    int rtn = -1;

    Connection conn = DBHelper.getConnection();

    PreparedStatement pst = null;

    if (conn != null)
    {
        try
        {
        String sql = "update T_User set user_name = ?,password = ? "
                + "where user_id = ? ";

        pst = conn.prepareStatement(sql);

        pst.setString(3, user.getUserid());
        pst.setString(1, user.getUsername());
        pst.setString(2, user.getPassword());

        rtn = pst.executeUpdate();
    }
        catch(Exception ex)
        {
            throw ex;
        }
        finally
        {
        try
        {
            pst.close();
        }
        catch(Exception e)
        {
            conn.close();
        }
        }
    }

    return rtn;
}

    //查
    public ArrayList<User> getListAll() throws Exception
    {
        ArrayList<User> rtn = new ArrayList<User>();

        Connection conn = DBHelper.getConnection();

        PreparedStatement pst = null;

        if (conn != null)
        {
            try
            {

            String sql = "select * from t_user";

            pst = conn.prepareStatement(sql);

            ResultSet rs = pst.executeQuery();
            if(rs != null)
            {
                while(rs.next())
                {
                    User u = new User();

                    u.setUserid(rs.getString("user_id"));
                    u.setUsername(rs.getString("user_name"));
                    u.setPassword(rs.getString("password"));
                    u.setuserTime(rs.getString("user_time"));
                    rtn.add(u);        //取一个数就放一个数
                }
            }
            }
            catch(Exception ex)
            {
                throw ex;
            }
            finally
            {
            try
            {
                pst.close();
            }
            catch(Exception e)
            {
                conn.close();
            }
            }
        }
        return rtn;
    }
}

M

时间: 2024-10-06 20:47:37

20151210--MVC的相关文章

爱上MVC~业务层刻意抛出异常,全局异常的捕获它并按格式返回

对于业务层的程序的致命错误,我们一直的做法就是直接抛出指定的异常,让程序去终断,这种做法是对的,因为如果一个业务出现了致命的阻塞的问题,就没有必要再向上一层一层的返回了,但这时有个问题,直接抛异常,意味着服务器直接500了,前端如何去显示,或者如果你是API的服务,如果为前端返回,如果是500,那直接就挂了,哈哈! 下面是在MVC环境下优化的全局异常捕获代码(非API) /// <summary> /// 全局异常捕获 /// </summary> public class Glo

ASP.NET MVC 使用Remote特性实现远程属性验证

RemoteAttribute是asp.net mvc 的一个验证特性,它位于System.Web.Mvc命名空间 下面通过例子来说明 很多系统中都有会员这个功能,会员在前台注册时,用户名不能与现有的用户名重复,还要求输入手机号码去注册,同时手机号码也需要验证是否重复,下面是实体类 /// <summary> /// 会员 /// </summary> public class Member { public int Id { get; set; } [Required(Error

Asp.Net MVC及Web API框架配置会碰到的几个问题及解决方案 (精髓)

前言 刚开始创建MVC与Web API的混合项目时,碰到好多问题,今天拿出来跟大家一起分享下.有朋友私信我问项目的分层及文件夹结构在我的第一篇博客中没说清楚,那么接下来我就准备从这些文件怎么分文件夹说起.问题大概有以下几点: 1.项目层的文件夹结构 2.解决MVC的Controller和Web API的Controller类名不能相同的问题 3.给MVC不同命名空间的Area的注册不同的路由 4.让Web API路由配置也支持命名空间参数 5.MVC及Web API添加身份验证及错误处理的过滤器

Swagger+ springfox +Spring mvc

简介 Swagger 是一个规范和完整的框架,用于生成.描述.调用和可视化 RESTful 风格的 Web 服务.总体目标是使客户端和文件系统作为服务器以同样的速度来更新.文件的方法,参数和模型紧密集成到服务器端的代码,允许API来始终保持同步.Swagger 让部署管理和使用功能强大的API从未如此简单.这一次我将从零开始搭建一个工程来演示如何在Spring mvc中整合Swagger生成Restful接口文档. 新建工程 我们新建一个Maven工程,并添加Web Facet,工程结构如下图所

MVC下微信企业号网页应用开发调用JSSDK接口不成功问题

在MVC下进行企业微信里的网页应用开发,前台页面中为了调用图像接口,使用了JSSDK.按照官方文档进行了正确配置. 现象:WEB开发工具调试一切正常,但从手机企业微信应用进入页面后接口调用无效(这个页面是从一级页面链接过来的),开了调试模式后,显示config:ok.说明配置无误.经过反复检查,终于发现问题所在. 原因:在一级页面(http://xx.xxx.xxx/main/index)中的链接是使用htmlhelper来写的,即@Html.ActionLink("测试接口",&qu

ASP.NET MVC与CSRF(跨站脚本)攻击

CSRF 一 何为CSRF CSRF(Cross-site request forgery跨站请求伪造,也被称成为"one click attack"或者session riding,通常缩写为CSRF或者XSRF,是一种对网站的恶意利用.需要注意的是,CSRF与XSS的区别,CSRF是其他网站进行对你的网站的攻击. 关于CSRF的详细信息请看:https://baike.baidu.com/item/CSRF/2735433 二 CSRF的危害 对CSRF进行简单了解后,我们先来看看

95后实习生的远程办公体验(asp.net mvc\C#技术栈)

这个月我们做了一件别人看起来很疯狂的事情,就是让一批95后的实习生实行远程办公,效果还不错,于是写此文总结一下. 其实认真算算,我自己的远程工作经验有十年了吧,在北京工作的时候天气不好就申请在家办公,在硅谷的时候每周有三天在家办公,两天去办公室办公.所以我也算得上是远程办公的老司机了吧. 不过,我之前都是对有多年工作经验的老司机才实行远程办公,还从来没有对还未毕业的实习生实行过.老实说,不敢啊,也不放心,况且我在cnblogs博客园呆了十年,还真没见过对还未毕业的实习生实行过远程办公的. 那为什

视图框架:Spring MVC 4.0(1)

目录 一.表单标签库 1.1.简介 1.2.常用属性 1.3.form标签与input标签 1.4.checkbox标签 1.5.radiobutton标签 1.6.password标签 1.7.select标签 1.8.option标签 1.9.options标签 1.10.textarea.errors标签 1.11.hidden标签 1.12.radiobuttons 单选列表与checkboxs复选列表 二.视图解析器 2.1.ViewResolver视图解析器 2.2.链式视图解析器

Spring MVC HTTP请求数据绑定

package com.springmvc.controller; import com.springmvc.model.UserInfo; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.stereotype.Controller; import org.springframework.uti

MVC概述

学习MVC模式   一.MVC简介 MVC是Model-View-Controller的简称,即模型-视图-控制器.MVC是一种设计模式,它把应用程序分成三个核心模块:模型.视图.控制器,它们各自处理自己的任务. 1.模型(Model) a.模型是应用程序的主体部分,模型表示业务数据和业务逻辑. b.一个模型能为多个视图提供数据. c.由于应用于模型的代码只需写一次就可以被多个视图重用,所以提高了代码的可重用性. 2.视图(View): 简单来说就是在页面上填写java代码实现显示. 详细来说视