Unable to logout using spring 4 MVC - java

I have used spring 4 MVC in my project which is annotation based.
I am able to login successfully but I am not able to logout.
I have posted the configuration,initializer and controller classes below
along with the login page and welcome page.Please let me know what changes need to be done to my code so that I log out successfully.
I am currently getting the below error on logout
Feb 06, 2017 2:36:03 PM org.springframework.web.servlet.PageNotFound noHandlerFound
WARNING: No mapping found for HTTP request with URI [/Student_Login/%3Cc:url%20value='/login'%20/%3E] in DispatcherServlet with name 'dispatcher'
AppConfig_login
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = "com.student.login")
public class AppConfig_login {
#Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
#Bean
public MessageSource messageSource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename("message");
return messageSource;
}
}
AppInitializer_login
public class AppInitializer_login extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { AppConfig_login.class };
}
#Override
protected Class<?>[] getServletConfigClasses() {
// TODO Auto-generated method stub
return null;}
#Override
protected String[] getServletMappings() {
return new String[] { "/" };
}}
AppController
package com.student.login.controller;
import java.util.List;
import java.util.Locale;
#Controller
#RequestMapping("/")
public class AppController_login {
#Autowired
StudentService service;
#Autowired
MessageSource messageSource;
/*
* This method will list all existing employees.
*/
#RequestMapping(value = {"/"}, method = RequestMethod.GET)
public String listStudents(ModelMap model) {
//List<Student> students = service.findAllStudents();
//model.addAttribute("students", students);
Student student = new Student();
model.addAttribute("student", student);
return "login";
}
#RequestMapping(value = { "/" }, method = RequestMethod.POST)
public String checkCredentials(#Valid Student student, BindingResult result,
ModelMap model) {
if (result.hasErrors()) {
return "login";
}
System.out.println(student.getRoll_no());
System.out.println(student.getPassword());
/*
* Preferred way to achieve uniqueness of field [ssn] should be implementing custom #Unique annotation
* and applying it on field [ssn] of Model class [Employee].
*
* Below mentioned peace of code [if block] is to demonstrate that you can fill custom errors outside the validation
* framework as well while still using internationalized messages.
*
*/
if(service.isCredentialValid(student.getRoll_no(),student.getPassword())){
FieldError login_Error =new FieldError("student","password",messageSource.getMessage("non.unique.credentials", new String[]{student.getRoll_no()}, Locale.getDefault()));
result.addError(login_Error);
return "login";
}
//service.saveStudent(student);
model.addAttribute("welcome", "Welcome Student " + student.getName() + " registered successfully");
return "welcome_student";
}
#RequestMapping(value = { "/login" }, method = RequestMethod.GET)
public String logoutPage(ModelMap model) {
Student student = new Student();
model.addAttribute("student", student);
//model.addAttribute("edit", false);
return "login";
}
/*
* This method will provide the medium to add a new employee.
*/
#RequestMapping(value = { "/registration" }, method = RequestMethod.GET)
public String newStudent(ModelMap model) {
Student student = new Student();
model.addAttribute("student", student);
model.addAttribute("edit", false);
return "registration";
}
/*
* This method will be called on form submission, handling POST request for
* saving employee in database. It also validates the user input
*/
#RequestMapping(value = { "/registration" }, method = RequestMethod.POST)
public String saveEmployee(#Valid Student student, BindingResult result,
ModelMap model) {
if (result.hasErrors()) {
return "registration";
}
if(!service.isStudentRollNoUnique(student.getRoll_no())){
FieldError roll_no_Error =new FieldError("student","roll_no",messageSource.getMessage("non.unique.roll_no", new String[]{student.getRoll_no()}, Locale.getDefault()));
result.addError(roll_no_Error);
return "registration";
}
service.saveStudent(student);
model.addAttribute("success", "Student " + student.getName() + " registered successfully");
return "login_success";
}}
login.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Student Registration Form</title>
<style>
.error {
color: #ff0000;
}
</style>
</head>
<body>
<h2>Login Form</h2>
<form:form method="POST" modelAttribute="student">
<!-- <form:input type="hidden" path="id" id="id"/>-->
<table>
<tr>
<td><label for="roll_no">Roll No:</label> </td>
<td><form:input path="roll_no" id="roll_no"/></td>
<td><form:errors path="roll_no" cssClass="error"/></td>
</tr>
<tr>
<td><label for="password">Password:</label> </td>
<td><form:input path="password" id="password"/></td>
<td><form:errors path="password" cssClass="error"/></td>
</tr>
<tr>
<td colspan="3">
<input type="submit" value="Submit"/>
</td>
</tr>
</table>
</form:form>
<br/>
<br/>
Go back to Registration
</body>
</html>
welcome_student
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
hello user
Logout
</body>
</html>

