SpringMVC demo 小例子,实现简单的登录和挂号

1.成立一个动态的web工程

2.导入springMvc所急需的jar包(这里可以去网上找,资源有过多)

前两部就不详细描述了,前面才是纯正代码~

第一有一个web.xml文件,这一个属于大布局文件,由于只要写login,里面大概布置一下骨干条件就足以

 

<servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>
        org.springframework.web.servlet.DispatcherServlet
    </servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
     <servlet-name>springmvc</servlet-name>
     <url-pattern>/</url-pattern>
  </servlet-mapping>

投入的这么些叫Dispatcher
Servlet,可以依照servlet-name找到相应的小布置文件,也就是部署spring
MVC的文书

在web.xml文件同级目录下新建springmvc-servlet.xml文件,下边是springmvc-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:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-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">
    <!--默认的注解映射的支持 -->
    <mvc:annotation-driven/>
    <!--启用自动扫描 -->
    <context:component-scan base-package="controller"/>
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

在意表明的是,启动自动扫描,spring会在指定的包下(例如我这边是controller包),自动扫描标注@Controller的类

prefix指的是回去的值给电动加一个前缀,同理suffix指的就是后缀

图片 1

 

 图片 2

见到此间也是够忙绿了,下面是交由的完好目录,下边起先写逻辑代码,先从loginController起始

@Controller
public class LoginController {
    @RequestMapping(value="/",method=RequestMethod.GET)
    public String sayHello(){
        //model.addAttribute("msg", "Hello,World!");
        return "login";
    }

释疑下面代码,@Controller,标注这一个类是Controller类,spring会自动举行扫描,@Request
Mapping中的value指的是url中的地址后缀,设置成/的目标自然是为着便利啊,

譬如说启动工程时,url只需要输入什么localhost:8080/项目名,它就会活动跳转到login页面;method指的是来的url是post请求依旧get请求

return的是login字符串,我们还记得上边说的prefix了吧,它就会把你的url自动拼接上,完整路径就是下面这一个

/WEB-INF/jsp/login.jsp

 接下来看login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>login</title>
</head>
<body>
    <form action="login" method="post">
        用户名:<input type="text" name="username"/><br/>
        密&nbsp;&nbsp;码:<input type="password" name="password"/>
        <input type="submit" value="登陆"/>
        <a href="regist">注册</a>
    </form>
</body>
</html>

此处的action再次来到的是login,Controller会自动捕获到这多少个请求,于是在login
Controller中要有一个方法来捕获这一个请求

@RequestMapping(value="login",method=RequestMethod.POST)
    public String login(Model model, // 向前台页面传的值放入model中
            HttpServletRequest request){ // 从前台页面取得的值
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String user_name = LoginCheck.check(username, password);
        if(user_name != null && user_name != ""){
            model.addAttribute("msg", user_name);
            return "success";
        }else{
            return "login2";
        }
    }

登陆嘛,当然要有证实,于是就有了LoginCheck,不多说,上代码

package logic;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import dao.Dao;

public class LoginCheck {

    public static String check(String username,String password){
        try {
            Connection conn = Dao.getConnection();
            PreparedStatement p = conn.prepareStatement("select * from user_t where user_name=? and password=?");
            p.setString(1, username);
            p.setString(2, password);
            ResultSet rs = p.executeQuery();
            if(rs.next()){
                String user_name = rs.getString("user_name");
                Dao.close(rs, p, conn);
                return user_name;
            }
            Dao.close(rs, p, conn);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
}

向数据库查询就要有DAO啦,Dao网上都有,我的就是在网上随便找一个改动就用了~

package dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class Dao {
    // 获取数据库连接
    public static Connection getConnection(){

        Connection conn = null;
        String url = "jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf8&useSSL=false&serverTimezone=Hongkong";
        try
        {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection(url,"root","数据库密码");//大家分享代码的时候也不要暴露自己的数据库密码,这样是非常不安全的
        }
        catch(ClassNotFoundException e)
        {
            e.printStackTrace();
            System.out.println("数据库驱动加载出错");
        }
        catch(SQLException e)
        {
            e.printStackTrace();
            System.out.println("数据库出错");
        }
        return conn;
    }
     //关闭相关通道
    public static void close(ResultSet rs,PreparedStatement p,Connection conn)
    {
        try
        {
            if(!rs.isClosed()){
                rs.close();
            }
            if(!p.isClosed()){
                p.close();
            }
            if(!conn.isClosed()){
                conn.close();
            }
        }
        catch(SQLException e)
        {
            e.printStackTrace();
            System.out.println("数据关闭出错");
        }
    }
    //关闭相关通道
    public static void close(PreparedStatement p,Connection conn)
    {
        try
        {
            if(!p.isClosed()){
                p.close();
            }
            if(!conn.isClosed()){
                conn.close();
            }
        }
        catch(SQLException e)
        {
            e.printStackTrace();
            System.out.println("数据关闭出错");
        }
    }
}

好了,假使查询的结果十分上数据库中询问到的值了,那么就可以跳转到success页面了,success.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>登陆成功</title>
</head>
<body>
    登陆成功!
    欢迎~${msg};
</body>
</html>

login大功告成,接下去的挂号页面和这一个道理相似,我不多废话了,把代码附上供我们参考

首先是regist.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>注册页面</title>
</head>
<body>
    <form action="registSuccess" method="Post">
        用户名:<input type="text" name="username"/>
        密&nbsp;&nbsp;码<input type="text" name="password"/>
        年&nbsp;&nbsp;龄<input type="number" name="age"/>
        <input type="submit" value="提交"/>
    </form>
</body>
</html>

接下去是RegistController

package controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import logic.RegistCheck;

@Controller
public class RegistController {
    @RequestMapping(value="regist",method=RequestMethod.GET)
    public String regist(){
        return "regist";
    }

    @RequestMapping(value="registSuccess",method=RequestMethod.POST)
    public String registSuccess(HttpServletRequest request,Model model){
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String age = request.getParameter("age");

        if(RegistCheck.registCheck(username, password,age)){
            model.addAttribute("username", username);
            return "login";
        }else{
            return "regist2";
        }
    }
}

接下去是RegistCheck

 

package logic;

import java.sql.Connection;
import java.sql.PreparedStatement;

import dao.Dao;

public class RegistCheck {

    public static boolean registCheck(String username,String password,String age){
        String user_name = LoginCheck.check(username, password);
        if(user_name == null || user_name == ""){
            try {
                Connection conn = Dao.getConnection();
                PreparedStatement p = conn.prepareStatement("insert user_t(user_name,password,age) VALUES (?,?,?);");
                p.setString(1, username);
                p.setString(2, password);
                p.setString(3, age);
                p.executeUpdate();
                System.out.println("注册成功");
                Dao.close(p, conn);
                return true;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return false;
    }
}

还有一个registSuccess.jsp,成功重回的页面,我只是放了个空页面,没内容

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>注册成功</title>
</head>
<body>
    注册成功!
</body>
</html>

好了,现在终止login和注册页面都写好了,新人刚到公司的时候非凡容易碰着这样的小训练,哈哈哈说多了,喜欢就点赞哈

欢迎转载,转载请阐明出处~

Java从读书到抛弃,MySQL从删库到跑路,哈哈哈

 

相关文章