I'm working e-commerce store project using spring mvc. In a JSP login page, i need to check user name and user password after clicking submit button. If all information are ok then i'm gonna go to the next page, otherwise stay on the same page.
This is my Administrator class(Model) Administrator.java
#Entity
#Table(name="ADSMINISTRATOR")
public class Administrator {
#Id
private String userName;
private String userPassword;
//getter and setter
}
This is my controller class AdministratorController.java
#Controller
#RequestMapping(value="/administratorController")
public class AdministratorController {
#RequestMapping(value="/loginForm.html")
public ModelAndView getAdministratorLoginForm() {
return new ModelAndView("Administrator");
}
public ModelAndView goToMainPage(#ModelAttribute("administrator") Administrator administrator) {
//Checking userName and userPassword here
//if ok then
return new ModelAndView("mainPageDemo");
}
}
And this is my JSP(View) Administrator.jsp
<body>
<table>
<tr> <td>User Name: </td> <td><input type="text" name="userName" value="" placeholder="User Name"></input></td> </tr>
<tr> <td>User Password: </td> <td><input type="text" name="userPassword" value="" placeholder="User Password"></input></td> </tr>
<tr><td><input type="submit"></input></td> </tr>
</table>
</body>
</html>
Now When I click submit button in Administrator.jsp page, I need to execute goToMainPage() method in AdministratorController.java class. How can i do this?
Related
i tried this code for login page and am getting the above error , am new to spring please help me.
#Controller
#RequestMapping("/login")
public class LoginController {
#Autowired
private LoginService loginser;
#RequestMapping("/loginadmin")
public String loginAdmin() {
return "loginadmin";
}
#RequestMapping("/loginemployee")
public String loginEmployee() {
return "loginemployee";
}
#RequestMapping("/adminvalidate")
public #ResponseBody String validateAdmin(#RequestParam(value="userid") String userid, #RequestParam(value="password") String password) {
String result = loginser.validate(userid, password);
if (result.equals("pass")) {
return "redirect:/admin/view";
}
return "error";
}
}
ui
<div id="wrapper">
<div id="header">
<h1>Admin Login</h1>
</div>
</div>
<div id="container">
<div id="content">
<form:form action="adminvalidate"
method="POST">
<table>
<tbody>
<tr>
<td><label>User-Id : </label></td>
<td><input type="text" path="emp_Id" placeholder="User Id" id="userid"/></td>
</tr>
<tr>
<td><label>Password : </label></td>
<td><input type="password" path="emp_firstname" placeholder="Password" id="password"/></td>
</tr>
<tr>
<td><label></label></td>
<td><input type="submit" value="login"></td>
</tr>
</tbody>
</table>
<input type="button" value="back" onclick="window.location.href='/';return false">
</form:form>
</div>
</div>
i need to write code for login page that to check the credentials and am getting 400 error
Since you put an image instead of code ,I can not see the entire code of yours,
According to your question,the reason is the userid parameter is not passed to your controller method,check if you have set the name of user id input element as below:
<input type='text' name='userid' path='emp_id'>
Another possible way to avoid this issue is set the required=false in your controller method:
public #ResponseBOdy String validateAdmin(#RequestParam(value="userid",required=false)){
}
400 error comes when the server was unable to process the request sent by the client due to invalid syntax. check your URL syntax and you didn't give the method name in controller Like POST
In my application the user clicks a link to edit an exam of their choice.
When they click the link it should open the editExam.html and the URL contains the ID of the exam they selected.
When I click the link the URL is correct (it contains the exam ID) however it doesn't display the editExam.html page it just displays my main page (the default localhost page)
allSubjects.html (the page where the user selects which exam to edit)
<h4> exams:</h4>
<div th:each="exam : ${subject.exam}">
<h4 th:text="${exam.examTitle}"/>
<a th:href="#{/editExam.html(id=${exam.examId})}">Edit Exam</a>
editExam.html (this is the page I can't display)
<form action="#"th:action="#{/editExam.html{examId}}" th:object="${exam}" method="put">
<table>
<tr>
<td> Exam Title:</td>
<td><input type="text" th:field="*{examTitle}" th:text="${exam.examTitle}"/></td>
<!-- <td th:if="${#fields.hasErrors('examTitlee')}" th:errors="*{examTitle}">error message</td> -->
</tr>
<tr>
<td> Exam grade worth </td>
<td><input th:field="*{examGradeWorth}" /></td>
<!-- <td th:if="${#fields.hasErrors('examGradeWorth')}" th:errors="*{examGradeWorth}">error message</td> -->
</tr>
<tr>
<td>examGradeAchieved</td>
<td><input th:field="*{examGradeAchieved}"/></td>
</tr>
<tr>
<td><button type="submit">Submit post</button></td>
</tr>
</table>
</div>
</form>
My controller:
//Update an exam
#RequestMapping(value = "/editExam.html{examId}", method = { RequestMethod.POST, RequestMethod.PUT})
public String editExam(#ModelAttribute("exam") #PathVariable(value = "examId")Long examId, #RequestBody Exam exam,Model model, BindingResult result) {
examRepository.findOne(examId);
model.addAttribute("examTitle", exam.getExamTitle());
model.addAttribute("examGradeWorth", exam.getExamGradeWorth());
model.addAttribute("examGradeAchieved", exam.getExamGradeAchieved());
exam.setExamTitle(exam.getExamTitle());
exam.setExamGradeWorth(exam.getExamGradeWorth());
exam.setExamGradeAchieved(exam.getExamGradeAchieved());
examRepository.save(exam);
return "editExam";
}
This code was displaying the editExam page before I added "RequestMethod.POST" to the controller.
Try to change
<a th:href="#{/editExam.html(id=${exam.examId})}">Edit Exam</a>
to
<a th:href="#{/exam/{id}(id=${exam.examId})}">Edit Exam</a>
and in your Controller
#RequestMapping(value = "/editExam.html{examId}", method = { RequestMethod.POST, RequestMethod.PUT})
to
#RequestMapping(value = "/exam/{examId}", method = { RequestMethod.POST, RequestMethod.PUT})
This url does not look correct. It should be /editExam.html?id=1, without a /.
I noticed that you are mixing request params and path variables. In your controller you expect #PathVariable(value = "examId") but in the view you are specifying request parameter instead of path variable.
Check this post: #RequestParam vs #PathVariable
I'm in the process of upgrading our web app to use Wicket 7 (was using 6.19).
The first page is a login screen, but for some reason, the form's onSubmit() method isn't being called, so on clicking the submit button, I just get the login page re-displayed.
I've consulted the Wicket 7 migration guide, which doesn't mention any specific changes in this area.
It's a pretty straightforward case, as you can see, it's a simple form containing username and password fields
<form wicket:id="loginform" id="loginform" >
<table style="display: table; border: 0px; margin: auto;">
<tr style="display: table-row;">
<td class="login" colspan="2"><span wicket:id="feedback">Feedback</span></td>
</tr>
<tr style="display: table-row;">
<td class="login">
<label for="username"><wicket:message key="username">Username</wicket:message>: </label>
</td>
<td class="login">
<input wicket:id="username" id="username" type="text" name="user" value="" size="30" maxlength="50"/>
</td>
</tr>
<tr style="display: table-row;">
<td class="login">
<label for="password"><wicket:message key="password">Password</wicket:message>: </label>
</td>
<td class="login">
<input wicket:id="password" id="password" type="password" name="pswd" value="" size="30" maxlength="16"/>
</td>
</tr>
<tr style="display: table-row;">
<td class="login"> </td>
<td class="login"><input class="btn" type="submit" name="Login" value="Login" wicket:message="title:loginButtonTitle"/></td>
</tr>
</table>
</form>
Here's the Java code setting up the page components -
public class Login extends UnSecurePageTemplate {
private static final long serialVersionUID = -7202246935258483555L;
#SpringBean private IBrandingService brandingService;
#SpringBean private IRemonService remonService;
#SpringBean private IUserAdminService userAdminService ;
private static final Logger logger = LoggerFactory.getLogger( Login.class);
public Login() {
this(new PageParameters());
}
public Login(PageParameters pageParameters) {
super(pageParameters);
BrandingThemeProperties properties = brandingService.getBrandingThemeProperties();
String welcomeLabel = properties.getProperty("welcome-label");
add(new Label("welcome", welcomeLabel));
add(new Label("loginHeader", getStringFromPropertiesFile("loginInstruction", this)));
LoginForm form = new LoginForm("loginform", new SimpleUser(), pageParameters);
form.add(new FeedbackPanel("feedback"));
add(form);
}
And here's the Login form (the login() method authenticates the user and returns another page) -
public final class LoginForm extends Form<SimpleUser>
{
PageParameters pageParameters;
public LoginForm(String id, SimpleUser simpleUser, PageParameters pageParameters)
{
super(id, new CompoundPropertyModel<SimpleUser>(simpleUser));
this.pageParameters = pageParameters;
add(new TextField<String>("username").setRequired(true).add(StringValidator.maximumLength(50)));
add(new PasswordTextField("password").setResetPassword(true).add(StringValidator.maximumLength(50)));
}
/**
* Called upon form submit. Attempts to authenticate the user.
*/
protected void onSubmit()
{
SimpleUser user = getModel().getObject();
String username = user.getUsername();
String password = user.getPassword();
login(username, password, pageParameters);
}
}
I also tried using a submit Button, but its onSubmit() wasn't called either.
I am learning Spring MVC using Spring In Action 3rd Action, I have implemented the basic program which shows the user registration form and once we submit the form, it will be validated using #Valid.
Here is my Spring Controller:
#Controller
#RequestMapping("/spitter")
public class SpitterController {
private final SpitterService spitterService;
#Inject
public SpitterController(SpitterService spitterService) {
this.spitterService = spitterService;
}
#RequestMapping(method = RequestMethod.GET, params = "new")
public String createSpitterProfile(Model model) {
Spittle spittle = new Spittle();
model.addAttribute(spittle);
model.addAttribute(new Spitter());
return "spittles/edit";
}
#RequestMapping(method = RequestMethod.POST)
public String addSpitterFromForm(#Valid Spitter spitter,
BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return "spittles/edit";
}
spitterService.saveSpitter(spitter);
return "redirect:/spitter/" + spitter.getUsername();
}
}
Here is my Spitter class file:
package com.habuma.spitter.domain;
import java.util.List;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
public class Spitter {
private Long id;
#Size(min = 3, max = 20, message = "User name must be between 3 and 20 characters long.")
#Pattern(regexp = "^[a-zA-Z0-9]+$", message = "Username must be alphanumeric with no spaces")
private String username;
#Size(min = 6, max = 20, message = "The password must be atleast 6 characters long.")
private String password;
#Size(min = 3, max = 50, message = "Your full name must be between 3 and 50 characters long.")
private String fullName;
#Pattern(regexp = "[A-Za-z0-9._%+-]+#[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}", message = "Invalid email address.")
private String email;
private List<Spittle> spittles;
private boolean updateByEmail;
......Setters & Getters.....
#Override
public boolean equals(Object obj) {
Spitter other = (Spitter) obj;
return other.fullName.equals(fullName)
&& other.username.equals(username)
&& other.password.equals(password);
}
#Override
public int hashCode() {
return super.hashCode();
}
}
This is my edit.jsp file which is shown to the user for registration:
<%# taglib prefix="sf" uri="http://www.springframework.org/tags/form"%>
<div>
<h2>Create a free Spitter account</h2>
<sf:form method="POST" modelAttribute="spitter" enctype="multipart/form-data">
<fieldset>
<table cellspacing="0">
<tr>
<th><label for="user_full_name">Fullname:</label></th>
<td><sf:input path="fullName" size="15" id="user_full_name" />
<sf:errors path="fullName" cssClass="error" /></td>
</tr>
<tr>
<th><label for="user_screen_name">Username:</label></th>
<td><sf:input path="username" size="15" maxlength="15"
id="user_screen_name" /> <small id="username_msg">No spaces,please.</small>
<sf:errors path="username" cssClass="error" /></td>
</tr>
<tr>
<th><label for="user_password">Password:</label></th>
<td><sf:password path="password" size="30" showPassword="true"
id="user_password" /> <small>6
characters or more (betricky!)</small> <sf:errors path="password"
cssClass="error" /></td>
</tr>
<tr>
<th><label for="user_email">EmailAddress:</label></th>
<td><sf:input path="email" size="30" id="user_email" /> <small>In
case you forget something</small> <sf:errors path="email"
cssClass="error" /></td>
</tr>
<tr>
<th></th>
<td><sf:checkbox path="updateByEmail"
id="user_send_email_newsletter" /> <label
for="user_send_email_newsletter">Send me email updates!</label></td>
</tr>
<tr>
<th><label for="image">Profile image:</label></th>
<td><input name="image" type="file" />
</tr>
<tr>
<th></th>
<td><input name="commit" type="submit"
value="I accept.Createmyaccount." /></td>
</tr>
</table>
</fieldset>
</sf:form>
</div>
To load the form I am accessing the URL as : http://localhost:8081/SpringInAction3/spitter?new, once the form is loaded I am just submitting the form without entering any details so that I can check if my form is getting validated or not. But I am getting below exception:
java.lang.NullPointerException
com.habuma.spitter.domain.Spitter.equals(Spitter.java:87)
org.hibernate.validator.engine.resolver.SingleThreadCachedTraversableResolver$TraversableHolder.equals(SingleThreadCachedTraversableResolver.java:138)
java.util.HashMap.get(HashMap.java:305)
org.hibernate.validator.engine.resolver.SingleThreadCachedTraversableResolver.isReachable(SingleThreadCachedTraversableResolver.java:45)
org.hibernate.validator.engine.ValidatorImpl.isValidationRequired(ValidatorImpl.java:757)
org.hibernate.validator.engine.ValidatorImpl.validateConstraint(ValidatorImpl.java:324)
org.hibernate.validator.engine.ValidatorImpl.validateConstraintsForRedefinedDefaultGroup(ValidatorImpl.java:273)
org.hibernate.validator.engine.ValidatorImpl.validateConstraintsForCurrentGroup(ValidatorImpl.java:256)
org.hibernate.validator.engine.ValidatorImpl.validateInContext(ValidatorImpl.java:210)
org.hibernate.validator.engine.ValidatorImpl.validate(ValidatorImpl.java:119)
org.springframework.validation.beanvalidation.SpringValidatorAdapter.validate(SpringValidatorAdapter.java:106)
org.springframework.validation.DataBinder.validate(DataBinder.java:760)
I am getting NullPointerException in my equals method of Splitter class. Please let me know where I am doing mistake?
Edit:
When I tried to print the values of the fields in my Spitter object I am getting null for all the fields so that is causing the NullPointerException.
This time I removed the equals and hashCode methods from my Spitter class, now when I am submitting the form, the validation is not happening and the page is going to http://localhost:8081/SpringInAction3/spitter/null without showing any errors.
Why the validation is not happening in this case? Also if I just follow the steps in that book, I am getting NullPointerException which is not expected. Please let me know where I am doing mistake?
As per this SO post : #Valid (jsr 303) not working in Spring mvc 3.0, I also have the tag <mvc:annotation-driven/> in my configuration file.
I see one mistake so far. The sf:form attribute enctype is set as multipart/form-data but that is only used on file uploads, so i guess spring mvc is using the MultipartResolver instead of Data binding mechanism that binds form data to form backing objects , try changing it to application/x-www-form-urlencoded, which is the default and correct type for your case.
I asked a question earlier how to do this using Webflow, but it has proven to be impractical for my situation.
I am trying to have a walk through 3 screens which add to an object information and then require a confirm to add to the database at the end. [To maintain simplicity etc]
The first screen takes in username for example
then the next screen requires contact information
then the third screen shows a summary and asks to confirm
I am having trouble figuring out how to pass the same object through several screens. I understand how to pass information from one screen to next, but for some reason same technique doesn’t work through several screens.
Sample 3 pages:
AddUser.jsp
<div id="form">
<h2 >Step 1</h2>
<form action="AddUserContact" method="post">
<table>
<tr>
<td>User Name:</td>
<td><input type="text" id="username" name="username"/></td>
</tr>
<tr>
<td><input type="submit" value="Next"/></td>
</tr>
</table>
</form>
</div>
AddUserContact.jsp
<div id="form">
<h2 >Step 2</h2>
<form action="UserSummaryConfirm" method="post">
<table>
<tr>
<td>${user.username}</td>
</tr>
<tr>
<td>Address:</td>
<td><input type="text" id="address" name="address"/></td>
</tr>
<tr>
<td><input type="submit" value="Next"/></td>
</tr>
</table>
</form>
</div>
UserSummaryConfirm.jsp
<h2>Step 3</h2>
<form action="home" method="post">
<table>
<tr>
<td>User Name:</td>
<td>${user.username}</td>
</tr>
<tr>
<td>Address:</td>
<td>${address}</td>
</tr>
<tr>
<td>Confirm</td>
</tr>
</table>
</form>
I have a Controller for every page [its for me to understand better what is going on, Ill simplify it later]
AddUserController.java
#Controller
public class AddUserController{
#RequestMapping(value = "AddUser")
public ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
User user = new User();
ModelAndView mav = new ModelAndView("AddUser");
user.setUserName(request.getParameter("username"));
mav.addObject("user", user);
return mav;
}
}
AddUserContactController.java
#Controller
public class AddUserContactController{
#RequestMapping(value = "AddUserContact")
public ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
ModelAndView mav = new ModelAndView("AddUserContact");
mav.addObject("user", request.getParameter("user"));
return mav;
}
}
AddUserConfirm.java
#Controller
public class AddUserConfirm{
#RequestMapping(value = "UserSummaryConfirm")
public ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
ModelAndView mav = new ModelAndView("UserSummaryConfirm");
mav.addObject("user", request.getParameter("user"));
mav.addObject("address", request.getParameter("address"));
return mav;
}
}
And then the User class is just a simple class with getters and setters.
The problem I am having is no matter what I have tried to pass the object, I cannot seem to figure out why the same technique doesnt work.
The address on the third screen is beeing displayed no problem, but the username is not displayed on any of the screens.
With the webflow the way I did it was created a UserBean that was global to all webflow screens. It was easy to add to the same object from any screen and display any information. How can I achieve the same result for this?
Thank you.
WORKING CODE:
Using SessionAttributes
AddUser.jsp
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<div id="form">
<h2 >Step 1</h2>
<form:form action="AddUserContact" commandName="user" method="POST">
<table>
<tr>
<td>User Name:</td>
<td><form:input type="text" id="username" path="username"/></td>
</tr>
<tr>
<td><input type="submit" value="Next"/></td>
</tr>
</table>
</form:form>
</div>
AssUserContact.jsp
<div id="form">
<h2 >Step 2</h2>
<form:form action="UserSummaryConfirm" commandName="user" method="post">
<table>
<tr>
<td>Address:</td>
<td><input type="text" id="address" path="address"/></td>
</tr>
<tr>
<td><input type="submit" value="Next"/></td>
</tr>
</table>
</form>
</div>
UserSummaryConfirm.jsp
<h2>Step 3</h2>
<form:form action="home" method="get">
<table>
<tr>
<td>User Name:</td>
<td><%=session.getAttribute("username")%></td>
</tr>
<tr>
<td>Address:</td>
<td><%=session.getAttribute("address")%></td>
</tr>
<tr>
<td>Confirm</td>
</tr>
</table>
</form:form>
AddUserController.java
#Controller
#SessionAttributes({ "username", "address" })
public class AddUserController{
User usr = new User();
#RequestMapping(value = "AddUser")
public String loadIndex(Model model, User user) {
model.addAttribute("User", user);
return "AddUser";
}
#RequestMapping(value = "AddUserContact")
public String processUserName(Model model, User user) {
usr.setUsername(user.setUsername());
model.addAttribute("User", user);
return "AddUserContact";
}
#RequestMapping(value = "UserSummaryConfirm")
public String processUserContact(Model model, User user) {
usr.setAddress(user.getAddress());
model.addAttribute("username", usr.getUsername());
model.addAttribute("address", usr.getAddress());
return "UserSummaryConfirm";
}
Because in second screen you are using
<tr>
<td>${user.username}</td>
</tr>
User input is not bind to any input so it will not be passed to controller with form data .
While you are using address as
<tr>
<td>Address:</td>
<td><input type="text" id="address" name="address"/></td>
</tr>
As it is bind to input (as you have assigned name="address" which is same as path="name") so its value will be send to controller.
If you want to pass the same object across 3 screens then it's better use #SessionAttribute instead of hiding it and passing again and again.
EDIT :
As you are using session attribute now, remove input element .(which is bind to username) from second screen. Just use instead
<td>session.getAttribute("username")%></td>
I have done a "wizard-style" form like this before. My solution used a single form bean that we put into session for the entire process, and included only the pieces in each page that needs to be added. Spring will not erase a value in the form bean unless you include an input for the given value. We don't use JSR-303, and I don't think this method would work if you are using it. Our validation uses a combination of BindingErrors and custom validation code, so I just setup the code to only validate portions at a time, corresponding to what page the form just submitted.