你的位置:首页 > Java教程

[Java教程]SpringMVC demo 小例子,实现简单的登录和注册

1.创建一个动态的web工程

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

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

首先有一个web.

 

<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.

 

<? ="http://www.w3.org/2001/ ="http://www.springframework.org/schema/p" ="http://www.springframework.org/schema/context" ="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指的就是后缀

 

 

看到这里也是够辛苦了,上面是给出的完整目录,下面开始写逻辑代码,先从loginController开始

@Controllerpublic 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;@Controllerpublic 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从删库到跑路,哈哈哈