Spring学习4--登录示例

来源:互联网 发布:淘宝申请全球购的条件 编辑:程序博客网 时间:2024/06/10 04:55

工程目录:

这里写图片描述

1.导入spring相关jar包

2.填写配置文件

applicationContext.xml

    <util:properties id="jdbcProps" location="classpath:db.properties"/>    <context:component-scan base-package="com.test"/>    <!-- 视图处理 -->    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">        <property name="prefix" value="/WEB-INF/jsp/"></property>        <property name="suffix" value=".jsp"></property>    </bean>

db.properties

driver=com.mysql.jdbc.Driverurl=jdbc:mysql://localhost:3306/testuser=rootpwd=***

web.xml

    <servlet>        <servlet-name>springmvc</servlet-name>        <servlet-class>            org.springframework.web.servlet.DispatcherServlet        </servlet-class>        <init-param>            <param-name>contextConfigLocation</param-name>            <param-value>classpath:applicationContext.xml</param-value>        </init-param>        <load-on-startup>1</load-on-startup>    </servlet>     <servlet-mapping>        <servlet-name>springmvc</servlet-name>        <url-pattern>*.do</url-pattern>    </servlet-mapping>

3.创建实体类

public class User implements Serializable{    private int id;    private String name;    private String password;    private String phoone;    ...getter和setter...}

4.数据库连接类和dao方法

JdbcDataSource:

@Componentpublic class JdbcDataSource implements Serializable{    private String driver;    @Value("#{jdbcProps.url}")    private String url;    @Value("#{jdbcProps.user}")    private String user;    @Value("#{jdbcProps.pwd}")    private String pwd;    public String getDriver() {        return driver;    }    //必须使用Bean属性输入,否则不能进行JDBC Driver注册    @Value("#{jdbcProps.driver}")    public void setDriver(String driver) {        try {            Class.forName(driver);            this.driver = driver;        } catch (ClassNotFoundException e) {            e.printStackTrace();        }    }    public String getUrl() {        return url;    }    public void setUrl(String url) {        this.url = url;    }    public String getUser() {        return user;    }    public void setUser(String user) {        this.user = user;    }    public String getPwd() {        return pwd;    }    public void setPwd(String pwd) {        this.pwd = pwd;    }    public Connection getConnection() throws SQLException{        Connection conn = DriverManager.getConnection(url, user, pwd);        return conn;    }    public void close(Connection conn){        if(conn != null){            try {                conn.close();            } catch (SQLException e) {                e.printStackTrace();            }        }    }}

MysqlUserDao:

@Repository("userDao")public class MysqlUserDao implements UserDao, Serializable{    private JdbcDataSource dataSource;    public MysqlUserDao(){    }    public MysqlUserDao(JdbcDataSource dataSource){        this.dataSource = dataSource;    }    public JdbcDataSource getDataSource() {        return dataSource;    }    @Autowired    public void setDataSource(JdbcDataSource dataSource) {        this.dataSource = dataSource;    }    public User findByName(String name){        System.out.println("利用jdbc技术查找User信息");        String sql = "select * from aaa where name=?";        Connection conn = null;        try {            conn = dataSource.getConnection();            PreparedStatement ps = conn.prepareStatement(sql);            ps.setString(1, name);            ResultSet rs = ps.executeQuery();            User user = null;            while(rs.next()){                user = new User();                user.setId(rs.getInt("id"));                user.setName(rs.getString("name"));                user.setPassword(rs.getString("password"));                user.setPhoone(rs.getString("phoone"));            }            rs.close();            ps.close();            return user;        } catch (SQLException e) {            e.printStackTrace();            throw new RuntimeException(e);        }finally{            dataSource.close(conn);        }    }}

接口:

public interface UserDao {    public User findByName(String name);}

5.编写业务层Service

@Servicepublic class UserService implements Serializable{    private UserDao userDao;    public UserDao getUserDao() {        return userDao;    }    @Resource(name="userDao")    public void setUserDao(UserDao userDao) {        this.userDao = userDao;    }    //登录系统    public User login(String name, String pwd){        User user = userDao.findByName(name);        if(user != null && pwd.equals(user.getPassword())){            return user;        }else{            return null;        }    }}

6.控制层Controller

@Controller@RequestMapping("/login")public class LoginController {    @Autowired       private UserService userService;    @RequestMapping("/login.do")    public String loginForm(){        //向表单界面传参数        return "loginForm";//映射到loginForm.jsp    }    @RequestMapping("login-action.do")    public String checkLogin(HttpServletRequest req){        System.out.println("=====进入Controller====");        String name = req.getParameter("name");        String password = req.getParameter("password");        System.out.println(name+"~~~"+password);        User user = userService.login(name, password);        //登录成功将登录用户的信息保存在当前会话中        req.getSession().setAttribute("user", user);        return "success"; //映射到success.jsp中        //重定向:redirect:login.do    }}

7.编写JSP页面

loginForm.jsp:

    <h1>登录系统</h1>    <form action="login-action.do" method="post">        用户名:<input name="name" />        密码:<input name="password" />        <input type="submit" value="提交"/>    </form>

success.jsp:

<body>    登录成功    姓名:${user.name}    密码:${user.password}    手机:${user.phoone}</body>

8.调用链接

localhost:8080/工程名/login/loginForm.do

0 0
原创粉丝点击