实现登录的方式
零零散散的复习一下,防止以后糊涂或者忘记了
jsp页面关键部位:
<form action="${pageContext.request.comtextPath}/login" method="post">
***********省略一些代码
<input name = "username" type="text" class="textinput"/>
<input name = "password" type="password" class="textinput">
***********
</form>
servlet.java部分代码
public class LoginServlet extends HttpServlet{
private static final long serialVersionUID = 1L;
**********
public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{
//1.获取登录页面表单输入的用户名和密码
String username = request.getParameter("username");
String password= request.getParameter("password");
//2.调用service层方法
UserService service = new UserService();
User user = service.login(username,password);
*******
}
}
Service层
public User login(String username,String password){
//从Dao,进行与数据库的操作,根据名字和密码查询
User user = dao.findUserByUsernameAndPassword(username,password);
if(user !=null){
return user;
}
}
dao层
public User findUserByUsernameAndPassword(String username,String password) throw SQLException{
String sql="select *from user where user=? and password=?";
//连接数据库的方法
//或者第二种连接方法
//获取JdbcTemplate类,使用JdbcTemplate来操作数据库
//JdbcTemplate jdbc=new JdbcTemplate(new ComboPooledDataSource());
//String sql = "select * from users where user=? and password=?";
QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());
return runner.query(sql,new BeanHandler<User> (User.class),username,password);
}
- SSM框架 ->controller->service->serviceImpl->dao->mapper
controller
@Controller
public class UserController{
@Autowired
private UserService userService;
@RequestMapping("/login.action",method=RequestMethod.POST)
public String login(String username,String password,Model model,HttpSession session){
//添加HttpSeesion是为了以后要进行其他操作时,可以从seesion里面拿取数据
User user = userService.findUser(user,password);
if(user ! = null){
session.setAttribute("USER_SESSION",user);
return "head";
}
model.addAttribute("msg","你的账号密码错误,请重新输入!");
return "login";
}
}
UserServiceImpl层
@Service
public class UserServiceImpl implements UserService{
@Autowired
private UserDao userDao;
public User findUser(String username,String password){
User user = this.userDao.findUser(username,password);
return user;
}
}
UserService层
public interface UserService{
public User findUser(String username,String password);
}
Dao层
public interface UserDao{
public User findUser(@Param("username") String username,@Param("password") String password);
}
UserDao.xml层
<mapper namespace = "com.****你的xml包名位置">
<select id="findUser" parameterType="String" resultType="user">
select* from sys_***(数据库对应的表名) where username=#{username}
and userpassword=#{password}
</select>
要是代码有错误之处,还望各位大佬指出来!