So I finally figured out that the problem was in my jsp welcome_student
I forgot to include the below line
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

Related

I can't find the error from .jsp

I can't figure it out why that is not working. That is the jsp that make me problems. I follow a tutorial from youtube and my jsp looks the same like the jsp from the video. I adapted the code from the video but i don't think that is the problem because the controller and the jsp are the same like those from the video.
here is the tutorial, jsp is at min 24
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Upload Page</title>
</head>
<body>
<spring:url value="/doUpload" var="doUplodaURL" />
<form:form method="post" modelAttribute="formUpload" action="${doUplodaURL
}" enctype="multipart/form-data" >
<form:input path="files" type="file" multiple="multiple"/>
<form:errors path="files" /><br/>
<button type="submit" >Upload</button>
</form:form>
</body>
</html>
and that is my controller
#Controller
public class CsvController {
#Autowired
FileValidator fileValidator;
#Autowired
CsvServices csvServices;
#RequestMapping(value = "/uploadPage", method = RequestMethod.GET)
public ModelAndView getPage() {
ModelAndView model = new ModelAndView("upload_page");
FileUpload formUpload = new FileUpload();
model.addObject("formUpload", formUpload);
return model;
}
#RequestMapping (value="/doUpload", method=RequestMethod.POST)
public String doUpload(#ModelAttribute("formUpload") FileUpload fileUpload, BindingResult result, RedirectAttributes redirectAttributes ) throws IOException {
fileValidator.validate(fileUpload, result);
if(result.hasErrors()) {
return "uploadPage";
} else {
redirectAttributes.addFlashAttribute("fileNames", uploadAndImportDb(fileUpload));
return "redirect:/succes";
}
}
#RequestMapping(value = "/succes", method = RequestMethod.GET)
public ModelAndView succes() {
ModelAndView model = new ModelAndView("succes");
return model;
}
private List<String> uploadAndImportDb(FileUpload fileUpload) throws IOException{
List<String> fileNames = new ArrayList<String>();
List<String> paths = new ArrayList<String>();
CommonsMultipartFile[] commonsMultipartFiles = fileUpload.getFiles();
String filePath = null;
for(CommonsMultipartFile multipartFile : commonsMultipartFiles) {
filePath = "C:\\Users\\bogda\\Desktop\\input\\" + multipartFile.getOriginalFilename();
File file = new File(filePath);
FileCopyUtils.copy(multipartFile.getBytes(), file);
fileNames.add(multipartFile.getOriginalFilename());
paths.add(filePath);
}
//parse and import
csvServices.process(paths);
return fileNames;
}
}
Kindly add commons-fileupload-x.x.jar inside WEb_INF/lib folder.

How can I update changed data on button?

