简体   繁体   中英

SPRING 3.0 MVC 2 page 1 controller

I just want to have 2 functions in JAVA Spring 3.0 MVC like page1.htm and page2.htm and just 1 controller, kinda is in CodeIgniter , i don't know why is so hard ...

This is what i did till now

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package controllers;

import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

// Import models
import models.LoginModel;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 *
 * @author Candy
 */

@RequestMapping("/app")
public class LoginController extends SimpleFormController {
    public LoginController()
    {
        //Initialize controller properties here or 
        //in the Web Application Context

        setCommandClass(models.Employee.class);
        setCommandName("Employee");
        //setSuccessView("pages/login/login_form_view");
        //setFormView("pages/login/login_execute_view");
    }


    // On form load
    @Override
    protected ModelAndView showForm(HttpServletRequest request, HttpServletResponse response, BindException errors) throws Exception 
    {
        LoginModel loginModel = new LoginModel(request);

        if(!loginModel.isLogged())
        {
            ModelAndView mv = new ModelAndView("pages/login/login_form_view");

            // mv.addObject("chestie",loginModel.isLogged());

            return mv;
        }
        else
        {
            return new ModelAndView("redirect:/dashboard.htm");
        }


    }

    @Override
    protected void doSubmitAction(Object command) throws Exception
    {
        throw new UnsupportedOperationException("Not yet implemented");
    }

    //Use onSubmit instead of doSubmitAction 
    //when you need access to the Request, Response, or BindException objects
    @Override
    protected ModelAndView onSubmit(
    HttpServletRequest request, 
    HttpServletResponse response, 
    Object command, 
    BindException errors) throws Exception 
    {
        // User has submited a POST request
        ModelAndView mv = new ModelAndView("pages/login/login_execute_view");

        // Check if the user is logged or not, user must be NOT LOGGED in order to log
        LoginModel loginModel = new LoginModel(request);
        if(!loginModel.isLogged())
        {
            // Just continue
            String email = request.getParameter("email").toString();
            String password = request.getParameter("password").toString();

            // Check this email/pass
            Map<String,String> resultLogin = loginModel.login(email, password);

            String result = resultLogin.get("result").toString();
            String reason = resultLogin.get("reason").toString();
            // String qqq = resultLogin.get("qqq").toString();

            /*
            java.util.Date dt = new java.util.Date();

            java.text.SimpleDateFormat sdf = 
                 new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            String currentTime = sdf.format(dt);
            */
            if(result == "true")
            {
                // Login is good, redirect to dashboard
                return new ModelAndView("redirect:/dashboard.htm");

                // Display the error
                //mv.addObject("loginResult",result);
                //mv.addObject("loginReason",reason);
                //mv.addObject("qqq",qqq);
                //mv.addObject("qqq2",request.getSession().getAttribute("is_logged").toString());
            }
            else
            {
                // Display the error
                mv.addObject("loginResult",result);
                mv.addObject("loginReason",reason);

                return mv;
            }

        }
        else
        {
            return new ModelAndView("redirect:/login.htm");
        }
    }     
}

this controller will not work if I remove

applicationContext.xml
<bean class="controllers.LoginController"/>

dispatcher-servlet.xml
<bean class="controllers.LoginController" p:formView="pages/login/login_form_view" p:successView="pages/login/login_execute_view"/>

web.xml
<servlet>
    <servlet-name>LoginController</servlet-name>
    <servlet-class>controllers.LoginController</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>LoginController</servlet-name>
    <url-pattern>/login</url-pattern>
</servlet-mapping>
  1. Why i have to edit 3 XML when i create a new controller? Is not a simpler way?

  2. All i want right now is just make another function logout() that loads the ModelAndView mv = new ModelAndView("pages/login/logout_view"); , that's all.

And this

@RequestMapping("/app")
@Override
protected ModelAndView showForm(HttpServletRequest request, HttpServletResponse response, BindException errors) throws Exception 
{
    ModelAndView mv = new ModelAndView("pages/login/login_form_view");

    return mv;
}

gives me 404 error ...

  1. What should i use? SimpleFormController , extend Controller , AbstractController (i'm using NETBEANS ). I'm confused, i wish there were a good java framework like CodeIgniter . I don't quite understand how mappings work, but i do know how an apache rewrite works.

Thank you very much.

If you are using Spring 3, you can easily use @controller annotation for your controller class which are used for your page request and navigation.

You can use @Service annotation for your business logic and @Repository for your Database transaction and bind these layers together using @Autowired annotation as well .

so your request goes this way ( UI Request -> @Controller -> @Service -> @Repository ) and come back to the original controller class again for navigation.

But about your question, when you mark a class with @Controller annotation in spring, that simply means you candidate that class for your URL mappings and navigations, the sample below show how you can use @RequestMapping annotation inside Controlller Class for your URL mapping:

@Controller
@RequestMapping("/employee")
public class Employees{

@AutoWired
private EmployeeServiceInterface empServInt;

  @ModelAttribute("empAdd")
  public Employee createEmployeeModel(){
      return new Employee();
  } 

  @RequestMapping(value="/add", method = RequestMethod.POST)
  public String addEmployee(@ModelAttribute("empAdd")Employee employee,Model model, HttpSesion session){

     Employee employee = empServInt.createUser(employee);
     if(yourCondition()){
          return "redirect:/TO_THIS_PAGE";
      }
    return "GO_TO_PAGE_NAVIGATION_HERE";
  }
}

note that @RequestMapping get activated when a request come with the URL HOST_NAME:PORT/PROJECT_NAME/employee/add because of @RequesMapping annotation value.

Secondly @ModelAttribute you saw in sample create a model for your page that helps you to submit the Employee Object Bean values from UI using commandName attribute in Spring Form tag which binds the html inputs to Employee Bean class by using path="" attribute :

<form:form commandName="empAdd" method="post" >...</form:form>

Thirdly take note that the @AutoWired can automatically wired an interface to an implementation so in my example if a class like EmployeeServiceImpl implements the interface EmployeeServiceInterface by calling the interface methods like: empServInt.createUser(employee); spring automatically call related EmployeeServiceImpl.createUser(employee) implementation method for you.

Fourthly: take note that for you to be able to use Controller and the Service & Repository annotation to work you should have defined the packages that have those annotations in your Spring Descriptor XML file like so:

<context:component-scan base-package="java.package" />

Fifthly if you noticed the method inside Employees has String return type that provide your navigation but for this to work you should have define the page prefix and suffix that is going to return inside your Spring Descriptor XMl file as well like so:

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/view/" />
    <property name="suffix" value=".jsp" />
</bean>

according to above config, if your method which is annotated with @RequestMapping is returning employee String, Spring go and fetch the page from this location:

[PREFIX]employee[POSSIX] --> /WEB-INF/view/employee.jsp

For better understanding I found a useful sample link for you. Link

Good Luck !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM