1. LoginService
  2. LoginServiceImpl
  3. LoginController class

LoginService:

public interface LoginService {
	public boolean checkLogin(String userName, String userPassword);
}

LoginServiceImpl class:

@Service("loginService")
public class LoginServiceImpl implements LoginService {

	@Autowired
	private LoginDAO loginDAO;

	public void setLoginDAO(LoginDAO loginDAO) {
		this.loginDAO = loginDAO;
	}

	public boolean checkLogin(String userName, String userPassword) {
		System.out.println("In Service class...Check Login");
		return loginDAO.checkLogin(userName, userPassword);
	}

LoginController class:

In the LoginController we have to modify the validation logic to use the service class for validating the user. LoginController class:

@Controller
@RequestMapping("loginform.html")
public class LoginController {

	@Autowired
	public LoginService loginService;

	@RequestMapping(method = RequestMethod.GET)
	public String showForm(Map model) {
		LoginForm loginForm = new LoginForm();
		model.put("loginForm", loginForm);
		return "loginform";
	}

	@RequestMapping(method = RequestMethod.POST)
	public String processForm(@Valid LoginForm loginForm, BindingResult result, Map model) {

		if (result.hasErrors()) {
			return "loginform";
		}

		boolean userExists = loginService.checkLogin(loginForm.userName(), loginForm.getPassword());
		if (userExists) {
			model.put("loginForm", loginForm);
			return "loginsuccess";
		} else {
			result.rejectValue("userName", "invaliduser");
			return "loginform";
		}

	}

For creating full login site we should add Hibernate and MySql driver dependencies in pom.xml file. Another thing is to add applicationContext.xml file for initializing Spring and Hibernate related components. For example bean definition for MySQL dataStructure and sessionFactor which will be used in DAO classes.

Thera are also a few changes in: web.xml:

<display-name>Spring4Example</display-name>
	<servlet>
		<servlet-name>dispatcher</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>dispatcher</servlet-name>
		<url-pattern>/forms/*</url-pattern>
	</servlet-mapping>
	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>

	<context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>

    <listener>
        <listener-class>
            org.springframework.web.context.ContextLoaderListener
        </listener-class>
    </listener>

My site is free of ads and trackers. Was this post helpful to you? Why not BuyMeACoffee