I want to edit data of the user by inputting new value in the textbox such as his first name and show these changes in his profile.
I tried to use Ajax but I don't understand what the url should be in there.
That's my jsp file with edit form and Ajax script:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<script type="text/javascript">
$("edit").click(function() {
var firstName = $(request.getParameter("firstname")).val();
$.ajax({
url: '',
type: 'POST',
data: {
firstName: firstName
}
});
});
</script>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>${title}</title>
</head>
<body>
<h4>To edit your information fill the fields, please.</h4>
<form name='f' action="${pageContext.request.contextPath}/j_spring_security_check" method='POST'>
<table>
<tr>
<td>First Name:</td>
<td><input type='text' name='firstname' id='firstname' value='${firstname}'></td>
</tr>
<tr>
<td><input name="edit" type="submit" value="Submit" /></td>
</tr>
</table>
</form>
I have update and get methods for the first name in one of the classes:
public class UserInfoDAOImpl extends JdbcDaoSupport implements UserInfoDAO {
#Autowired
public UserInfoDAOImpl(DataSource dataSource) {
this.setDataSource(dataSource);
}
//.....other methods
#Override
public void editFirstName(String userName, String fName){
String sql = "update Users set FirstName = ? where Username = ?";
Object[] params = new Object[] {fName, userName};
this.getJdbcTemplate().update(sql, params);
}
#Override
public String getFirstName(String userName) {
// TODO Auto-generated method stub
String sql = "select u.FirstName from Users u where u.Username = ? ";
Object[] params = new Object[] { userName };
String firstName = (String)getJdbcTemplate().queryForObject(sql, params, String.class);
return firstName;
}
}
So I don't really get to use these already written methods to update the data and get these changes in user profile.
I am new to Ajax so I'm glad to get any help.
You are wrong on your JSP, the j_spring_security_check is default URL Spring Login.
For updating firstname you must do #RequestMapping #ResponseBody on your Controller de handle the Ajax Request.

Spring MVC, JSP do nor load properly my css

I created simple web-app using spring mvc with form in jsp and some css in it. I run it on tomcat7
Thats my code:
public class SpittrWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[]{RootConfig.class};
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[] {WebConfig.class};
}
#Override
protected String[] getServletMappings() {
return new String[] {"/"};
}
}
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = "com.springinaction.spittr.web")
public class WebConfig extends WebMvcConfigurerAdapter{
#Bean
public ViewResolver viewResolver(){
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
viewResolver.setViewClass(JstlView.class);
viewResolver.setExposeContextBeansAsAttributes(true);
return viewResolver;
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer){
configurer.enable();
}
}
#Controller
#RequestMapping(value = "/spitter")
public class SpitterController {
#Autowired
public SpitterController(SpitterRepository spitterRepository){
this.spitterRepository = spitterRepository;
}
public SpitterController() {}
#RequestMapping(value = "/register", method = RequestMethod.GET)
public String showRegistrationForm(Model model) {
model.addAttribute(new Spitter());
return "registrationForm";
}
}
Finally jsp page:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib prefix="sf" uri="http://www.springframework.org/tags/form" %>
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Spittr</title>
<style>
div.errors {
backgraund-color: #ffcccc;
border: 2px solid red;
}
label.error {
color: #ffcccc;
}
input.error{
backgraund-color: #ffcccc;
}
</style>
</head>
<br>
<h1>Rejestracja</h1>
<sf:form method="POST" commandName="spitter">
<sf:errors path="*" cssClass="errors" element="div"/>
<sf:label path="firstName" cssErrorClass="error">Imię:</sf:label>
<sf:input path="firstName"/><br/>
<sf:label path="lastName" cssErrorClass="error">Nazwisko:</sf:label>
<sf:input path="lastName"/><br/>
<sf:label path="username" cssErrorClass="error">Nazwa użytkownika: </sf:label>
<sf:input path="username"/><br/>
<sf:label path="email" cssErrorClass="error">Email:</sf:label>
<sf:input path="email" type="email"/><br/>
<sf:label path="password" cssErrorClass="error">Password:</sf:label>
<sf:password element="span" path="password"/><br/>
<input type="submit" value="Zarejestruj"/>
</sf:form>
<hr />
</body>
</html>
My problem is that, when i'am opening website under my browser(doesn't matter which one) just part of css's is loaded. It uses only border: 2px solid red; and color: #ffcccc;. I can't find solution for that problem. Could it be some issue with encoding? I have the same problem when I import css from outside. I even used bootstrap css. Funny thing is that css's worked for some time and unexpectedly stopped.
Any ideas?

Springs 3.6.4 +form bindingerror

// type Exception report
message java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'test' available as request attribute
description The server encountered an internal error that prevented it from fulfilling this request.
HomeController.java
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/** Handles requests for the application home page. */
#Controller
public class HomeController {
private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
/** Simply selects the home view to render by returning its name. */
#RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Model model, Locale locale) {
logger.info("Welcome home! The client locale is {}.", locale);
Date date = new Date();
DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
String formattedDate = dateFormat.format(date);
model.addAttribute("serverTime", formattedDate);
return "home";
}
}
HomeModel.java
package com.test.app;
public class HomeModel {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
HometController.java
package com.test.app;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
#Controller
public class HometController {
#RequestMapping(value = "/try", method = RequestMethod.POST)
public String trynew(#ModelAttribute("test") HomeModel hm, BindingResult br, Model model) {
model.addAttribute("test", new HomeModel());
System.out.println("in try");
return "tst";
}
}
home.jsp
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%# page session="false" %>
<html>
<head>
<title>Home</title>
</head>
<body>
<h1>
Hello world!
</h1>
<P> The time on the server is ${serverTime}. </P>
</body>
<form:form method="POST" modelAttribute="test" name="test" action="try">
<form:input path="name"/>
<input type="submit" value="test"/>
</form:form>
<!-- onClick="document.test.submit()" -->
</html>
tst.jsp
<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Hello World with Spring 3 MVC</title>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1251">
</head>
<body>
<h1>Registration Form</h1><br />
<form:form commandName="USER">
<table>
<form:errors path="*" cssStyle="color : red;"/>
<tr><td>Name : </td><td><form:input path="name" /></td></tr>
<tr><td colspan="2"><input type="submit" value="Save Changes" /></td></tr>
</table>
</form:form>
</body>
</html>
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'test' available as request attribute
remove this parameter #ModelAttribute("test") HomeModel hm to get rid of your exception
#Controller
public class HometController {
#RequestMapping(value = "/try", method = RequestMethod.POST)
public String trynew( BindingResult br, Model model) {
model.addAttribute("test", new HomeModel());
System.out.println("in try");
return "tst";
}
}

How do you query a database from JSP Form Data?

I am in need of assistance. I am trying to write a basic form that populates a drop-down list and based on what you select, it queries the database. However, I cannot get it to do it, It just receives all the queries. I am at a loss so if you have any helpful advice or helpful links, that'd be great. I really need to learn Spring MVC, and Hibernate combined. thanks!
HomeController Code: (This controller populates the list)
/**
* Handles requests for the application home page.
*/
#Controller
public class SearchController {
#Autowired
FilmBo filmBo;
/**
* Simply selects the home view to render by returning its name.
*/
#RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Locale locale, ModelMap model) {
Selection selection = new Selection();
model.addAttribute("selection", selection);
return "search";
}
#ModelAttribute("categoryList")
public List<String> populateList(){
List<String> categoryList = filmBo.searchByCategory("");
return categoryList;
}
}
Here is the MainController that the form upon submit gets sent to:
public class FilmController {
private static final Logger logger = LoggerFactory.getLogger(SearchController.class);
#Autowired
FilmBo filmBo;
#RequestMapping(value = "/films", method = RequestMethod.GET)
public String home(Locale locale, Model model, #RequestParam(value="title",required=false) String title,
#RequestParam(value="category",required=false) String category) {
logger.info("Welcome home! The client locale is {}.", locale);
List<Film> filmList = filmBo.searchByTitle(title);
logger.info("filmList: " + filmList);
model.addAttribute("filmList", filmList);
List<String> filmCategory = filmBo.searchByCategory(category);
logger.info("filmCategory: " + filmCategory);
model.addAttribute("filmCategory",filmCategory);
return "films";
}
}
Here is my jsp page:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%# page session="false"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<div class="form">
<form:form action="${pageContext.request.contextPath}/films"
method="GET" commandName="selection">
Film Title<input type="text" name="title">
<br>
Select a Film Category:<br>
<form:select path="selection">
<form:option value="NONE" label="--- Select ---" />
<form:options name="category" items="${categoryList}" />
</form:select>
<button name="submit" type="submit">Submit Name</button>
</form:form>
</div>
</body>
</html>

Categories

Resources